Home > Software design >  Linq many to many relationship with no foreign key
Linq many to many relationship with no foreign key

Time:06-01

I'm struggling with many to many relationships using linq where there is no foreignkey but where the intersection table has been created for me behind the scenes based on a collection of entities on a model.

Given the following classes

public class BaseEntity
{
    public int Id { get; set; }

    public DateTime DateUpdated { get; set; }
}

public class Student : BaseEntity
{
    public string Name { get; set; }

    [JsonIgnore]
    public ICollection<Course> Courses { get; set; }
}

public class Course : BaseEntity
{
    public string Name { get; set; }

    public ICollection<Student> Students { get; set; }
}

and the tables that were created

dbo.Courses
dbo.Students
dbo.CourseStudent // (but this is not in my context class as ef generated it for me when I ran my migration)

I'm using Blazor and in one of my components I get a student, from there I want to get the courses that student is assigned to but I'm having trouble with the query and have tried the below and many others

// What I'm trying to achieve
// select * from courses where students.id == id
// or
// select * from courses where students contains student.id

public async Task<List<Course>> GetByStudent(int id) // studentId
{
    return await _db.Courses.GroupBy(x => x.Students.Where(x => x.Id == id)).ToList();
    return await _db.Courses.Include(x => x.Students).Where(x => x.Id == id).ToListAsync();                              
}

Thanks for reading, I do hope it makes sense!

Can anyone can point me in the right direction of how I can get all courses for a single student by the student navigation property.

Or, ways to access a navigation property using linq without a foreign key.

CodePudding user response:

direction of how I can get all courses for a single student by the student navigation property.

context.Students.Include(s => s.Courses).First(s => s.Id == studentId)

The Include makes EF write the joins to bring the related courses in for the student. That it's going through a mapping table is EF's job to sort out, rather than yours..

Side note, that though include does joining it isn't necessarily required in cases where you mention properties and navigations explicitly in a where or select clause. See Gert's detailed answer here for more info on the interplay between Include and Select

  • Related