c# - MVC 4 and lazy loading: "Collection was modified" error when deleting multiple records -
in asp.net mvc 4 project, have model leaguemember
:
public class leaguemember { [key, column(order = 0)] public int memberid { get; set; } [key, column(order = 1)] public int leagueid { get; set; } public bool? isactive { get; set; } public virtual league league { get; set; } public virtual member member { get; set; } }
in league model, have:
public virtual icollection<leaguemember> leaguemembers { get; set; }
in edit
view of league
controller, have dropdown leaguemembers
, in edit action trying delete existing leaguemembers , creating new ones:
[httppost] public actionresult edit(leaguemembersviewmodel leaguememberviewmodel) { if (modelstate.isvalid) { var league = leaguememberviewmodel.league; context.entry(league).state = entitystate.modified; /* without line next foreach statement complain league.leaguemembers null due lazy loading..*/ context.entry(league).collection("leaguemembers").load(); var leaguemembers = leaguememberviewmodel.league.leaguemembers; foreach (var leaguemember in leaguemembers) { context.leaguemembers.remove(leaguemember); } foreach (var memberid in leaguememberviewmodel.selectedmembers) { var leaguemember = new leaguemember { memberid = memberid, league = league }; context.leaguemembers.add(leaguemember); } context.savechanges(); return redirecttoaction("index"); } leaguememberviewmodel.memberlist = new multiselectlist(context.members, "id", "name", leaguememberviewmodel.selectedmembers); return view(leaguememberviewmodel); }
when executed, line foreach (var leaguemember in leaguemembers)
complains on second iteration of forloop:
collection modified; enumeration operation may not execute
is there better way delete bulk records in one-to-many relationship?
in case, to remove leaguememberviewmodel.league.leaguemembers
perhaps without iterating through collection?
something like, replacing:
context.entry(league).collection("leaguemembers").load(); var leaguemembers = leaguememberviewmodel.league.leaguemembers; foreach (var leaguemember in leaguemembers) { context.leaguemembers.remove(leaguemember); }
with:
leaguemember.league.leaguemembers.remove();
i think code has typos. example, looks var league = leaguemember.league
should var league = leaguememberviewmodel.league
. reading between lines suspect leaguemembers
same leaguemembers of attached league
object. (that attach setting entitystate.modified
).
if so, error explained fact loop through loaded collection , @ same time remove items it. remedy simple:
foreach (var leaguemember in leaguemembers.toarray()) // <= toarray
which copies collection local array not change.
as second question: no there no built-in way bulk deletes in entity framework.
Comments
Post a Comment