在典型的一对多关系中,当我删除时:
var orderEntity = context.Orders.Single(o => o.orderID == entityID);
var baddetail = orderEntity.OrderDetails
.Single(od => od.orderDetailID == badOrderDetailID);
orderEntity.OrderDetails.Remove(baddetail);
我得到错误:
The operation failed: The relationship could not be changed because one
or more of the foreign-key properties is non-nullable. When a change is made
to a relationship, the related foreign-key property is set to a null value.
If the foreign-key does not support null values, a new relationship must
be defined, the foreign-key property must be assigned another non-null value,
or the unrelated object must be deleted.
作为一种解决方案,提出了扩展 DBContext.SaveChanges()
public override int SaveChanges()
{
foreach (OrderDetails od in this.OrderDetails.ToList())
{
// Remove OrderDetails without Order.
if (od.Order == null)
{
this.OrderDetail.Remove(od);
}
}
return base.SaveChanges();
}
但是正在检查带有空订单的 OrderDetails,当 orderID 不可为空时似乎很奇怪。这样做的正确方法是什么?
编辑:
例如,当您通过绑定Order.OrderDetails
到和 DataGrid 公开时,会发生这种奇怪的删除。