Some previous code I had written used the Find()
method to retrieve single entities by their primary key:
return myContext.Products.Find(id)
This worked great because I had this code tucked into a generic class, and each entity had a different field name as its primary key.
But I had to replace the code because I noticed that it was returning cached data, and I need it to return data from the database each call. Microsoft's documentation confirmed this is the behavior of Find()
.
So I changed my code to use SingleOrDefault
or FirstOrDefault
. I haven't found anything in documentation that states these methods return cached data.
Now I am executing these steps:
- Save an entity via EF.
- Execute an UPDATE statement in SSMS to update the recently saved record's Description field.
- Retrieve the entity into a new entity variable using
SingleOrDefault
orFirstOrDefault
.
The entities being returned still have the old value in the Description
field.
I have run a SQL trace, and verified that the data is being queried during step 3. This baffles me - if EF is making a round trip to the database, why is it returning cached data?
I've searched online, and most answers apply to the Find()
method. Furthermore, they suggest some solutions that are merely workarounds (dispose the DbContext
and instantiate a new one) or solutions that won't work for me (use the AsNoTracking()
method).
How can I retrieve my entities from the database and bypass the EF cache?
DbContext
object should be scoped and have a very short lifespan (like for only the life of one HTTP request). In such a short time, there isn't a reason to go back to the database to get the same record twice. I suspect yourDbContext
object has been alive too long.