views:

59

answers:

2

My understanding of the Entity Framework is that if it can answer a query from its cache, it will. My simple testing, however, shows repeated queries hit the database even though they were previously answered positively:

var u1 = context.Users.SingleOrDefault(u => u.Id == 1);
var u2 = context.Users.SingleOrDefault(u => u.Id == 1);

These queries are successful. For each, I see a SELECT TOP (2) in SQL Profiler.

Why does EF go to the database for that second query?

+2  A: 

Well, because EF doesn't use caching. nHibernate does. Here article on how to enable caching with EF.

Edit: EF doesn't have transparent out-of-the-box cache. But it has explicit cache within unit of work: ObjectContext.GetObjectByKey

Andrey
Well that's a fly in the ointment. Thanks for the info, and a link to a solution!
ladenedge
That's not entirely true. I think you're confusing the EF and L2E. LINQ to Entities doesn't use caching by default, but the EF *does* cache materialized instances in its context. Try, e.g., `ObjectContext.GetObjectByKey`
Craig Stuntz
@Craig Stuntz i meant transparent cache (like what ladenedge meant).
Andrey
I did indeed mean transparent caching, but I wonder: is there a way to query the EF cache? Either way, is it more appropriate to go with a caching provider as in Andrey's link?
ladenedge
@Andrey, I understand what you *mean*, but I was responding to what you *wrote.* EF and L2E are not the same thing! @ladenedge, if you need a cache which lasts longer than a unit of work, then yes, you want a caching provider. If you want cached objects *within* a unit of work, as with your example in your question, then use `GetObjectByKey`.
Craig Stuntz
@Craig Stuntz i edited answer so it is more complete
Andrey
+2  A: 

EF always executes query but returns the same instance of the object. Second query is not materialized into the new object instead instance created by the first query is returned. Here is the article about that behavior. There are some aditional concepts which can force second query for example to update existing instance.

Ladislav Mrnka
Nice article, thank you!
ladenedge