0

I have a many-to-many relationship set up with Entity Framework like this:

public class Student
{
    public int StudentId { get; set; }
    public string Name { get; set; }

    public ICollection<StudentCourse> StudentCourses { get; set; }
}

public class Course
{
    public int CourseId { get; set; }
    public string Name { get; set; }

    public ICollection<StudentCourse> StudentCourses { get; set; }
}

public class StudentCourse
{
    public int StudentId { get; set; }
    public Student Student { get; set; }

    public int CourseId { get; set; }
    public Course Course { get; set; }
}

This works great, I have Students and I have Courses, and StudentCourses is the many-to-many relationship between them.

I also have an Advisor class, which has a collection of StudentCourses that the Advisor is in charge of:

public class Advisor
{
    public int AdvisorId { get; set; }
    public ICollection<StudentCourse> StudentCourses { get; set; }
}

I would like to get a collection of Advisors and the StudentCourses they're in charge of, but also the data properties from the Student and Course objects (like Name), all at once. This works for me:

var advisors = await _dbContext.Advisors
    .Include(a => a.StudentCourses)
         .ThenInclude(sc => sc.Student)
    Include(a => a.StudentCourses)
        .ThenInclude(sc => sc.Course)
    .ToListAsync();

But is this the only way I can do that? Seems wrong to have that duplicate Include statement

Steven
  • 18,761
  • 70
  • 194
  • 296
  • Possible duplicate of [EF LINQ include multiple and nested entities](https://stackoverflow.com/questions/15764572/ef-linq-include-multiple-and-nested-entities) - see the answer by @NickN – Camilo Terevinto Mar 28 '18 at 20:25
  • Or this question: https://stackoverflow.com/questions/40181872/ef-core-include-on-multiple-sub-level-collections?rq=1 – Camilo Terevinto Mar 28 '18 at 20:26
  • AFAIK that's the only way to include multiple sub- navigation properties. The new Lazy Loading features coming in EF Core 2.1 might alleviate having to write stuff like this so often. – Valuator Mar 28 '18 at 20:26
  • I dont see any relationship for advisor to your StudentCourses. This will result in a Cartesian join – Kevbo Mar 28 '18 at 20:27
  • @CamiloTerevinto - thanks for those, so it looks like what I'm doing IS the correct way to do it, just looks strange – Steven Mar 28 '18 at 20:30
  • It certainly does, but been using EF Core since 1.0 preview and there's no other way... yet – Camilo Terevinto Mar 28 '18 at 20:30
  • *is this the only way* No, you can also use projection -- `select new { ... }` -- and pick the exact properties you need "(like Name)". – Gert Arnold Mar 28 '18 at 22:36

0 Answers0