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

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;
主站蜘蛛池模板: 万山特区| 日土县| 涟源市| 新民市| 贵阳市| 阳西县| 屯留县| 泾源县| 准格尔旗| 罗平县| 浦县| 灵寿县| 云龙县| 刚察县| 太原市| 名山县| 樟树市| 大英县| 高要市| 齐齐哈尔市| 酒泉市| 霍邱县| 金乡县| 盐城市| 尉犁县| 墨玉县| 慈利县| 松溪县| 庄浪县| 老河口市| 湟中县| 新绛县| 东阿县| 通道| 类乌齐县| 武夷山市| 北京市| 上栗县| 巩留县| 舟山市| 博野县|