我在以下场景中遇到LINQ Query问题:
我有Activity和ActivityTeacher两个表和一些教师列表。
Activity Table
ActivityID Date Class
1 4/4/2012 1
2 4/5/2013 2
3 4/6/2013 5
4 5/6/2013 2
5 5/16/2013 1
6 5/20/2013 8
7 5/21/2013 7
8 6/22/2013 6
9 8/10/2013 5
10 8/12/2013 4
ActivityTeacher Table
ActivityID TeacherID
1 2
1 3
1 4
2 6
3 6
3 6
3 4
2 5
4 2
4 3
4 6
5 8
5 7
5 6
6 6
6 7
6 9
6 10
6 1
6 2
7 2
7 8
7 9
7 10
8 3
8 4
8 6
8 7
9 10
9 3
9 2
10 1
10 2
教师名单= {2,3,4} 现在我想根据教师名单从活动中选择记录= {2,3,4} 不使用foreach循环。
答案 0 :(得分:2)
Activity
实体应具有您可以使用的Teachers
导航属性:
context.Activities
.Where(x => listOfTeachers.Contains(x.Teachers.Select(t => t.TeacherId)));
如果listOfTeachers
包含三个ID 2,3,4,则此查询应转换为类似于以下内容的SQL:
select a.*
from Activity a
inner join ActivityTeacher at
on a.activityid = at.activityid
where at.teacherid in (2, 3, 4);