我有一个 ChangeRequest 对象和一个具有多对多关系的 BusinessArea 对象。有一个连接表:ChangeRequestBusinessArea。
如果我使用 BusinessAreaID 2、7、8 和 10 创建并保存新的 ChangeRequest,则连接表会更新得很好。
例如
ChangeRequestID BusinessAreaID
1 2
1 7
1 8
1 10
但是,当我随后使用 BusinessAreaID 1、2、3、7 和 10 编辑并保存相同的 ChangeRequest 时,我得到以下信息:
ChangeRequestID BusinessAreaID
1 2
1 7
1 8
1 10
1 11
1 12
1 13
1 14
1 15
这是代码:
课程
namespace MOC.Models
{
public class ChangeRequest
{
public ChangeRequest()
{
BusinessAreas = new List<BusinessArea>();
}
public int ChangeRequestID { get; set; }
public string ChangeRequestName { get; set; }
public virtual ICollection<BusinessArea> BusinessAreas { get; set; }
}
}
namespace MOC.Models
{
public class BusinessArea
{
public int BusinessAreaID { get; set; }
public string BusinessAreaName { get; set; }
public virtual ICollection<ChangeRequest> ChangeRequests { get; set; }
}
}
动作方法
[HttpPost]
public ActionResult Edit(int id, ChangeRequestViewModel ChangeRequestViewModel)
{
if (ModelState.IsValid)
{
var changeRequest = new ChangeRequest
{
ChangeRequestID = id
};
AddOrUpdateBusinessAreas(changeRequest, ChangeRequestViewModel.BusinessAreas);
db.Entry(changeRequest).State = EntityState.Modified;
db.SaveChangeRequests();
return RedirectToAction("Index");
}
return View(ChangeRequestViewModel);
}
private void AddOrUpdateBusinessAreas(ChangeRequest ChangeRequest, IEnumerable<AssignedBusinessAreaData> assignedBusinessAreas)
{
foreach (var assignedBusinessArea in assignedBusinessAreas)
{
if (assignedBusArea.Assigned) {
var busarea = new BusArea { BusAreaID = assignedBusArea.BusAreaID };
Change.BusAreas.Add(busarea);
} else {
var busarea = new BusArea { BusAreaID = assignedBusArea.BusAreaID };
Change.BusAreas.Remove(busarea);
}
}
}