When working with LINQ to Entities, Entity Framework has to parse the expression tree from the LINQ query and convert it to SQL. It is possible to save the output of this using CompiledQuery, but this is something that you have to manually code. One of the new features coming in Entity Framework 5 (EF5) is automatic query compilation (see here) and it is enabled it by default. For repeated queries this can bring some nice performance improvements (as demonstrated here).

The posts from the EF team show how to control the caching by setting context.ContextOptions.DefaultQueryPlanCachingSetting = false. In the Release Candidate for EF5 this property is no longer there. Instead, you need to set the EnablePlanCaching property on the ObjectSets. As an example, consider the following simple query:

 

var query1 = from customer in context.Customers
                where customer.Country == "UK"
                select customer;

In this query, context.Customers is the ObjectSet. To disable caching we need to set the EnablePlanCaching property as shown below:

 

ObjectQuery<Customer> customersNoCache = context.Customers;
customersNoCache.EnablePlanCaching = false;
var query1 = from customer in context.Customers
                    where customer.Country == "UK"
                    select customer;

Personally, this feels like quite a lot of noise that gets in the way of the query. To solve this I created a little extension method that means we can now write the query as

var query1 = from customer in context.Customers.DisablePlanCaching()
                where customer.Country == "UK"
                select customer;

 

The extension methods to achieve this are really pretty simple:

public static class ObjectQueryExtensions
{
    public static ObjectQuery<T> DisablePlanCaching<T>(this ObjectQuery<T> query)
    {
        query.EnablePlanCaching = false;
        return query;
    }
    public static ObjectQuery DisablePlanCaching(this ObjectQuery query)
    {
        query.EnablePlanCaching = false;
        return query;
    }
}

 

Enjoy!

Original Post by Stuart Leeks on June 12th, 2012

Here: http://blogs.msdn.com/b/stuartleeks/archive/2012/06/12/entity-framework-5-controlling-automatic-query-compilation.aspx