LINQ to Entities无法识别方法’System.Linq.IQueryable`

我想运行这个LINQ简单代码在LINQ中有记录号,但结果是错误的

var model = _db2.Persons.Select( (x, index) => new { rn = index + 1, col1 = x.Id }).ToList(); 

错误:

LINQ to Entities无法识别方法’System.Linq.IQueryable 1[f__AnonymousType2 2 [System.Int32,System.Int32]]选择[Person, f__AnonymousType2 2](System.Linq.IQueryable 1 [MvcApplication27.Models] .Person],System.Linq.Expressions.Expression 1[System.Func 3 [MvcApplication27.Models.Person,System.Int32, f__AnonymousType2`2 [System.Int32,System.Int32]]])’方法,这个方法无法转换为商店表达式。

问题是LINQ to Entities不了解如何将Select重载(提供索引的重载)转换为SQL查询。 你可以通过首先从你需要的数据库中选择部分来解决这个问题(避免不必要地选择每一列),然后执行AsEnumerable()将其作为IEnumerable而不是IQueryable ,然后执行Select纯粹在C#中(简而言之, IQueryable被转换为SQL,而IEnumerable则在代码中运行)。

 var model = _db2.Persons.Select(x => x.Id).AsEnumerable().Select( (id, index) => new { rn = index + 1, col1 = id }).ToList(); 

请注意,您拥有的查询似乎是无序的,因此每次调用时,id / index配对都可以更改。 如果您期望一致性,您应该按某种方式订购(例如_db2.Persons.OrderBy(...) )。

编辑

添加Scott的评论:

作为一个很好的参考, 这里是框架中内置的所有Linq语句的列表,以及它是否兼容的列表 。

您可以选择Id,然后使用linq to objects创建自己的匿名对象,对于示例:

 var model = _db2.Persons.Select(x => x.Id) .ToList() // return int[] .Select((id, index) => new { rn = index + 1, col1 = id }) // return anonymous[] (with rn and col1) .AsEnumerable(); // get an IEnumerable (readonly collection) 

可能这是因为entity framework不支持这种使用linq的查询,因为linq可以在内存中执行,因此,在这种情况下,您可以选择只需要(在您的情况下为id )并使用ToList()方法执行它为了具体化您的查询,之后您将有一个内存列表,因此,您可以使用linq到对象并使用所需的支持方法。