在 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();