我在它们自己的上下文中执行代码,但这导致数据在主线程上下文中不同步。所以我需要在其他上下文完成工作后刷新实体,然后才能更新它。
不幸的是,我收到了 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/