Reload object in an Entity Framework context with updated values

允我心安 提交于 2019-12-10 19:10:15

问题


I have an EF object that I pull from the db. I then make an update to the corresponding row in the DB through a function call which uses another DBContext. After this update, I would like to reload the contents of the object with the updated contents, however the EF context seems to cache the contents. Here's a sample of the code(I've removed some unrelated fluff to make it simpler):

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's not the case.
}

I find that I can use a new context to pull 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 contents directly after I perform the update?


回答1:


you should be able to call context.Refresh(RefreshMode.StoreWins,umbrella) to make sure you have the latest version.



来源:https://stackoverflow.com/questions/7639219/reload-object-in-an-entity-framework-context-with-updated-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!