Entity Framework eager loads associated collection but won't lazy load it

被刻印的时光 ゝ 提交于 2019-12-11 19:08:30

问题


I've tried to get the Studies property of the Department object to lazy load, but it will only load when I eagerly load it. I've added a DepartmentId to the Study class with no results, used ICollection, ISet and virtual. Public and private setters seems to make no difference (and it shouldn't). Nothing seems to work. Using 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

回答1:


Your Study class needs a public or protected parameterless constructor to work with lazy loading: MSDN




回答2:


You need to actually load Studies:

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

Otherwise they won't exist and First() will crash.

So either you Include() your entity for eager loading, or you Load() it later in a lazy way.



来源:https://stackoverflow.com/questions/23331244/entity-framework-eager-loads-associated-collection-but-wont-lazy-load-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!