2011-07-05 2 views
1

EF4 컨텍스트에서 지연로드를 활성화하려고합니다.InEntity Framework 4에서 지연로드가 작동하지 않습니다.

데이터를로드하려고하는 코드는 다음과 같습니다 내가 작업 패턴의 저장소 및 장치 실험하고 있지만 그것을 이해, 아래의 명령이 작동해야

using (IUnitOfWork uw = new EFUnitOfWork()) 
{ 
    foreach (Document doc in uw.Documents.All) 
    {   
     Console.WriteLine("Name: {0} Description: {1} Category: {2}", doc.Name, doc.Description, doc.DocumentCategory.Name); 
    } 
} 

.

ctx.ContextOptions.LazyLoadingEnabled = true; 

문제는 doc.DocumentCategory.Name에 액세스 할 때 NullReferenceException이 발생합니다.

왜이 데이터가 지연되어로드되지 않습니까?

DocumentCategories를로드 한 경우 DocumentCategory 속성이 확인됩니다.

public class Document 
{ 
    public Document() 
    { 

    } 

    public Document(int id) 
    { 
     Id = id; 
    } 

    public virtual int Id { get; set; } 
    public virtual string Name { get; set; } 
    public virtual string Description { get; set; } 
    public virtual int DocumentCategoryId { get; set; } 
    public virtual bool Deleted { get; set; } 
    public DocumentCategory DocumentCategory { get; set; } 

    public override string ToString() 
    { 
     return Name; 
    } 
} 
+0

Do * all * 문서에 DocumentCategory가 있습니까? LazyLoading이 주어진 Document에 대해 DocumentCategory를 검색하려고 시도 했으므로 아무 것도 찾지 못해 null이 반환되어 NullReferenceException이 발생합니다. – Smudge202

+0

예, DocumentCategoryId는 데이터베이스의 nullableable 필드이며 테이블 사이에 외래 키가 있습니다. –

+1

탐색 속성이 가상으로 표시되어 있습니까? Document 클래스의 정의를 보여줄 수 있습니까? – Dave

답변

3

또한 지연로드를 지원하려면 DocumentCategory 속성을 가상으로 표시해야합니다. 살펴보기 http://msdn.microsoft.com/en-us/library/dd468057.aspx

+0

고마워요, 질문에 대한 코멘트에 처음 도착했기 때문에 답을 표시했습니다. –

+0

힘든 기분이 아닙니다 :) –

2

이 Document.DocumentCategory 가상으로 선언되어 다음과 같이

내 문서 클래스를 정의? EF에서는 속성에 액세스 할 때 실제로 지연로드를 수행하는 프록시 유형을 생성해야합니다. (그렇지 않으면 EF는 속성 값에 액세스 할 때 알 수 없음)

또한 DocumentCategory가 이미 가상 인 경우 EF가 프록시 유형을 생성하는 데 앞서 다른 속성이있을 수 있습니다. 디버거를 사용하여 "Document"인스턴스를 검사하여 실제로 프록시 유형인지 확인하십시오.

관련 문제