实体框架渴望加载关联的集合,但不会延迟加载 [英] Entity Framework eager loads associated collection but won't lazy load it

查看:104
本文介绍了实体框架渴望加载关联的集合,但不会延迟加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将Department对象的Studies属性进行延迟加载,但是只有当我热切加载它时,它才会加载.我已将DepartmentId添加到Study类,但没有结果,使用了ICollectionISetvirtual.公共和私人二传手似乎没有什么不同(应该没有).似乎没有任何作用.使用EF 6.1.

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

推荐答案

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

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

这篇关于实体框架渴望加载关联的集合,但不会延迟加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆