[英]Compare Array of IDs Entity Framework
I have a simple scenario for which i want to write LINQ query, But i am unable to get it right. 我有一个想要编写LINQ查询的简单方案,但是我无法正确完成。 Here is the scenario:
这是场景:
I have 3 Tables: 我有3张桌子:
STUDENT:
--------------------------
SID Name
---------------------
1 Jhon
2 Mishi
3 Cook
4 Steven
COURSE:
-------------------
CID Name
-------------------
1 Maths
2 Physics
3 Bio
4 CS
STUDENTCOURSE:
---------------------------
SCID SID CID
-----------------------
1 1 1
2 1 2
3 1 4
4 2 1
5 2 2
6 2 3
7 3 1
8 3 4
10 4 2
For this case i want to pass array of course ids to query and return all student those have all the these courses registered against them. 对于这种情况,我想传递课程ID的数组来查询并返回所有针对他们注册了所有这些课程的学生。 What i tried:
我试过的
int[] cIds = {1,2,4 };
var result = from s in context.Students
where s.StudentCourses.Any(sc=> cIds.Contains(sc.CID))
select s;
But this returns students those registered either of the course id 1,2,4. 但是,这将返回已注册课程ID 1、2、4的学生。 Hope you understand my problem.
希望你理解我的问题。
Thanks for the help. 谢谢您的帮助。
Use this: 用这个:
int[] cIds = {1,2,4 };
var q = context.StudentCourses.Join(context.Students,
x => x.SId,
x => x.Id,
(sc, s) => new { Student = s, CourseId = sc.CId })
.GroupBy(x => x.Student.Id)
.Where(sc => cIds.All(cid => sc.Any(y => y.CourseId == cid)))
.Select(x => x.FirstOrDefault().Student)
.ToList();
Or if you prefer linq query: 或者,如果您更喜欢linq查询:
int[] cIds = {1,2,4 };
var q2 = (from s in context.Students
join sc in context.StudentCourses on s.Id equals sc.SId into sCources
where cIds.All(id => sCources.Any(y => y.CId == id))
select s).ToList();
Here is a fiddle for it, using linq-to-objects. 这是使用linq-to-objects的小提琴 。
Edit: 编辑:
I didn't notice that in your model there is a navigation property from Student
to StudentCourse
, in this case the query will be much simpler and does not need join, and Patrick's answer works perfectly. 我没有注意到,在您的模型中,有一个从
Student
到StudentCourse
的导航属性,在这种情况下,查询会简单得多,不需要联接, Patrick的答案非常有效。
Try the following: 请尝试以下操作:
int[] cIds = {1,2,4 };
var result = from s in context.Students
where cIds.All(id => s.StudentCourses.Any(sc=> sc.CID == id))
select s;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.