23 October 2012

Entity Framework 5 performance improvements for testable applications

    Earlier this year I wrote a series of posts about how to automate Entity Framework(EF) testing but since then a lot of things happened: EF 5 was released, it was made open source and Microsoft has published an in-depth article about performance tweaks for older versions of EF and performance improvements in EF 5. Following these events I can now expand my previous post and address an important performance consideration around the EF testable interface that I described earlier.

    A common and ugly sight for any application that uses EF in production is the explosion of horrendous CompiledQuery static code constructs: for any Linq to EF query that is called often within your application you have to create a Compiled Query instance to ensure its query plan is cached and to benefit from the extra performance that comes with this change. But CompileQuery objects are suited for the old style EF context class ObjectContext - they are not available for the new DbContext EF context class introduced in EF 4.1. This means that if your application has a lot of chatty database calls you are stuck with ObjectContext because you really need to use those CompiledQuery instances. And this also means you cannot actually do unit testing in this scenario... at least not until EF 5 was released.

    With EF 5 and .NET 4.5 you benefit from automatic compilation of Linq to EF queries. This brings a major boost in performance for all EF models, removes the need for all those ugly CompiledQuery instances and makes the DbContext class (finally) a worthy replacement for the old ObjectContext class. And yes it means that you can use the IDbContext interface and benefit from unit testing the EF model if this is what your application needs.


No comments: