在使用 EF 更新期间出现以下错误:
操作失败:无法更改关系,因为一个或多个外键属性不可为空。当对关系进行更改时,相关的外键属性将设置为空值。如果外键不支持空值,则必须定义新的关系,必须为外键属性分配另一个非空值,或者必须删除不相关的对象。
有什么通用方法可以找到哪些外键属性导致上述错误?
[更新]
对于以下代码导致上述错误的一种情况(我在断开连接的环境中工作,所以我曾经graphdiff
更新我的对象图),当它想要运行时_uow.Commit();
:
public void CopyTechnicalInfos(int sourceOrderItemId, List<int> targetOrderItemIds)
{
_uow = new MyDbContext();
var sourceOrderItem = _uow.OrderItems
.Include(x => x.NominalBoms)
.Include("NominalRoutings.NominalSizeTests")
.AsNoTracking()
.FirstOrDefault(x => x.Id == sourceOrderItemId);
var criteria = PredicateBuilder.False<OrderItem>();
foreach (var targetOrderItemId in orderItemIds)
{
int id = targetOrderItemId;
criteria = criteria.OR(x => x.Id == id);
}
var targetOrderItems = _uow.OrderItems
.AsNoTracking()
.AsExpandable()
.Where(criteria)
.ToList();
foreach (var targetOrderItem in targetOrderItems)
{
//delete old datas and insert new datas
targetOrderItem.NominalBoms = sourceOrderItem.NominalBoms;
targetOrderItem.NominalBoms.ForEach(x => x.Id = 0);
targetOrderItem.NominalRoutings = sourceOrderItem.NominalRoutings;
targetOrderItem.NominalRoutings.ForEach(x => x.Id = 0);
targetOrderItem.NominalRoutings
.ForEach(x => x.NominalTests.ForEach(y => y.Id = 0));
targetOrderItem.NominalRoutings
.ForEach(x => x.NominalSizeTests.ForEach(y => y.Id = 0));
_uow.OrderItems.UpdateGraph(targetOrderItem,
x => x.OwnedCollection(y => y.NominalBoms)
.OwnedCollection(y => y.NominalRoutings,
with => with
.OwnedCollection(t => t.NominalTests)));
}
_uow.Commit();
}