官术网_书友最值得收藏!

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;
主站蜘蛛池模板: 府谷县| 大关县| 吉林市| 通化市| 北流市| 图片| 将乐县| 亚东县| 桂阳县| 隆林| 阿拉善盟| 绍兴市| 丹江口市| 哈巴河县| 清水河县| 黑山县| 砀山县| 兴化市| 高州市| 九寨沟县| 新蔡县| 汝阳县| 凤凰县| 彰武县| 乌拉特前旗| 宁夏| 即墨市| 汝州市| 宝清县| 汉沽区| 盐边县| 连云港市| 乡城县| 丹东市| 镇巴县| 远安县| 台北县| 通许县| 泰和县| 米泉市| 东丰县|