Refresh Entity in Entity Framework Context with Updated Values

I have an EF object that I pull from db. Then I do the update of the corresponding row in the database through a function call that uses another DBContext . After this update, I would like to reload the contents of the object with the updated contents, however, the contents are cached in the EF context. Here's a sample code (I removed some unbound fluff to make it easier):

 using (UmbrellaEntities context = new UmbrellaEntities()) { var umbrella = (from u in context.Umbrellas where u.umbrellaId == umbrellaId && !u.deleted select u).Single(); int oldVersion = umbrella.Version; updateUmbrellaVersions(); //perform update on table Umbrella using a new `UmbrellaEntities` object. //ideally I'd like to be able to get the updated umbrella.Version without a new call. var umbrella = (from u in context.Umbrellas where u.umbrellaId == umbrellaId && !u.deleted select u).Single(); int newVersion = umbrella.Version; //at this point i expect newVersion to be different from oldVersion, since the value in the db has been updated, but that not the case. } 

I find that I can use the new context to pull out the updated context, but this is inefficient.

 using (UmbrellaEntities context = new UmbrellaEntities()) { var umbrella = (from u in context.Umbrellas where u.umbrellaId == umbrellaId && !u.deleted select u).Single(); int oldVersion = umbrella.Version; updateUmbrellaVersions(); //perform update on table Umbrella using a new `UmbrellaEntities` object. } using (UmbrellaEntities context = new UmbrellaEntities()) { var umbrella = (from u in context.Umbrellas where u.umbrellaId == umbrellaId && !u.deleted select u).Single(); int newVersion = umbrella.Version; //we have the right value } 

Is there a way to reload the content immediately after the update?

+3
source share
1 answer

you can call context.Refresh(RefreshMode.StoreWins,umbrella) to make sure you have the latest version installed.

+4
source

Source: https://habr.com/ru/post/899097/


All Articles