我假设你可以得到所选择的人员标识的进入操作方法,和所有的人都已经存在于数据库...因为这种形式只是建立以人的关系和更新部门本身,而不是创造新的员工。
在你想要做这样的事情(伪代码)情况:
// get the department from the form using the model binder
Department updated = ... ;
// get the ids of the selected people from the form too.
var currentlySelectedStaffIds = ...;
// get the original department from the database
// including the originally related staff
Department original = ctx.Departments.Include("Staff")
.First(dep => dep.Id = updated.Id);
// get the ids of all the originally related staff
var originalStaffIds = original.Staff.Select(s => s.Id).ToArray();
// get the People to be removed from the department
var removedStaff = (from staff in original.Staff
where !currentlySelectedStaffIds.Contains(staff.Id)
select staff).ToArray();
// get People added to the department (but attached to the context)
var addedStaff = currentlySelectedStaffIds.Except(originalStaffIds)
.Select(id => new Person {Id = id}).ToArray();
// Remove the original staff no longer selected.
foreach(var removed in removedStaff)
{
original.Staff.Remove(removed);
}
// Attach the 'added' staff and build a new relationship for each one
foreach(var added in addedStaff){
//Put the staff added to the department in the context
ctx.AttachTo("People", added);
// build a new relationship
original.Staff.Add(added);
}
// Apply the changes from updated to the original entity
ctx.ApplyPropertyChanges("Departments", updated);
ctx.SaveChanges();
这主要是你需要做的..
希望这有助于
亚历
什么