[英]Compare Array of IDs Entity Framework
我有一個想要編寫LINQ查詢的簡單方案,但是我無法正確完成。 這是場景:
我有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
對於這種情況,我想傳遞課程ID的數組來查詢並返回所有針對他們注冊了所有這些課程的學生。 我試過的
int[] cIds = {1,2,4 };
var result = from s in context.Students
where s.StudentCourses.Any(sc=> cIds.Contains(sc.CID))
select s;
但是,這將返回已注冊課程ID 1、2、4的學生。 希望你理解我的問題。
謝謝您的幫助。
用這個:
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();
或者,如果您更喜歡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();
這是使用linq-to-objects的小提琴 。
編輯:
我沒有注意到,在您的模型中,有一個從Student
到StudentCourse
的導航屬性,在這種情況下,查詢會簡單得多,不需要聯接, Patrick的答案非常有效。
請嘗試以下操作:
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.