Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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. 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.

like image 267
Ciobanu Ion Avatar asked Dec 07 '25 03:12

Ciobanu Ion


1 Answers

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.

like image 61
Aleksei Anufriev Avatar answered Dec 09 '25 02:12

Aleksei Anufriev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!