2

Lets say you have the following entity realtionship

School ||---|< Course >|--|< Student

Worst drawing ever, but a school can have several courses, and a course can have several students.

In EF I would normally do it like this to get all the data:

return _db.School
       .Include(t => t.Classes)
       .ThenInclude(c => c.Course)
       .ThenInclude(s => s.Student)

But let say I only want students with name Billy. Then I would guess I could to it like this

return _db.School
           .Include(t => t.Classes)
           .ThenInclude(o => o.Course)
           .ThenInclude(o => o.Student.Where(s => s.Studen.name.Equals( "Billy"))

Not possible as far as I can see, so therefore I do it like this:

return _db.School
     .Select(school => new School()
           {
               Id = school.Id
               Name = school.Name
               Courses = school.Courses.Select(courses => new Course() 
                    {
                       Id = course.Id,
                       Name = course.Name
                       Students = course.Students.Select(student => new Student()
                           {
                               Id = student.Id,
                               Name = student.Name
                           }).Where(s => s.Name.Equals("Billy"));
                     })
               });
etc....

There must be a better way? Any suggestions?

The code is just mocked, so might be a bunch of syntax errors and typos. But you get the idea.

Ørjan
  • 2,749
  • 2
  • 16
  • 24
  • What is the expected aggregate you want to see? Select all students where name is "Billy" or select schools with courses where any Billy is involved, or what is expected result? – WueF Dec 13 '18 at 09:51
  • 2
    Filtered `Include` is not supported. Try global query filters. – Gert Arnold Dec 13 '18 at 09:54
  • thanks for response, got the answer from this post: https://stackoverflow.com/questions/16798796/ef-include-with-where-clause – Ørjan Dec 13 '18 at 12:11

0 Answers0