简体   繁体   English

查询实体框架缓存

[英]Query about Entity Framework caching

Lets say I have these three methods: 可以说我有以下三种方法:

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; }
}

Would this cause a query to the database each time I make a call to GetCustomerByEmailAddress() / GetCustomerByCustomerGuid() or would EF cache the results of GetCustomer() and query that for my information? 每次我调用GetCustomerByEmailAddress() / GetCustomerByCustomerGuid() ,都会导致对数据库的查询吗?还是EF会缓存GetCustomer()的结果并查询我的信息?

On the other hand, would it just cache the result of each call to GetCustomerByEmailAddress() / GetCustomerByCustomerGuid() 另一方面,它是否只是缓存对GetCustomerByEmailAddress() / GetCustomerByCustomerGuid()的每次调用的结果

I am trying to establish the level of manual caching I should go to, I really dislike running more SQL queries than are absolutely necessary. 我正在尝试建立应该去的手动缓存级别,我真的不喜欢运行比绝对必要更多的SQL查询。

Yes, it'll query the database every time. 是的,它每次都会查询数据库。

Your concern should be to optimize your code so that it only queries for and returns the record you need. 您应该关注的是优化代码,使其仅查询并返回所需的记录。 Right now it's pulling back the entire table and then you're filtering it with FirstOrDefault() . 现在,它正在拉回整个表,然后使用FirstOrDefault()对其进行过滤。

Change public IEnumerable<Customer> GetCustomers() to public IQueryable<Customer> GetCustomers() to make it more efficient. public IEnumerable<Customer> GetCustomers()更改为public IQueryable<Customer> GetCustomers() ,以提高效率。

It will result in a call to the database every time. 每次都会导致对数据库的调用。 I actually asked a similar question earlier today and you can see more here: Why does Entity Framework 6.x not cache results? 我实际上在今天早些时候问过类似的问题,您可以在此处看到更多信息: 为什么Entity Framework 6.x不缓存结果?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM