如何在实体框架和 ASP.NET MVC 中伪造外键集合属性

2024-02-23

在亚历克斯·詹姆斯的博客文章中如何在 .NET 3.5 SP1 中伪造外键属性 http://blogs.msdn.com/alexj/archive/2009/03/25/tip-7-faking-foreign-key-properties-in-net-3-5-sp1.aspx,他解释了如何向实体对象添加外键属性。

我使用它来获取与强类型 ASP.NET MVC 应用程序中的 DropDownList 一起使用的引用/导航属性,如下所述:

带有 ADO.NET 实体框架的强类型 ASP.NET MVC https://stackoverflow.com/questions/922402/strongly-typed-asp-net-mvc-with-ado-net-entity-framework

我还需要处理集合。我可以使用 Tyler Garlick 的 CheckBoxList 而不是内置的 DropDownList。

ASP.NET MVC 与 CheckBoxList http://img241.imageshack.us/img241/5197/checkboxlistpeople.gif http://img241.imageshack.us/img241/5197/checkboxlistpeople.gif

但是如何扩展 ObjectContext 和 EntityObject 来处理一对多类型关系?

我是否可以扩展我的 Department EntityObject 类以包含 Guid 通用列表类型的 PersonIds 属性?如何处理 set 访问器?


我假设您可以将选定的人员 ID 放入操作方法中,并且所有人员都已存在于数据库中...因为此表单只是创建与人员的关系并更新部门本身,而不是创建新员工。

在这种情况下,你想做这样的事情(伪代码):

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

这本质上就是你需要做的..

希望这可以帮助

Alex

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在实体框架和 ASP.NET MVC 中伪造外键集合属性 的相关文章

随机推荐