查询实体框架缓存

时间:2014-02-11 22:40:22

标签: c# asp.net-mvc entity-framework caching asp.net-mvc-5

让我们说我有这三种方法:

public Customer GetCustomerByCustomerGuid(Guid customerGuid)
{
    return GetCustomers().FirstOrDefault(c => c.CustomerGuid.Equals(customerGuid));
}

public Customer GetCustomerByEmailAddress(string emailAddress)
{
    return GetCustomers().FirstOrDefault(c => c.EmailAddress.Equals(emailAddress, StringComparison.OrdinalIgnoreCase));
}

public IEnumerable<Customer> GetCustomers()
{
    return from r in _customerRepository.Table select r;
}

//_customerRepository.Table is this:
public IQueryable<T> Table
{
    get { return Entities; }
}

每次调用GetCustomerByEmailAddress() / GetCustomerByCustomerGuid()时,这会导致对数据库的查询,还是EF会缓存GetCustomer()的结果并查询该信息?

另一方面,它是否只会将每次调用的结果缓存到GetCustomerByEmailAddress() / GetCustomerByCustomerGuid()

我正在尝试建立我应该去的手动缓存级别,我真的不喜欢运行更多的SQL查询而不是绝对必要的。

2 个答案:

答案 0 :(得分:4)

是的,它每次都会查询数据库。

您应该关注优化代码,以便它只查询并返回您需要的记录。现在它正在拉回整个表格,然后你用FirstOrDefault()过滤它。

public IEnumerable<Customer> GetCustomers()更改为public IQueryable<Customer> GetCustomers()以提高效率。

答案 1 :(得分:1)

每次都会导致对数据库的调用。我今天早些时候问了一个类似的问题,你可以在这里看到更多:Why does Entity Framework 6.x not cache results?