我可以同时使用eager和lazy加载吗?

时间:2019-07-05 08:21:16

标签: c# entity-framework entity-framework-6

我有一个延迟加载的模型类。到现在为止,我一直都使用惰性加载,例如,将单个学生及其课程集合加载。

如果我想加载所有课程并包含所有已注册学生的集合,我可以使用Include()方法在一个懒惰加载的属性上渴望加载吗?有副作用吗?

[ForeignKey("Id")]
public virtual ICollection<Students> Students { get; set; }
public IQueryable<Students> GetCoursesWithAllStudents()
{
     return db.Courses.Include(c => c.Students);
}

1 个答案:

答案 0 :(得分:0)

是的,可以。 Include()专门这样做,它包括个相关实体:它通常在正常情况下不加载它们。您可以添加ThenInclude()来深化关系阶梯,因为它允许加载与先前包含的实体相关的数据。
但是,返回的实体是阶梯中的最高实体,而不是最新实体。 在下面的示例中,返回一个IQueryable<Professors>,其中加载了Courses个实体,并在Courses内包含了Students

public IQueryable<Professors> GetCoursesWithAllStudents()
{
     return db.Professors.Include(professor => professor.Courses)
                         .ThenInclude(course => course.Students);
}
相关问题