我从DbContext得到以下错误:“违反了多重约束.关系”MyModel.FK_ChildEntities_MyEntities“的角色”MyEntity“具有多重性1或0..1.
使用ASP.NET,实体框架4
使用独立实体
该错误发生在我第二次尝试重新连接一个实体到dbcontext.该方案是一个不成功的保存,然后是重新尝试.
我在会话中有一个分离的实体.用户更改表单中的属性,添加内容,删除内容,最终点击保存.我从dbcontext的一个新实例中获取实体的附件副本,将更改从分离的实体应用到附加实体,验证,查找错误并中止.用户更改任何内容并再次保存.
第二个保存,整个保存过程重复,只有这一次,所有这一切都到了.几乎所有的东西都被重复,造成一个错误或者其他的或全部的错误.来自视图和查找表的仅作为引用的值将创建新的和重新分配的id.大多数这些问题我已经能够解决,但我遗留了多重错误.正在创建子元素作为其他子元素的精确副本,直到唯一的ID,仅在添加状态.或者,如果我引用某些属性,而不是克隆未修改的小孩,它会删除新的.无论哪种方式,代码都没有像第一次那样执行.
我抛弃了dbcontext和附件实体的实例,每次保存尝试.我认为这足以恢复任何变化,但必须坚持的事情.唯一没有被忽略或重置的是分离的实体,这是在会话中,但我没有对其进行任何更改.至少不是直接
代码(非常简化)是这样的:
void Save() { using (var context = new MyContext()) { // detached entity from session MyEntity detachedEntity = (MyEntity)Session["DetachedEntity"]; // attached entity from context MyEntity attachedEntity = context.MyEntities.Single(x=>x.id == detachedEntity.id); // <remove children representing lookup table elements from detachedEntity to prevent duplicates> // <remove children representing view elements from detachedEntity to prevent duplicates> // <apply changes from detachedEntity to attachedEntity> // <add new children> // <remove deleted children> // <update modified children> // <set entity state to unchanged on view and lookup elements of attachedEntity to ensure no duplicates...> // <validate> if (errors.count>0) // <report errors> else context.SaveChanges(); } }
作为示例,这会产生多重错误:
// represents first save: using (var context = new MyContext()) { // detached entity from session MyEntity detachedEntity = (MyEntity)Session["DetachedEntity"]; // attached entity from context MyEntity attachedEntity = context.MyEntities.Single(x=>x.id == detachedEntity.id); int debug1 = context.ChangeTracker.Entries<ChildEntity>().Count(); // debug1 == 0; attachedEntity.ChildEntities.Add(detachedEntity.ChildEntities.First()); int debug2 = context.ChangeTracker.Entries<ChildEntity>().Count(); // debug2 == 1; } // represents second save: using (var context = new MyContext()) { // detached entity from session MyEntity detachedEntity = (MyEntity)Session["DetachedEntity"]; // attached entity from context MyEntity attachedEntity = context.MyEntities.Single(x=>x.id == detachedEntity.id); int debug1 = context.ChangeTracker.Entries<ChildEntity>().Count(); // debug1 == 0; attachedEntity.ChildEntities.Add(detachedEntity.ChildEntities.First()); int debug2 = context.ChangeTracker.Entries<ChildEntity>().Count(); // multiplicity error; }
解决方法
不知何故,dbcontext会记住添加了什么对象.如果完全相同的对象出现两次,则会发生爆炸
而不是将我的独立实体中的子实体添加到附加的实体,我应该创建每个小孩的新副本
ChildEntity detachedChild = detachedEntity.ChildEntities.First(); attachedEntity.ChildEntities.Add(new ChildEntity { propertyA = detachedChild.propertyA,propertyB = detachedChild.propertyB });
代替
attachedEntity.ChildEntities.Add(detachedEntity.ChildEntities.First());