Reputation: 195
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!
Upvotes: 9
Views: 9710
Reputation: 3020
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/
Upvotes: 3
Reputation: 1239
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.
Upvotes: 1
Reputation: 126547
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.
Upvotes: 1