【问题标题】:Reload object in an Entity Framework context with updated values在具有更新值的实体框架上下文中重新加载对象
【发布时间】:2011-10-03 18:41:54
【问题描述】:

我有一个从数据库中提取的 EF 对象。然后我通过使用另一个DBContext 的函数调用对数据库中的相应行进行更新。在此更新之后,我想用更新的内容重新加载对象的内容,但是 EF 上下文似乎缓存了这些内容。 这是代码示例(我删除了一些不相关的绒毛以使其更简单):

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.
}

我发现我可以使用新的上下文来拉取更新的上下文,但这效率低下。

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
}

有没有办法在我执行更新后直接重新加载内容?

【问题讨论】:

  • 为什么要使用不同的 dbcontext?
  • 你的意思是为什么我在函数updateUmbrellaVersions 中使用新的上下文而不是在此处移动更新代码或将dbContext 传递给更新函数?更新代码调用我无法更改其 API 的服务。

标签: .net entity-framework entity-framework-4


【解决方案1】:

您应该可以致电context.Refresh(RefreshMode.StoreWins,umbrella) 以确保您拥有最新版本。

【讨论】:

  • 这似乎有效,但据我所知,它不会重新加载实体列表属性(例如外键数据)
猜你喜欢
  • 1970-01-01
  • 2016-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多