Database Reference
In-Depth Information
proxy classes can be troublesome in n-tier scenarios where you need to serialize data to send to another
physical tier, such as to a WCf or to a Web apI client. See recipe 9-7 for more detail.
Note
13-6. Auto-Compiling LINQ Queries
Problem
You want to improve the performance of queries that are reused several times, and you would like to achieve this
performance upgrade with no additional coding or configuration.
Solution
Let's say that you have a model like the one shown in Figure 13-8 .
Figure 13-8. A model with an Associate and its related Paycheck
In this model, each Associate has zero or more paychecks. You have a LINQ query that is used repeatedly
throughout your application, and you want to improve the performance of this query by compiling it just once and
reusing the compiled version in subsequent executions.
When executing against a database, Entity Framework must translate your strongly typed LINQ query to a
corresponding SQL query, based upon your database provider (SQL Server, Oracle, and so on). Beginning with
version 5 of Entity Framework, each query translation is cached by default. This process is referred to as auto-caching.
With each subsequent execution of a given LINQ query, the corresponding SQL query is retrieved directly from
query plan cache, bypassing the translation step. For queries containing parameters, changing parameter values will
still retrieve the same query. Interestingly, this query plan cache is shared among all instances of a context object
instantiated with the application's AppDomain, meaning that, once cached, any context object in the AppDomain has
access to it.
In Listing 13-10, we compare performance with caching enabled and then disabled. To illustrate the performance
benefit, we've instrumented the code in Listing 13-10 to print the number of ticks for each of ten iterates taken for
both the uncompiled and the compiled versions of the LINQ query. In this query, we can see that we get roughly a
2X performance boost. Most of this, of course, is due to the relatively high cost of compiling versus the low cost for
actually performing this simple query.
 
 
Search WWH ::




Custom Search