首页 > 解决方案 > 实体框架深度克隆/复制实体

问题描述

我想深度克隆,然后像这样保存新的新实体,但是应该更改 PropertyInfo 上的外键 PropertyId 以引用新创建的属性 - 有没有方便的方法来实现这一点?

报告的重复问题没有解决我的问题,它回答了如何深度克隆实体,而不是如何更新关联实体上的 FK。

var originalEntity = Context.Property.Include("PropertyInfo")
                        .AsNoTracking()
                        .FirstOrDefault(e => e.Id == 1);


 Context.Properties.Add(originalEntity);

标签: c#entity-frameworkmodel-view-controller

解决方案


删除主 ID

var originalEntity = Context.Property.Include("PropertyInfo")
                        .AsNoTracking()
                        .FirstOrDefault(e => e.Id == 1);


originalEntity.Id = 0;
//either create propertyinfo or assign propertyinfo
originalEntity.PropertyInfo = createdPropertyInfo || Context.PropertyInfo.First(x => x.Id == idOfFKPropertyInfo);

 Context.Properties.Add(originalEntity);

推荐阅读