Dani
Dani

Reputation: 15069

Manually delete object tree in entity-Framework

If I want to delete manually an object and all it's children, How can I do it (I don't want to use cascade-delete)

When I'm trying to iterate over the children list - I get an exception because I'm changing the collection inside foreach - and that's a problem... any other way to do it ? (I'm setting each time state to deleted).

var myAssignemnt = (from s in context.Assignments.Include("ActivityInAssignments").Where(s => s.AssignmentID == AssignmentID) select s).FirstOrDefault();

foreach (ActivityInAssignment acc in myAssignemnt.ActivityInAssignments)
{
  context.ObjectStateManager.ChangeObjectState(acc, System.Data.EntityState.Deleted);
}
context.ObjectStateManager.ChangeObjectState(myAssignemnt, System.Data.EntityState.Deleted);
context.SaveChanges();

Upvotes: 1

Views: 684

Answers (1)

Henk Holterman
Henk Holterman

Reputation: 273274

Maybe try ... in myAssignemnt.ActivityInAssignments.ToList()

Upvotes: 2

Related Questions