1

我有一个清单:

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;

但我不想使用它,因为我遇到了必须比较超过 2 个 ID 的情况,这意味着,我必须分开 2 个以上primitive datatype List并在查询中使用它们,这是我不想要的.

如何在 linq 查询中直接使用外部列表。??

我不能使用这个:

allSchools.Where(s=>s.LocationId==this.LocationId ||
lstStudents.Contains(s)).ToList();

请帮助...我经历了这个这个..但它们对我没有帮助..

4

2 回答 2

1

问题是实体框架无法将您的学生列表转换为有效的 SQL 语句 - 显然数据库服务器对您的课程一无所知Student,因此实体框架无法将 LINQ 查询转换为数据库服务器可以理解的内容。有三种解决方案。

  1. 如果可能,请摆脱您的方法GetConditionalStudents()并直接将构建此列表的查询包含在主查询中。

  2. 通过调用相应的查询和使用 LINQ to Objects 处理这两个列表,lstStudents将这两个列表提取到内存中。allSchoolsToList()

  3. 使用对象 ID 而不是对象,因为 Entity Framework 能够将整数、字符串等列表转换为IN语句。

在我看来,您似乎已经在执行选项二,但显然您不是因为代码失败,但我无法确定确切的缺陷。

于 2013-02-16T00:39:15.733 回答
0

尝试:

var schools = from p in allSchools
              where (p.LocationId==this.LocationId && p.Students.Any(s => lstStudents.Contains(s)))
              select p;
于 2013-02-15T23:13:03.857 回答