1

在 ASP.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; }

在控制器的Edit视图中League,我有一个下拉菜单LeagueMembers,在其编辑操作中,我试图删除现有的 LeagueMembers 并创建新的:

[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 的第二次迭代:

收藏已修改;枚举操作可能无法执行

有没有更好的方法来删除一对多关系中的批量记录?

在这种情况下,可能不遍历集合就全部删除?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();
4

3 回答 3

1

我认为你的代码有一些错别字。例如,它看起来var league = leagueMember.League应该是var league = leagueMemberViewModel.League。我怀疑这与附加对象leagueMembers的联盟成员相同。league(您通过设置附加EntityState.Modified)。

如果是这样,错误的解释是您循环加载的集合并同时从中删除项目。补救措施很简单:

foreach (var leagueMember in leagueMembers.ToArray()) // <= ToArray

它将集合复制到不变的本地数组中。

至于你的第二个问题:没有在实体框架中进行批量删除的内置方法。

于 2013-05-02T18:35:33.287 回答
0

迭代时不能修改集合,最好的方法是使用反向 for 循环,如下所示:

        for (int i = leagueMembers.Count - 1; i >= 0; i--)
        {
            context.LeagueMembers.Remove(leagueMembers[i]);
        }
于 2013-05-02T22:39:40.720 回答
-1

这是一个常见的 .NET 错误,您可以通过将foreach循环替换为for循环来解决此问题:

for (var i = 0; i < leagueMembers.Count; i++)
{
    context.LeagueMembers.Remove(leagueMembers[i]);
}
于 2013-05-02T15:41:03.663 回答