我将实体框架与点网框架一起使用
例如,我有像
这样的学生班public class Student
{
public int StudentId { get; set; }
public int Age { get; set; }
public int DepartmentId { get; set; }
public string Name { get; set; }
}
当我需要在许多系中寻找学生时,我可以像下面这样
List<Student> students = new List<Student>
{
new Student{Age = 12,DepartmentId =1 },
new Student{Age = 11,DepartmentId =2 },
new Student{Age = 11,DepartmentId =3 },
new Student{Age = 13,DepartmentId =4 },
};
// get all department ids
var departmentIds = students.Select(s => s.DepartmentId);
var studentList = DbContext.Students.Where(s=>departmentIds.Contains(s.DepartmentId)).ToList();
这将生成类似SQL查询
Select StudentId , Age , DepartmentId , Name
From Students where DepartmentId in (1 , 2 , 3 , 4)
我的问题
我需要搜索与学生列表中的任何项目匹配的任何学生 类似于以下查询
Select StudentId , Age , DepartmentId , Name
From students
Where
(departmentId= 1 and age = 12)
OR
(departmentId= 2 and age = 11)
OR
(departmentId= 3 and age = 12)
OR
(departmentId= 4 and age = 13)
答案 0 :(得分:0)
存储每个部门的年龄并写
var departmentAge = departments.ToDictionary(d => d.DepartmentId, d => d.RequiredAge);
然后
.Where(s => departmentIds.Contains(s.DepartmentId) && s.Age == departmentAge[s.DepartmentId])
第二部分不可翻译为SQL。您可能需要用AsEnumerable
分隔它,或将查询中的两个表连接起来以获得类似的信息
Select s.StudentId, s.Age, s.DepartmentId, s.Name
From Students s inner join Departments d
where s.DepartmentId in (1 , 2 , 3 , 4) and s.Age = d.RequiredAge
答案 1 :(得分:0)
根据Henk Holterman的评论,只需将其写出
List<Student> students = new List<Student>
{
new Student{Age = 12,DepartmentId =1 },
new Student{Age = 11,DepartmentId =2 },
new Student{Age = 11,DepartmentId =3 },
new Student{Age = 13,DepartmentId =4 },
};
var studentList = DbContext.Students.Where(s=> (s.DepartmentId == students[0] &&
s.Age == students[0]) || (s.DepartmentId == students[1] && s.Age ==
students[1]) || (s.DepartmentId == students[2] && s.Age ==
students[2]) || (s.DepartmentId == students[3] && s.Age ==
students[3])).ToList();