EF中的多对多关系linq查询 [英] Many to many relation linq query in EF

查看:665
本文介绍了EF中的多对多关系linq查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆