The relationships of my entities: Course records have a one-to-many relationship with Enrollment records. Enrollment records have a one-to-many relationship with Student records.

My Problem: I would like to select a single Course entity and be able to access the Student entities associated to Enrollments associated to the Course. I would like to do this all in one single query, and I want the return type to be Courses. However, the code below throws an exception with the message "Lambda expression used inside Include is not valid."

Courses course = db.Courses.Where(course => course.Id == courseId)
    .Include(course => course.Enrollments)
    .ThenInclude(enrollments => enrollments.Select(enrollment => enrollment.Student))
    .First();

Some alterations I have tried:

  • I tried putting the Include and ThenInclude calls before the Where call to no avail.
  • If I comment out the ThenInclude lines, then this line executes with no error (but without the needed data obviously)
  • I tried refactoring everything in the ThenInclude into the Include, and I got the same runtime exception.
  • I tried using SelectMany instead of Select, and I got the same error.

My Question: Is there some way for me to use Include to select all entities of type a associated with any of the entities of type b that are associated with a given entity of type c?

Preference: I am aware that I can grab all of this data using Select and not use Include at all, but I would like to use Include to do this, if possible.

Other Info Relevant to my Problem: I am using EFCore 3.1.3 and Sql Server 2014.

Let me know if you need any further clarification. Thank you for reading this far :)

P.S. Please edit if you can think of a more concise title for this question.

0

There are 0 best solutions below