I have the following action method inside my asp.net mvc web application:-
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Dept dept = db.Depts.Include(a => a.Emps).Single(a=>a.DeptID == id);
var emps = dept.Emps;
foreach (var c in emps)
{
dept.Emps.Remove(c);
}
db.Depts.Remove(dept);
db.SaveChanges();
return RedirectToAction("Index");
}
now this will raise the following exception , inside the foreach
code :-
An exception of type 'System.InvalidOperationException' occurred in System.Core.dll but was not handled in user code
Additional information: Collection was modified; enumeration operation may not execute.
but if i simply add a .ToList() to the emps as follow:-
var emps = dept.Emps.ToList();
foreach (var c in emps)
{
the error will disappear. but my question is why i need to add a .ToList() ? since in my case the dept variable should have the related emps records from the database , because i have added a .Include(), so the .Tolist() which will force the error to disappear should not have any effect.. ? Can anyone advice on this please? Thanks
Emps
in a new list.dept.Emps.Remove(x)
doesn't modify your copy. – ta.speot.isEmps
will beDbSet<Emp>
which is a reference type. You're copying the reference to the underlyingDbSet
. – ta.speot.is