0
votes

I have a model class with lazy loading on. Until now I always used lazy loading, for example loading a single student with a collection of his courses.

If I want to load all the courses with the collection of all students who are enrolled, can I use the Include() method of eager loading on a property with lazy loading on? Are there any side effects?

[ForeignKey("Id")]
public virtual ICollection<Students> Students { get; set; }
public IQueryable<Students> GetCoursesWithAllStudents()
{
     return db.Courses.Include(c => c.Students);
}
1
No problems, no side effects.Camilo Terevinto

1 Answers

1
votes

Yes, you can. Include() specifically does that, it includes related entities: it forces them to be loaded when normally they aren't. You might add ThenInclude() to go deeper down the relationship ladder, as it allows to load data related to the previously included entity.
However, the returned entity is the highest one in the ladder, not the latest. In the following example, an IQueryable<Professors> is returned, with the Courses entities loaded and, inside the Courses, the Students.

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