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

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;
主站蜘蛛池模板: 金平| 德州市| 铜山县| 阳东县| 台安县| 呼伦贝尔市| 新河县| 东兴市| 尤溪县| 西乌珠穆沁旗| 乐亭县| 元朗区| 海阳市| 武乡县| 株洲县| 西城区| 凌云县| 满城县| 于都县| 余庆县| 长治市| 周口市| 秦皇岛市| 海丰县| 桐梓县| 曲水县| 观塘区| 扎鲁特旗| 张家界市| 宿州市| 社会| 泽州县| 怀来县| 康保县| 镇远县| 甘泉县| 毕节市| 龙山县| 江陵县| 甘南县| 军事|