![](/img/trans.png)
[英]Handle Optimistic Concurrency in SQL Server with EF Core - when updating child, how to update the parent?
[英]Optimistic Concurrency while Updating Records in EF 4
在VS 2012中调试时收到此异常
具有相同键的对象已存在于ObjectStateManager中。 ObjectStateManager无法使用相同的键跟踪多个对象。
//_dbSet declaration:
private readonly IDbSet<T> _dbSet;
//Method parameter
public virtual void Update(T entity)
//method fragment
public virtual void Update(T entity)
{
if (Entities == null) return;
var entry = Entities.Entry(entity);
switch (entry.State)
{
case EntityState.Modified:
var currentValues = entry.CurrentValues.Clone();
entry.Reload();
switch (entry.State)
{
case EntityState.Detached:
Entities.Entry(entry).State = EntityState.Modified;
break;
default:
entry.Reload();
entry.CurrentValues.SetValues(currentValues);
break;
}
break;
case EntityState.Detached:
_dbSet.Attach(entity); /*Here is the thing*/
entry.CurrentValues.SetValues(entity);
break;
}
Entities.Commit();
}
我花了将近一个星期的时间来尝试使用以下模式来解决乐观并发:DbFactory,工作单元,DI,通用存储库,但没有得到结果。
我认为异常消息很清楚:
具有相同键的实体(即,映射到相同数据库记录的实体)已经加载并附加在目标DbSet
。
在这种情况下,您决定做什么完全取决于您:
entity
实例(或更复杂的事物); entity
。 代码难闻;
第一个switch
语句使用entry.State
并检查实体是处于修改状态还是处于分离状态; 然后在修改后的情况下,将创建一个新的switch语句来检查实体是否已分离或处于其他状态。
异常没有说明乐观并发性。 相反,它指出您正在尝试将实体附加到对象上下文,并且上下文中已经存在具有相同键的实体。
我要感谢所有人,他们将宝贵的时间花在了我的头上。 这是一篇新文章,阐明了我对通用存储库模式中的并发更新方法的最终解决方案。 多亏了本文,一切都没有丢失: 按属性寻找实体的键
那非常有用: RoccoC5
private object GetKeyValue(T entity)
{
var key =
typeof(T).GetProperties().FirstOrDefault(
p => p.GetCustomAttributes(typeof(KeyAttribute), true).Length != 0);
return (key != null) ? key.GetValue(entity, null) : null;
}
公共虚拟无效Update(T实体){如果(实体== null)返回;
var key = GetKeyValue(entity);
var originalEntity = _dbSet.Find(key);
Entities.Entry(originalEntity).CurrentValues.SetValues(entity);
Entities.Commit();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.