29

I'm using EF and when I do this:

            foreach (var reg in detail.Regs)
            {
                this.db.Regs.DeleteObject(reg);
            }

I get this:

Collection was modified; enumeration operation may not execute.

What I'm I doing wrong here???

1 Answer 1

80

The reason for that is because as you delete the objects from the context, EF is actively update the Regs navigation property count which means the detail.Regs collection is being changed during the foreach loop which always cause the exception you are getting.

You can create a new collection object and keep deleting from it like this:

foreach (var reg in detail.Regs.ToList())
{
    this.db.Regs.DeleteObject(reg);
}

Or even you can make it cleaner by using LINQ ForEach method:

detail.Regs.ToList().ForEach(r => db.Regs.DeleteObject(r));
Sign up to request clarification or add additional context in comments.

1 Comment

That get all the records from the database just to have them deleted no?

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.