2014-04-28 53 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

相关问题