实体框架渴望加载相关集合,但赢得了';Don’不要懒加载它

本文关键字:加载 Don 渴望 框架 集合 实体 | 更新日期: 2023-09-27 18:00:23

我试图将Department对象的Studies属性设置为延迟加载,但只有当我急切地加载它时,它才会加载。我在Study类中添加了一个DepartmentId,但没有结果,使用了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

实体框架渴望加载相关集合,但赢得了';Don’不要懒加载它

您的Study类需要一个公共或受保护的无参数构造函数来处理延迟加载:MSDN

您需要实际加载研究:

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

否则它们将不存在,First()将崩溃。

所以,要么你Include()你的实体急于加载,要么你稍后以懒惰的方式Load()它。