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.