.net - 如何在 Entity Framework 和ASP.NET MVC中伪造外键集合属性

标签 .net asp.net-mvc entity-framework ado.net

在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/

相关文章:

c# - 在c#中通过引用传递参数时跟踪地址

.net - SPI_GETMOUSEHOVERTIME 可以为零吗?

c# - 将 EF 模型序列化为 Json 时的循环引用

asp.net-mvc - 共享主机上的 ASP.NET MVC 无扩展 URL? (GoDaddy 等)

c# - 如何修复错误 'Name: The specified name is not allowed: _destroy'?

c# - 为什么会在运行时陷入困境?

.net - Azure 逻辑应用重试策略行为

c# - 有没有办法发现 Action<in T> 委托(delegate)实例的原始通用参数类型?

c# - 具有 asp 网络标识的自定义实体(一对多)

c# - 在 Entity Framework 4 中调用用户定义的函数