views:

332

answers:

1

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!

+1  A: 

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
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
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
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