2011-08-26 2 views
1

대다수의 관계가있는 간단한 코드 첫 번째 클래스가 있습니다. Child를 검색하고 Include를 사용하여 School을 검색하면 School = new School() 행을 주석 처리하면 제대로 작동하지만 School 클래스는 채워지지 않습니다. 나는 이것이 예상 된 행동이라고 생각한다. (누군가 누군가를 확인할 수 있겠는가?)하지만, 특히 컬렉션 프로퍼티와 똑같이하는 것이 좋으면 주어진다.EF4.1 생성자에서 비 목록 연결 속성을 인스턴스화하면 포함이 작동하지 않습니다.

public class Child 
{ 
    public Child() 
    { 
     School = new School();  
    } 

    public int Id { get; set; } 
    public string Name { get; set; } 

    public int SchoolId { get; set; } 
    public School School { get; set; }   
} 

public class School 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 

    public ICollection<Child> Children { get; set; }   
} 

public class TestContext : DbContext 
{ 
    public TestContext(string connectionString) 
     : base(connectionString) 
    { 
    } 

    public DbSet<Child> Children { get; set; }   
} 

public class Test 
{ 
    public Test() 
    { 
     var context = new TestContext("...connectionstring..."); 

     var child = context.Children.Include(x => x.School).Where(x => x.Id == 1).SingleOrDefault(); 

     Debug.Assert(child.School.Id != 0, "School is null"); 
    } 
} 

답변

2

예, 기본 constructur에서 참조 탐색 속성을 인스턴스화하는 원인 문제 :

그냥 빈 집합을 인스턴스화하고 있기 때문에 그것은 컬렉션을 위해 잘 작동 이 경우에는 참조 된 객체가 없습니다. 하지만 참조 속성에 대해서는이 작업을 수행하지 않는 것이 좋습니다.

관련 문제