Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load changes made in another DbContext

I have a WPF app that has a grid with a list of data that I loaded with EF. Some other window can make changes to the same data loaded on the grid but using a different dbcontext instance. How can I see the changed data on the grid? I know I can refresh a single entity with ctx.Entry<MyEntity>(instance).Reload(); - but I want to see all the changes and no matter what I do, I only see the old values. I can't use AsNoTracking neither create a new DbContext instance in this case.

like image 885
user1526627 Avatar asked Sep 03 '12 10:09

user1526627


1 Answers

To me looks like a very simple case and I cannot see why EF don't just update the values of the entities.

EF has this mechanism as well but it is not exposed on DbContext API. You need to get back to ObjectContext. If you just want to reload set of entities you will call:

var objectContext = ((IObjectContextAdapter)dbContext).ObjectContext;
objectContext.Refresh(RefreshMode.StoreWins, listOfEntitiesToReload);

RefreshMode.StoreWins causes all pending changes to be overwritten by reloaded values. You can also use RefreshMode.ClientWins which will keep your changes and merge them with reloaded data. The problem with this approach is that it only reloads entities you already have. You will not get new entities.

If you want to get new entities as well you must execute a query and you must tell EF that you want to reload values:

var objectContext = ((IObjectContextAdapter)dbContext).ObjectContext;
var objectSet = objectContext.CreateObjectSet<MyEntity>();
objectSet.MergeOption = MergeOption.OverwriteChanges;
var result = objectSet.Where(...).ToList();

Again MergeOption.OverwriteChanges overwrites all pending changes but you can use MergeOption.PreserveChanges to merge reloaded values to your edited values.

I think there can be still some issues with refreshing values with some relations and maybe also entities which were deleted in the database.

like image 125
Ladislav Mrnka Avatar answered Nov 05 '22 12:11

Ladislav Mrnka