gpt4 book ai didi

c# - 如何在一对多关系 EF 4.3.1 的导航集合中删除后正确清理

转载 作者:行者123 更新时间:2023-11-30 17:12:49 27 4
gpt4 key购买 nike

在典型的一对多关系中,当我删除 like 时:

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();
}

但是当 orderID 不可为 null 时,正在检查具有空订单的 OrderDetails 似乎很奇怪。这样做的正确方法是什么?

编辑:例如,当您通过将 Order.OrderDetails 绑定(bind)到 DataGrid 来公开时,就会发生这种奇怪的删除。

最佳答案

你可以这样做:

var orderEntity = context.Orders.Single(o => o.orderID == entityID);var baddetail = orderEntity.OrderDetails.Single(od => od.orderDetailID == badOrderDetailID);context.OrderDetails.Remove(baddetail);

因为在您的示例中您没有删除实体。您正在删除关系。因此它会尝试将 null 设置为您的 FK 列,并且它不可为空,您将获得异常。

关于c# - 如何在一对多关系 EF 4.3.1 的导航集合中删除后正确清理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10376096/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com