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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With