Typically one to many, when I delete as:
var orderEntity = context.Orders.Single(o => o.orderID == entityID);
var baddetail = orderEntity.OrderDetails
.Single(od => od.orderDetailID == badOrderDetailID);
orderEntity.OrderDetails.Remove(baddetail);
I get an 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, it was proposed to expand DBContext.SaveChanges ()
public override int SaveChanges()
{
foreach (OrderDetails od in this.OrderDetails.ToList())
{
if (od.Order == null)
{
this.OrderDetail.Remove(od);
}
}
return base.SaveChanges();
}
But it checks OrderDetails with zero orders, when orderID is not NULL, it seems odd. How to do it right?
EDIT:
As an example, this strange deletion happens when you open your Order.OrderDetailsto and DataGrid bindings.
source
share