With Object Framework 4, how do I remove a child entity from a parent collection?

cascading-deletes entity-framework

Question

I have a one-to-many connection between a parent and child object and I'm using Entity Framework 4. By deleting it from the parent's children collection, I'm attempting to remove a child using the parent repository:

public virtual void RemoveChild(Child child)
        {
            children.Remove(child);
        }

I get the following problem when I attempt to save the changes:

A relationship from the 'ParentChild' AssociationSet is in the 'Deleted' state. Given multiplicity constraints, a corresponding 'Child' must also in the 'Deleted' state.

Surely I don't need to use a child repository to specifically remove the child item!

1
9
5/21/2010 4:29:12 PM

Accepted Answer

Whether you have a cascade in the database will determine this. This ought to happen automatically if you do (which, given your query, you presumably should). Read more about this here..

1
5/21/2010 4:32:05 PM

Popular Answer

The following override on the DbContext is what I've found to fix this issue:

public override int SaveChanges()
{
    Set<Child>()
    .Local
    .Where(r => !Parent.Local.SelectMany(s => s.Children).Contains(r))
    .ToList()
    .ForEach(r => Set<Child>().Remove(r));

    return base.SaveChanges();
}

Look at this: http://blog.oneunicorn.com/2012/06/02/deleting-orphans-with-entity-framework/



Related Questions





Related

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