2009-05-28 110 views
3

在亚历克斯·詹姆斯的博客文章How to fake Foreign Key Properties in .NET 3.5 SP1假外键集合的属性,他解释了如何将外键属性添加到实体对象。如何在实体框架和ASP.NET MVC

我已经使用了如下解释得到一个参考/导航属性的强类型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处理一个一对多的类型关系?

难道我致以部EntityObject类包括的Guid类型泛型列表的PersonIds财产?我如何处理set访问器?

回答

1

我假设你可以得到所选择的人员标识的进入操作方法,和所有的人都已经存在于数据库...因为这种形式只是建立以人的关系和更新部门本身,而不是创造新的员工。

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

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

这主要是你需要做的..

希望这有助于

亚历

什么