首页 文章

如何深度克隆实体并避免导航属性导致的错误?

提问于
浏览
3

我的实体上的导航属性导致我的深度克隆失败,并显示错误:

“ObjectStateManager中已存在具有相同键的对象”

背景:

用户希望能够克隆父记录及其所有关联的子记录 . 我可以使用这个简单的技术单独克隆父实体(没有错误):

_context.Detach(currentParentEntity);
_context.AddToParentEntities(currentParentEntity);
_context.SaveChanges();

我发现了解决方案和另一种工作浅层克隆技术(来自diamandiev)here .

由于我真正需要的是深拷贝,我尝试实现hereherehere所示的序列化克隆技术 . 我的调用代码如下所示:

ParentEntity clonedParentEntity = (ParentEntity)DeepClone(currentParentEntity);
_context.Detach(currentParentEntity);
clonedParentEntity.EntityKey = null;
_context.AddToParentEntities(clonedParentEntity);
_context.SaveChanges();

此代码仅在克隆没有子实体的currentParentEntity时使用(在导航属性中引用) . 如果孩子存在,我会收到"object with the same key already exists"错误 . 为什么? How can I deep clone both a parent entity and it's associated child entities then save the cloned record without any errors?

提前致谢 .

编辑:对于完整接受的答案阅读Ladislav Mrnka的回答 plus the comments .

1 回答

  • 2

    如果你真的使用了序列化,你克隆了父实体和子实体 - 这不是你的问题 . 您的问题是调用 Detach ,因为它只会删除您要分离的单个实体(而不是其子代) . 因此,错误是由添加具有上下文已跟踪的相同键的子项引起的 .

相关问题