使用实体框架5的缓存查询

Cha*_*ice 13 linq-to-entities caching asp.net-mvc-4 entity-framework-5

我知道EF 5会自动缓存查询,但是它是按照上下文还是整体来做的?我们正在使用MVC并将调用包装在using块中以处理dbcontext.例如:

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

下次我们调用Find存储库时,EF 5会有这个查询的缓存版本,还是会因为我们将获得一个新的dbcontext而消失?如果我想要缓存查询,我需要处理吗?

Ale*_*Pop 6

查询将进行整体缓存,因此您可以安全地为每个请求创建和处置DbContext实例.无论如何,这是我的优先方法.
可以在此处找到Microsoft文档- 请参阅3.2查询计划缓存一节.