3

I was sure that issuing a FirstOrDefault() on entity framework will issue a query on the database and to hit cache I can use .Find().

But helping a colleague debug a problem in EF4.2 (query data didn't reflect the db data, and query wasn't in the sql profiler) got me to the solution that works. So use ".AsNoTracking()", and I later found other posts here that states:

" The following will sometimes pull from the EF cache" : .FirstOrDefault();

And another post with same issue: here

If you go to msdn:

By default when an entity is returned in the results of a query, just before EF materializes it, the ObjectContext will check if an entity with the same key has already been loaded into its ObjectStateManager. If an entity with the same keys is already present EF will include it in the results of the query. Although EF will still issue the query against the database, this behavior can bypass much of the cost of materializing the entity multiple times. .........

Unlike a regular query, the Find method in DbSet (APIs included for the first time in EF 4.1) will perform a search in memory before even issuing the query against the database.

And other SO posts: here and here seem to support msdn?

So how does EF object caching behave?

  • always hits DB except for .FirstOrDefault() when it works only sometimes (black box) so it's better to use .AsNoTracking().FirstOrDefault() just to be sure?
  • I should expect similar issues with other methods like: First(), Single(), SingleOrDefault()
1
  • 1
    I think the distinguishing feature here is whether you're issuing a query by primary key. Commented Oct 12, 2015 at 13:46

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.