Query about Entity Framework caching

2019-08-30 13:51发布

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?

On the other hand, would it just cache the result of each call to 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.

2条回答
在下西门庆
2楼-- · 2019-08-30 14:12

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().

Change public IEnumerable<Customer> GetCustomers() to public IQueryable<Customer> GetCustomers() to make it more efficient.

查看更多
男人必须洒脱
3楼-- · 2019-08-30 14:29

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?

查看更多
登录 后发表回答