【问题标题】:Entities may have been modified or deleted since entities were loaded自加载实体后,实体可能已被修改或删除
【发布时间】:2013-05-31 07:07:30
【问题描述】:

我在它们自己的上下文中执行代码,但这会导致数据在主线程上下文中不同步。因此,我需要在其他上下文完成工作后刷新实体,然后才能对其进行更新。

不幸的是,我收到了一个 OptimisticConcurrencyException 并且无法确定是哪个实体存在问题并且需要刷新?有没有办法找出是哪个实体导致了 OptimisticConcurrencyException?这条消息一点用都没有……

System.Data.Entity.Infrastructure.DbUpdateConcurrencyException:存储 更新、插入或删除语句影响了意外数量的 行 (0)。实体可能已被修改或删除,因为实体 被加载。刷新 ObjectStateManager 条目。 ---> System.Data.OptimisticConcurrencyException:存储更新、插入或 删除语句影响了意外数量的行 (0)。实体 自加载实体以来可能已被修改或删除。刷新 ObjectStateManager 条目。

【问题讨论】:

  • 或许,DbUpdateConcurrencyException.Entries 属性可以帮助检测未保存的实体。

标签: entity-framework concurrency task-parallel-library


【解决方案1】:

也许最好的解决方案是在其他线程完成后在主线程上下文中创建一个新的context。

否则,如果您需要重用context,这里有一个方便的方法来刷新您的上下文对象。

    public void RefreshAll()
    {
        // Get all objects in state manager with entityKey
        // (context.Refresh will throw an exception otherwise)
        var refreshableObjects = (from entry in
                ObjectContext.ObjectStateManager.GetObjectStateEntries(
                                                    EntityState.Deleted
                                                  | EntityState.Modified
                                                  | EntityState.Unchanged)
                                  where entry.EntityKey != null
                                  select entry.Entity);

        ObjectContext.Refresh(RefreshMode.StoreWins, refreshableObjects);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-20
    • 1970-01-01
    相关资源
    最近更新 更多