Entity Framework 6 - Uncached data with dependency injection

c# caching dependency-injection entity-framework-6


I recently discovered the hard way that EF does caching. I have a root viewmodel that creates the initial DbContext. With every other viewmodel that gets created, I pass that context over. That way, I only have one connection, and I have dependency injection.

I have a function in one of the viewmodels that changes a state one of the entities. When I get attempt to get the entity back from the database, the status remains unchanged (I'm assuming this is due to caching).

All the other posts I've found (that's for EF 6), wants to create a NEW instance of the class, like this :

var context = new MyContext();

Which would work, but it would prevent me from having only one connection, and also eliminate my dependency injection.

Is there any other way of getting the true value of the entity?

8/26/2018 3:51:05 PM

Accepted Answer

This is a known issue with long lived contexts and entity tracking system.

The DbEntityEntry class provides several methods to refresh the cached entity data - Reload, GetDatabaseValues, as well as detaching the entity from the change tracker (hence the cache) by setting the State to Detached. But they are applicable for single entity known in advance.

Also the old ObjectContext services provided a way to choose the query behavior via MergeOption enumeration - AppendOnly, OverwriteChanges, PreserveChanges and NoTracking. But all they are gone in DbContext services and the only remaining option is no tracking queries.

So anytime you want to be sure you'll get the actual database state, consider utilizing the no tracking queries by using .AsNoTracking() extension method. Just keep in mind that the returned entities are basically disconnected, so modifying them and applying the modifications back would be hard and can lead to exceptions like there is already entity tracked with the same key etc.

8/26/2018 3:30:04 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow