2014-04-28 50 views
0

我試圖讓Department對象的Studies屬性延遲加載,但它只會在我急切加載時加載。我已將DepartmentId添加到Study級別,但沒有結果,使用了ICollectionISetvirtual。公共和私人的制定者似乎沒有什麼區別(也不應該)。似乎沒有任何工作。使用EF 6.1。實體框架急切加載關聯的集合,但不會延遲加載它

public class Department 
{ 
    private Department() {} 

    public Department(DepartmentTitle title) 
    { 
    if (title == null) throw new ArgumentNullException(); 

    this.Title = title; 
    this.Studies = new HashSet<Study>(); 
    } 

    public int DepartmentId { get; private set; } 

    public virtual DepartmentTitle Title { get; private set; } 
    public virtual ICollection<Study> Studies { get; set; } 
} 

public class Study 
{ 
    private Study() {} 

    public Study(StudyTitle title, Department department) 
    { 
    if (title == null) throw new ArgumentNullException(); 
    if (department == null) throw new ArgumentNullException(); 

    this.Title = title; 
    this.Department = department; 
    } 

    public int StudyId { get; private set; } 

    public virtual StudyTitle Title { get; private set; } 
    public virtual Department Department { get; set; } 
} 

// Here I save the department and study objects 
// I verified they exist in the database  
var department = new Department(new DepartmentTitle("Department Title Here")); 
department.Studies.Add(new Study(new StudyTitle("Study Title Here"), department)); 
data.SaveChanges(); 

// In a new database context 
// Here I try to lazy load the Studies property, but get null 
// It works if I add Include("Studies") before Where() 
Department department = data.Departments.Where(d => d.Title.Value == "Department Title Here").Single(); 
System.Console.WriteLine(department.Studies.First().Title.Value); 

// DepartmentTitle and StudyTitle are simple complex types with a Value property 

回答

2

你的學習類需要一個公共的或受保護的無參數構造函數懶加載工作:MSDN

+0

這很奇怪,但它的工作原理。我認爲它沒有什麼區別,因爲它告訴我們EF如何使用反射來訪問任何需要的東西。顯然不是。 – Seralize

+0

我希望在幾個星期前我偶然發現了這個問題。試圖弄清楚爲什麼懶加載不適用於我的實體。我在我的實體上有一個私有的無參數構造函數,它可以很好地與EF一起從數據庫加載實體。將其更改爲受保護,並延遲加載最終有效。 !AARGH – TheOtherTimDuncan

1

你需要實際加載研究:

department.Studies.Load(); 
System.Console.WriteLine(department.Studies.First().Title.Value); 

否則,他們將不存在,First()會崩潰。

所以要麼你Include()您的實體急於加載,或者你Load()它後來以一種懶惰的方式。

+0

+1。我確信這種方法可行,但事實並非如此。然而,它引導我朝着正確的方向發展,否則它會帶領其他人朝着這個方向發展。 – Seralize

相關問題