在Alex James的博客文章How to fake Foreign Key Properties in .NET 3.5 SP1中,他解释了如何向实体对象添加外键属性。
我已经使用它来获取强类型ASP.NET MVC应用程序中与DropDownList一起使用的引用/导航属性,如下所述:
Strongly-Typed ASP.NET MVC with ADO.NET Entity Framework
我还需要处理收藏。我可以使用Tyler Garlick的CheckBoxList而不是内置的DropDownList。
ASP.NET MVC With CheckBoxList http://img241.imageshack.us/img241/5197/checkboxlistpeople.gif
但是,如何扩展ObjectContext和EntityObjects以处理一对多类型关系?
我是否可以将Department EntityObject类扩展为包括Guid的Generic List类型的PersonIds属性?如何处理集合访问器?
最佳答案
我假设您可以将选定的人员ID放入Action方法中,并且所有人员都已存在于数据库中……因为这种形式只是在创建与人员的关系并更新部门本身,而不是在创建新人员。
在这种情况下,您想要执行以下操作(伪代码):
// 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();
这实际上是您需要做的。
希望这可以帮助
亚历克斯
关于.net - 如何在 Entity Framework 和ASP.NET MVC中伪造外键集合属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/923400/