Kirsten
Kirsten

Reputation: 18066

Entity Framework Remove. Why do I need to set the entity state?

I use the following code snippet to delete a parent Job record with child Design records.

 foreach (var item in data.Items.Where(i => i.DeletePending == true && i.ItemId > 0))
{
    var deljob = connect.job.Include(j => j.Design).Single(j => j.JobID == item.ItemId);
    foreach (var delDesign in deljob.Design.ToArray())   
    {
        // next line is needed or it fails
        connect.Entry(delDesign).State = EntityState.Deleted;
        deljob.xVivDesign.Remove(delDesign);
    }
    // no need to set the state here
    connect.job.Remove(deljob);
}

The error is

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.

Upvotes: 0

Views: 62

Answers (2)

Kirsten
Kirsten

Reputation: 18066

The problem was that I was removing the Design from the Job's collection of designs. Instead I should have been removing the design from the Entity Set

Thus the answer was to use

connect.design.Remove(delDesign)

Upvotes: 1

It's telling you that there's a foreign key constraint that you would be violating by deleting that record.

If I have the following tables:

Customer

Id   | Name   | Age
---------------------
1    | Barry  | 52

Order

Id   | CustId   | OrderAmount
------------------------------
1    |   1      | 27.39

For this example, Order has a foreign key constraint on Order.CustId = Customer.id, I would not be able to delete Barry from my Customer table, unless I first deleted all references of Barry in the Order table because of the foreign key constraint (Anything in Order with a custId of 1)

As the error message explains,

When a change is made to a relationship, the related foreign-key property is set to a null value.

By deleting Barry from Customer, you no longer have a record of Customer with an ID of 1. This will violate the constraint, as it would try to set a non-nullable integer (userId in Order) to a null value.

I would suggest looking at Foreign Key Constraints

Assuming there are no other keys tied to the job you are trying to delete, you could delete the job entry after deleting all the design records associated with that job. Only do that if you are 100% confident that you will never need the design records again.

Upvotes: 1

Related Questions