Can someone please explain to me why the Entity Framework 6 cache works the way it does? It makes no sense to me.
As I read it (and experienced), Ef will always query the database - but if the data already exists in the context, then it will use the old data. Why would you do that? Surely this is just creating unnecessary database reads. If you are going to get the data, why would you not always use the most recent version.
https://learn.microsoft.com/en-us/ef/ef6/querying/
When results are returned from the database, objects that do not exist in the context are attached to the context. If an object is already in the context, the existing object is returned (the current and original values of the object's properties in the entry are not overwritten with database values).
Is there a way to get EF6 to update its context when it makes these queries?
EDIT: The reason why refreshing the context is not the solution for me is that it would require several other queries to run for the sake of a single small query. Basically the context is used to fetch several thousand records. The data may change in the background because I have other operations running async in a different context.
I have work arounds, I am just trying to understand why there isnt an easy option to update the data in the context with the information retrieved in a subsequent Where query.
Taking this operation:
_context.Products.Where(x=>categoryid==_categoryid);
var p = _context2.Products.FirstOrDefault(x=>x.ProjectId==1);
p.Description = "New Description";
_context2.SaveChanges();
Now if I run this query
_context.Products.Where(x=>categoryid==_categoryid);
Entity framework will get a data set in which it knows the latest value for product 1 ("New Description"), but it will totally ignore it and just return the value from the original context.
You can:
- Use DbEntry.Reload() - but that requires you to get the entity first, and then reload it - 2 trips
- New context (not a good option for me here)
Is there an option that would do something like the following pseudocode:
_context.BeginUpdateCache();
_context.Products.Where(x=>categoryid==_categoryid);
_context.EndUpdateCache();
which would result in _context.Products.Where(x=>categoryid==_categoryid) returning a set with the latest database value for product 1 - e.g. ("New Description")