Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cached Queries with Entity Framework 5

I understand that EF 5 will automatically cache the queries, but does it do it per context or overall? We are using MVC and are wrapping the calls in a using block to dispose of the dbcontext. For example:

public class Employee
{
    public string FirstName {get; set;}
    public string LastName {get; set;}
    public int ID {get; set;}
}

public class EmployeeQueryByFirstName : IQueryObject<Employee>
{
     private string _firstName;

     public void Set(string FirstName)
    {
         _firstName = FirstName;
    }

     public Expression<Func<Employee,bool>> AsExpression()
    {
        return (e=>e.FirstName == this._firstName);
    }
}

public class RepoExcerpt
{
    public TEntity Find<TEntity>(IQueryObject<TEntity> queryObject)
        where TEntity : class
    {
        using (var conn = ServiceLocator.IOC.Resolve<IDbContext>())
        {
            var query = (from q in conn.Set<TEntity>()
                        select q);
            query = query.Where(queryObject.AsExpression());
            return query.FirstOrDefault();
        }
    }
}

The next time we call Find on the repository, will EF 5 have a cached version of this query, or will it be gone because we will be getting a new dbcontext? And if I want cached queries, will I need to handle that?

like image 201
CharlesNRice Avatar asked Dec 04 '12 15:12

CharlesNRice


2 Answers

The queries are cached overall so you can safely create and dispose the DbContext instance for each request. This is my preffered approach anyway.
Microsoft documentation can be found here - see section 3.2 Query Plan Caching.

like image 121
Alex Pop Avatar answered Sep 30 '22 17:09

Alex Pop


From Microsoft:

By default, query plan caching is enabled for Entity SQL queries, whether executed through an EntityCommand or through an ObjectQuery. It is also enabled by default for LINQ to Entities queries in Entity Framework on .NET 4.5, and in Entity Framework 6

And no, you don't have to hold onto the same context for the caching to work. Note that only the query itself (i.e. the SQL that gets compiled via the Entity Framework) is cached, and by default this (cached) query will still be run against the DB each time the data is requested.

like image 33
Chris Halcrow Avatar answered Sep 30 '22 17:09

Chris Halcrow