c# - 实体框架深度克隆/复制实体
问题描述
我想深度克隆,然后像这样保存新的新实体,但是应该更改 PropertyInfo 上的外键 PropertyId 以引用新创建的属性 - 有没有方便的方法来实现这一点?
报告的重复问题没有解决我的问题,它回答了如何深度克隆实体,而不是如何更新关联实体上的 FK。
var originalEntity = Context.Property.Include("PropertyInfo")
.AsNoTracking()
.FirstOrDefault(e => e.Id == 1);
Context.Properties.Add(originalEntity);
解决方案
删除主 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);
推荐阅读
- android - 如果没有互联网访问,如何在 WebView 中添加网络错误消息
- salesforce - 当事件和处理程序在不同的组件中时,如何测试组件事件?
- python - 如何通过 Python API 获取数据集信息
- python - spyder plotly:绘制条形图的问题
- javascript - Rewriting function using arrow function to fix IE compatibility
- php - 在 laravel 中与视图作曲家共享后未定义的变量
- javascript - 注销反应时未呈现登录路线
- flask - 上传功能的烧瓶自定义错误处理
- r - 无法追加到表
- php - 单选按钮在php中给出错误的值