简体   繁体   English

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

[英]How to proper clean up after delete in the navigation collection in one to many relationship EF 4.3.1

In a typical relation one to many, when I delete like: 在一对多的典型关系中,当我删除时:

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

I obtain the error: 我得到错误:

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.

As a solution was proposed to extend the DBContext.SaveChanges() 作为解决方案被提议扩展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();
    }

But is checking for OrderDetails with null Orders, when orderID is not nullable seem`s odd. 但是当orderID不可为空时,检查具有空命令的OrderDetails似乎是奇怪的。 How is the proper way of doing this ? 这样做的正确方法如何?

EDIT: As an example this odd deleting is happening when you expose through binding your Order.OrderDetails to and DataGrid. 编辑:作为一个例子,当你通过绑定Order.OrderDetails和DataGrid公开时,会发生奇怪的删除。

You can just do this way: 你可以这样做:

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

Because in your example you are not deleting entity. 因为在您的示例中您不是删除实体。 You are deleting relationship. 你正在删除关系。 So it tries to set null to your FK column and, of it is not nullable you will get and exception. 所以它试图将null设置为你的FK列,并且它不可为空,你将获得和异常。

You are removing the OrderDetail from the Order's objects collection of OrderDetails. 您正从订单的OrderDetails对象集合中删除OrderDetail。 This is simply setting the OrderDetail's ID effectively to null and not marking it for deletion. 这只是将OrderDetail的ID有效地设置为null并且不将其标记为删除。 This is not allowed as the FK from the OrderDetail to the Order table in the database is not nullable. 这是不允许的,因为从OrderDetail到数据库中的Order表的FK不可为空。

You should be doing 你应该这样做

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

context.OrderDetails.Remove(baddetail);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM