1

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

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

can you explain why it works with ToList() and not original collection ? (I though the problem is in the foreach function and not inside the ActivityInAssignment collection.
The problem is in the collection, It reacts to items being 'removed' and that invalidates the foreach. ToList makes a copy of the references and that copy is immune to the changes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.