开发者

Reload object in an Entity Framework context with updated values

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
              开发者_StackOverflow社区          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?


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜