实体框架渴望加载相关的集合,但不会延迟加载它

时间:2014-04-28 01:34:12

标签: c# .net entity-framework entity-framework-6.1

我试图将Studies对象的Department属性设置为延迟加载,但只有在我急切加载它时才会加载。我在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 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

您需要实际加载研究:

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

否则他们不会存在,First()会崩溃。

因此,要么Include()您的实体需要加载,要么以Load()稍后以懒惰的方式加载它。