Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

c# - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...