entity-framework - 自加载实体以来,实体可能已被修改或删除

标签 entity-framework concurrency task-parallel-library

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

不幸的是,我收到了 OptimisticConcurrencyException 并且无法弄清楚是哪个实体是问题并且需要刷新?有没有办法找出导致 OptimisticConcurrencyException 的实体?此消息根本没有帮助...

System.Data.Entity.Infrastructure.DbUpdateConcurrencyException: Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries. ---> System.Data.OptimisticConcurrencyException: Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.

最佳答案

也许最好的解决方案是创建一个新的 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);
    }

关于entity-framework - 自加载实体以来,实体可能已被修改或删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16925420/

相关文章:

entity-framework - EF - 如何使用流畅的 EntityTypeConfiguration API 定义正则表达式属性?

c# - 更新 Entity Framework 6 中 foreach 循环中的记录

multithreading - 条件变量的成本是多少?

c# - 使用任务进行连续轮询

.net - 从组织上讲,在使用 Entity Framework Code First 时,我应该将常见查询放在哪里?

asp.net - Asp.Net MVC 3 应用程序中复杂子对象的集合?

scala - 使用 future 时程序不会终止

ruby-on-rails - 如何使用 puma 正确处理 rails 中的并发?

c# - 异步调用并行 for 循环

c# - 使用这种异步日志记录代码有什么缺点?