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

时间:2012-04-29 21:24:17

标签: c# .net entity-framework entity-framework-4.3

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

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不可为空时,正在检查具有空订单的OrderDetails似乎是奇怪的。这样做的正确方法如何?

修改 例如,当您通过绑定Order.OrderDetails和DataGrid进行公开时,会发生奇怪的删除。

2 个答案:

答案 0 :(得分:2)

你可以这样做:

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

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

答案 1 :(得分:0)

您正从订单的OrderDetails对象集合中删除OrderDetail。这只是将OrderDetail的ID有效地设置为null并且不将其标记为删除。这是不允许的,因为从OrderDetail到数据库中的Order表的FK不可为空。

你应该这样做

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

context.OrderDetails.Remove(baddetail);