LINQ到实体不能识别方法“System.Linq.IQueryable` [英] LINQ to Entities does not recognize the method 'System.Linq.IQueryable`
问题描述
我要运行这个LINQ简单的code有在LINQ备案号,但结果是错误的下面
VAR模型= _db2.Persons.Select(
(X,指数)=>新
{
RN =指数+ 1,
COL1 = x.Id
})了ToList()。
错误:
LINQ到实体不能识别方法 System.Linq.IQueryable
1 [<> f__AnonymousType2
2 [System.Int32的,System.Int32的],选择[人物,与LT;> f__AnonymousType22](System.Linq.IQueryable
1 [MvcApplication27.Models.Person],System.Linq.Ex pressions.Ex pression1 [System.Func
3 [MvcApplication27.Models.Person,System.Int32的,<> f__AnonymousType2`2 [System.Int32中,System.Int32的]]])'方法,和这种方法不能被翻译成存储 EX pression。
问题是,LINQ到实体不明白如何转换选择
过载(一,让你的索引)转换成SQL查询。您可以先选择需要从你的数据库的部分(避免选择每一列不必要的)解决这个问题,然后做 AsEnumerable()
来把它当作一种的IEnumerable< T>
而不是一个的IQueryable< T>
,然后做选择
纯粹在C#(简称的IQueryable< T>
,则转换为SQL,而的IEnumerable< T>
s的在code运行)。
VAR模型= _db2.Persons.Select(X => x.Id)。.AsEnumerable()选择(
(同上,指数)=>新
{
RN =指数+ 1,
COL1 = ID
})了ToList()。
请注意,当你拥有了它的查询似乎是无序的,所以ID /指数配对可以改变每次调用此。如果你期望的一致性,你应该通过一些命令(例如 _db2.Persons.OrderBy(...)
)。
I want to run this LINQ simple code to have record number in LINQ but result is beneath error
var model = _db2.Persons.Select(
(x, index) => new
{
rn = index + 1,
col1 = x.Id
}).ToList();
Error:
LINQ to Entities does not recognize the method 'System.Linq.IQueryable
1[<>f__AnonymousType2
2 [System.Int32,System.Int32]] Select[Person,<>f__AnonymousType22](System.Linq.IQueryable
1 [MvcApplication27.Models.Person], System.Linq.Expressions.Expression1[System.Func
3 [MvcApplication27.Models.Person,System.Int32,<>f__AnonymousType2`2 [System.Int32,System.Int32]]])' method, and this method cannot be translated into a store expression.
The problem is that LINQ to Entities doesn't understand how to convert that Select
overload (the one that gives you the index) into a SQL query. You can fix this by first selecting the portion from the DB you need (to avoid selecting every column unnecessarily), then doing AsEnumerable()
to take it as an IEnumerable<T>
instead of an IQueryable<T>
, and then doing the Select
purely in C# (in short, IQueryable<T>
s are converted to SQL, while IEnumerable<T>
s are run in code).
var model = _db2.Persons.Select(x => x.Id).AsEnumerable().Select(
(id, index) => new
{
rn = index + 1,
col1 = id
}).ToList();
Note that the query as you have it appears to be unordered, so the id/index pairings can change each time you call this. If you expected consistency, you should order by something (e.g. _db2.Persons.OrderBy(...)
).
这篇关于LINQ到实体不能识别方法“System.Linq.IQueryable`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!