2009-05-28 4 views
3

Alex James의 블로그 게시물 How to fake Foreign Key Properties in .NET 3.5 SP1에서 Entity 개체에 외래 키 속성을 추가하는 방법을 설명합니다.Entity Framework 및 ASP.NET MVC에서 외래 키 컬렉션 속성을 가짜로 만드는 방법

내가 여기에 설명 된 바와 같이 강력한 형식의 ASP.NET MVC 응용 프로그램에서 DropDownList로 작업 참조/탐색 속성을 얻기 위해 그것을 사용했습니다 :

Strongly-Typed ASP.NET MVC with ADO.NET Entity Framework

나는 또한 컬렉션을 처리해야합니다. 내장 된 DropDownList보다는 Tyler Garlick의 CheckBoxList를 사용할 수 있습니다. 방법

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

그러나 나는 일대 유형의 관계를 처리하기 위해 ObjectContext를 내 EntityObjects을 확장 할 수 있습니까?

Guid의 일반 목록 유형의 PersonIds 속성을 포함하도록 Department EntityObject 클래스를 확장합니까? 설정된 접근자를 어떻게 처리합니까?

답변

1

내가 선택한 사람 ID를 Action 메서드로 가져올 수 있고 모든 People가 데이터베이스에 이미 있다고 가정합니다.이 양식은 단순히 People과의 관계를 만들고 새 항목을 만들지 않기 때문에 부서 자체를 업데이트하기 때문입니다 직원. 이 (사이비 코드)와 같은 뭔가를 원하는 경우

는 :

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

이것은 당신이

알렉스

하는 데 도움이 ..

희망을해야 할 일을 본질적으로

관련 문제