webnoob
webnoob

Reputation: 15934

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?

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.

Upvotes: 0

Views: 1564

Answers (2)

Anthony Chu
Anthony Chu

Reputation: 37540

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.

Upvotes: 4

Adam Modlin
Adam Modlin

Reputation: 3024

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?

Upvotes: 1

Related Questions