Exception error "Collection was modified; enumeration operation may not execute"
Hi folks.
For anyone out there who tried to exercise the delete action method when the user is already authenticated.
In case you have succeeded after all printing errors in the book and tries to follow the advice in the last paragraph of page 116 in Chapter 1: "We can repeat the same steps for the Delete action methods within our Controller to lock down permission to delete Dinners as well, and ensure that only the host of a Dinner can delete it."
You will find that the code defined for Delete a dinner in the repository (DinnerRepository) will generate an exception "Collection was modified; enumeration operation may not execute" error.
This is due to the fact that as you delete the objects from the context, the Entity Framework is actively updating the RSVPs navigation property count which means the "dinner.RSVPs" collection is being changed during the "foreach" loop which will always cause the exception you are getting.
So the are 2 possible solutions:
a) Change the current foreach parameters:
public void Delete(Dinner dinner)
{
....
//--- Instead of using "foreach ( var rsvp in dinner.RSVPs )" ---//
//--- use this: ---//
foreach ( var rsvp in dinner.RSVPs.ToList() )
{
entities.RSVPs.DeleteObject( rsvp );
}
....
}
and
b) Use the LINQ ForEach method instead:
public void Delete(Dinner dinner)
{
....
//--- Instead of using "foreach ( var rsvp in dinner.RSVPs )" ---//
//--- use this: ---//
dinner.RSVPs.ToList().ForEach(record =>
entities.RSVPs.DeleteObject(record));
....
}
Hope it helps (at least it worked for me )
Regards
Carlos
|