I have 3 tables Student, Course, and the linking table StudentCourse, how do i return all the courses given a student Id = 1 but also include row where the student id might not be 1 and is taking same course as student of id 1? The stucture is like this:
student courses studentcourse
1 8 1 - 8
2 9 2 - 8
3 10 3 - 9
so the tricky part is that i also want to include the other rows for course 8 or any other course taken by Student of id 1.
the final result should be 2 rows: the where clause will specify that I am interested in the course where student id = 1 (which is course of id 8) but i also want to include the other rows from that course. So the result is :
1 - 8
2 - 8
Given that this is EF and your latest clarification you should have a Courses
navigation property on your Student
entity and a Students
navigation on your Course
entity that would allow you to do the following:
var students = db.Students
.Single(x=> x.Id == 1)
.Courses.SelectMany(c=> c.Students)
.Distinct();
来源:https://stackoverflow.com/questions/9510297/many-to-many-relation-linq-query-in-ef