Reputation: 6518
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
Context.Set<B>().AsNoCache().ToList();
which we do not have...
Upvotes: 1
Views: 2144
Reputation: 6518
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();
Upvotes: 0
Reputation: 16498
If you're looking to update an existing list of entities with possibly updated values from the DB, you can use ObjectContext
's Refresh method:
// what to refresh
// this will refresh all cached instances of B entities
var entitiesToRefresh = dbContext.Set<B>().Local;
var objectContext = ( ( IObjectContextAdapter )dbContext ).ObjectContext;
objectContext.Refresh( RefreshMode.StoreWins, entitiesToRefresh );
Note this will not load new entities from the DB if there should items added to the list - you would need to requery for those items.
Upvotes: 1