2009-05-28 184 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(); 

這主要是你需要做的..

希望這有助於

亞歷

什麼