MVC 4和延迟加载:“Collection”被修改了删除多条记录时出错
本文关键字:删除 记录 出错 修改 延迟加载 Collection MVC | 更新日期: 2023-09-27 18:12:03
. NET MVC 4项目,我有一个模型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; }
}
在联赛模式中,我有:
public virtual ICollection<LeagueMember> LeagueMembers { get; set; }
在League
控制器的Edit
视图中,我有LeagueMembers
的下拉菜单,在其编辑操作中,我试图删除现有的league成员并创建新成员:
[HttpPost]
public ActionResult Edit(LeagueMembersViewModel leagueMemberViewModel)
{
if (ModelState.IsValid)
{
var league = leagueMemberViewModel.League;
context.Entry(league).State = EntityState.Modified;
/* without this line the next foreach statement would complain that
League.LeagueMembers is null due to 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);
}
执行时,foreach (var leagueMember in leagueMembers)
行报错forloop的第二次迭代:
Collection被修改;枚举操作不能执行
在一对多关系中是否有更好的方法来删除批量记录?
在这种情况下,删除所有的leagueMemberViewModel.League.LeagueMembers
可能没有遍历集合?
类似,替换:
context.Entry(league).Collection("LeagueMembers").Load();
var leagueMembers = leagueMemberViewModel.League.LeagueMembers;
foreach (var leagueMember in leagueMembers)
{
context.LeagueMembers.Remove(leagueMember);
}
:
leagueMember.League.LeagueMembers.Remove();
我认为你的代码有一些错别字。例如,看起来var league = leagueMember.League
应该是var league = leagueMemberViewModel.League
。从字里行间看,我怀疑leagueMembers
与附加的league
对象的leagueMembers相同。(通过设置EntityState.Modified
来附加)。
如果是,则错误解释为循环遍历已加载的集合并同时从中删除项。补救方法很简单:
foreach (var leagueMember in leagueMembers.ToArray()) // <= ToArray
将集合复制到不更改的本地数组。
至于你的第二个问题:没有,没有内置的方法来做批量删除在实体框架
不能在遍历集合时修改它,最好的方法是使用像这样的反向for循环:
for (int i = leagueMembers.Count - 1; i >= 0; i--)
{
context.LeagueMembers.Remove(leagueMembers[i]);
}
这是一个常见的。net错误,您可以通过将foreach
循环替换为for
循环来解决此问题:
for (var i = 0; i < leagueMembers.Count; i++)
{
context.LeagueMembers.Remove(leagueMembers[i]);
}