Entity Framework - how to remove linked elements

c# entity-framework-6


I have the following model:

enter image description here

I have an object of entity vacancy (ef_entity), given from DB, which already has one linked swap element (given from DB too). I just want to remove it:

        if (ef_vacancy.Swaps != null)

when I want to do SaveChanges 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.

so, Entity Framework try to set "null" to Swap.VacancyID table instead of remove records. But I want to remove. If I try to do the following:

        var swap_to_delete = (from i in _db.Swaps where i.VacancyID == ID.Value select i).FirstOrDefault();
        if (swap_to_delete != null && _db.Entry(swap_to_delete).State != EntityState.Deleted)

It sometimes works, sometimes no work! I did not understand why it works, why not. How to do this easy action correctly?

2/11/2015 2:59:16 PM

Accepted Answer

This should answer your question: https://stackoverflow.com/a/2058787/1154763

The text of the answer (credit to Craig Stuntz):

Clear() removes the reference to the entity, not the entity itself.

If you intend this to be always the same operation, you could handle AssociationChanged:

Entity.Children.AssociationChanged += 
new CollectionChangeEventHandler(EntityChildrenChanged);

private void EntityChildrenChanged(object sender,
    CollectionChangeEventArgs e)
    // Check for a related reference being removed. 
    if (e.Action == CollectionChangeAction.Remove)

You can build this in to your entity using a partial class.

5/23/2017 12:06:32 PM

Popular Answer

You should delete the child items in ef_vacancy.Swaps one by one manually. Entity Framework doesn't do that for you. It finally cannot decide what you want to do with the old child items - if you want to throw them away or if you want to keep and assign them to other parent entities. It is not possible to just remove it from the Swaps collection as it cannot exist by itself, because it has a non-nullable foreign key referencing Vacancy(VacancyId). You can Delete the Swaps this way:

foreach (var child in ef_vacancy.Swaps)
   db.Entry(child).State = EntityState.Deleted;

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow