Reputation: 464
I have a table in the database called Course_Predecessor and I'm trying to delete all the items from this table using EF and then adding new data to the table. I can't delete the data because I get the following error : "collection was modified enumeration operation may not execute"
this is the code I'm using (inside of a fucntion which recieves the context of the db as ctx)
List<Course_Predecessor> lst = new List<Course_Predecessor>();
fillTheList(ref lst , someData);
ctx.Course_Predecessor.RemoveRange(ctx.Course_Predecessor.ToList());
ctx.Course_Predecessor.AddRange(predecessors);
I get the error at the RemoveRange function.
would appreciate any help.
Upvotes: 0
Views: 146
Reputation: 479
If you are using EF6 (which is looks like you are) then you should be able to delete all records in the table by doing the following. (Note the absence of the .ToList()
method in the RemoveRange
call)
ctx.Course_Predecessor.RemoveRange(ctx.Course_Predecessor);
ctx.SaveChanges();
Alternatively you could do:
foreach (var predecessor in ctx.Course_Predecessor)
{
ctx.Entry(predecessor).State = EntryState.Deleted;
}
ctx.SaveChanges();
Both sections of code do the exact same thing.
Upvotes: 1
Reputation: 122
You can try as following:
ctx.Course_Predecessor.ToList().ForEach(c => ctx.Course_Predecessor.Remove(c));
Upvotes: 1
Reputation: 222582
Try this,
ctx.Course_Predecessor.ToList().ForEach(r => ctx.Course_Predecessor.DeleteObject(r));
ctx.SaveChanges();
Upvotes: 0