Entity Framework Tutorial(Second Edition)
上QQ阅读APP看书,第一时间看更新

Performance improvements in Entity Framework 6

In Entity Framework 6, query performance has been improved a lot. One important performance improvement is in precompiled queries. A compiled query is one that is stored as a parsed tree in memory so that it needn't be regenerated with every subsequent call. You can create compiled queries in two ways: creating an ObjectQuery class with EntitySQL and also using the CompiledQuery.Compile function. Compiling expression trees into SQL every time is an overhead particularly for queries that are complex. This is exactly why compiled queries were introduced.

The earlier versions of Entity Framework contained the CompiledQuery class that you could use to precompile the query and then execute the query as and when needed. So, in essence, when using precompiled queries, the SQL to be executed is figured out only once (during precompilation) and this is then reused each time the compiled query is executed.

Note

Note that if you are using CompiledQuery, you should make sure that you are using the query more than once. This is because it is more costly than querying data the first time.

Now, what were the downsides? You cannot use CompiledQuery using the DbContext API as it only works with ObjectContext. Note that the support for compiled query was revoked from the DbContext API due to some technical limitations. If you use a code-first strategy, you will most likely be opting for the DbContext API. Thankfully, Entity Framework 6 solved this problem, so you no longer need to make this choice.

With Entity Framework 6, you have a feature called auto-compiled queries—this works very different from the way CompiledQuery works. You no longer need to write code to compile each query and then invoke as needed. How does it work then? Entity Framework stores the generated SQL in the cache using a background thread and then as and when needed (based on the calls made), it searches the compiled queries in the cache. This is illustrated in the following image:

Performance improvements in Entity Framework 6

Auto-compiled query in Entity Framework

You can also turn off query caching if you need to. The new ObjectContext.ContextOptions property allows you to control the default behavior of the query compilation. This property is set to true by default, but you can set it to false to turn off the auto-compilation of your queries. Here is an example:

dataContext.ContextOptions.DefaultQueryPlanCachingSetting = false;

If you are using DbContext, you should cast to IObjectContextAdapter, as shown in the following code:

((IObjectContextAdapter)dataContext).ObjectContext.ContextOptions.DefaultQueryPlanCachingSetting = false;