在一个查询中根据Linq中的外部列表筛选给定的列表
本文关键字:列表 Linq 外部 筛选 查询 一个 | 更新日期: 2023-09-27 17:59:50
我有一个列表:
List<Student> lstStudents = GetConditionalStudents();
我有另一个清单:
List<School> allSchools = dbContext.Schools.ToList();
每所学校都有学生名单
public class School
{
///other properties
public List<Student> {get;set;}
}
我被迫这么做:
List<School> schools = from p in allSchools
where p.LocationId==this.LocationId
where p.Students.Any(d=>lstStudents.Contains(d))
select p;
但它不起作用:给出错误
unable to create a constant value for .. only primitive types
编辑
我可以这样做:
List<int> integers = lstStudents.Select(s=>s.Id).ToList();
List<School> schools = from p in allSchools
where p.LocationId == this.LocationId
where p.Students.Any(d=>integers.Contains(d.Id))
select p;
但我不想使用它,因为我在某些情况下必须比较两个以上的Id,这意味着,我必须制作两个以上单独的primitive datatype List
,并在查询中使用它们,这是我不想要的。
如何在linq查询中直接使用外部列表。??
我不能使用这个:
allSchools.Where(s=>s.LocationId==this.LocationId ||
lstStudents.Contains(s)).ToList();
请帮忙。。。我经历了这个和这个。。但它们对我没有帮助。
问题是Entity Framework无法将您的学生列表转换为有效的SQL语句-显然数据库服务器对您的Student
类一无所知,因此Entity Framework不能将LINQ查询转换为数据库服务器能够理解的内容。有三种解决方案。
-
如果可能的话,去掉你的方法
GetConditionalStudents()
,直接把构建这个列表的查询包括在主查询中。 -
通过对各自的查询调用
ToList()
,将两个列表lstStudents
和allSchools
提取到内存中,并使用LINQ to Objects处理这两个列表。 -
使用对象ID而不是对象,因为实体框架能够将整数、字符串等列表转换为
IN
语句。
对我来说,看起来你已经在做选项二了,但显然你没有,因为代码失败了,但我无法确定确切的缺陷。
尝试:
var schools = from p in allSchools
where (p.LocationId==this.LocationId && p.Students.Any(s => lstStudents.Contains(s)))
select p;