DbContext cached data

entity-framework entity-framework-6


I read everywhere that the proper way to get fresh data from the database is to create a new instance of DbContext, and drop the existing. While this may be obvoius for some scenarios, I am finding difficulties to implement this in a more complex scenrario. The type of application in question is client app, where context lives as long as the form/view is displayed.

For example, imagine that we are adding some data of type A (this is the main data), and a specific instance of type A references objects of type B and C (this is the data referenced by ). This means that on the screen I could have loaded list of A, list of B and list of C. Lets say that list of B has received some changes on the network, that I would like to load. How can I refresh the list of B, without the need to fetch all three lists from database (because if I destroy the context, that is what I will need to do?

obvoius mehod would be somethin like


which we do not have...

12/17/2013 1:06:04 AM

Accepted Answer

During the tests I discovered that the only method that refresh data with the current records from the database (added, updated and deleted) is to use ObjectContext's ObjectSet and set MergeOption to OverwriteChanges (DbContext does not expose such a method).

var objectContext = ((IObjectContextAdapter)Context).ObjectContext;
ObjectSet<T> set = objectContext.CreateObjectSet<T>();
set.MergeOption = MergeOption.OverwriteChanges;
var list = set.ToList();
12/20/2013 12:36:58 AM

Popular Answer

The method you're looking for is here


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