EF中的多对多关系linq查询 [英] Many to many relation linq query in EF
问题描述
我有3个表Student,Course和链接表StudentCourse,在给定学生ID = 1的情况下,如何返回所有课程,还包括其中学生ID可能不为1并且与该学生的课程相同的行ID 1?结构是这样的:
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
所以棘手的部分是我还想包括课程8或ID为1的学生修读的任何其他课程的其他行.
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.
最终结果应该是2行:where子句将指定我对学生id = 1(这是id 8的课程)的课程感兴趣,但是我也想包括该课程的其他行.结果是:
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
推荐答案
鉴于这是EF,您的最新说明是,您在Student
实体上应具有Courses
导航属性,而在Course
实体,您可以执行以下操作:
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();
这篇关于EF中的多对多关系linq查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!