9

I'm using Entity Framework 4 and have a one-to-many relationship between a parent and child entity. I'm trying to delete a child using the parent repository by removing it from the parent's children collection:

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

When I try to save the changes I get the following error:

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 have to delete the child entity explicitly using a child repository!

simonjreid
  • 195
  • 2
  • 7

3 Answers3

3

What I've come across to solve this problem is the follwoing override on the DbContext:

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

Take a look here: http://blog.oneunicorn.com/2012/06/02/deleting-orphans-with-entity-framework/

Guillermo Ruffino
  • 2,940
  • 1
  • 26
  • 23
1

In EF4, if the child objects and the parent object are all attached to the ObjectContext, then EF will keep the Foreign Key references and Object References in-sync in both the Parent and the affected Children.

Beans
  • 1,159
  • 7
  • 17
1

It depends on whether you have a cascade in the DB. If you do (and, given your question, you probably should), then this should be automatic. You can read about this here.

Craig Stuntz
  • 125,891
  • 12
  • 252
  • 273
  • Thanks but I'm deleting a child not the parent. I've tried putting cascade on delete on the parent and get the same error. The parent is the aggregate root so I'm using the parent repository to delete one of its children. Do you know the best way to do this? Any help would be very much appreciated. – simonjreid May 24 '10 at 08:24
  • 1
    In this case removing the relationship deletes the child if (1) the parent's FK is in the child's PK and (2) there is a cascade. See http://blogs.msdn.com/dsimmons/archive/2010/01/31/deleting-foreign-key-relationships-in-ef4.aspx – Craig Stuntz May 24 '10 at 13:10
  • 1
    Thanks very much Craig. I think my scenario falls into Case 1 in that article - the parent's FK is not in the child's PK. So it seems I will have to delete the child myself. Sounds like future releases might take care of this for you... – simonjreid May 24 '10 at 14:50
  • 3
    Almost 3 years later and EF still doesn't take care of this, correct? – mwijnands Dec 14 '12 at 02:28