ehs*_*san 19 .net c# linq entity-framework
我想运行这个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__AnonymousType22 [System.Int32,System.Int32]]选择[Person,<> f__AnonymousType22](System.Linq.IQueryable1 [MvcApplication27.Models.Person],System.Linq.Expressions.Expression1[System.Func3 [ MvcApplication27.Models.Person,System.Int32,<> f__AnonymousType2`2 [System.Int32,System.Int32]]])'方法,并且此方法无法转换为商店表达式.
Tim*_* S. 22
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(...)).
Edit
Adding comment from 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)
发生这种情况可能是因为实体框架不支持使用 linq 的这种查询,因为 linq 可以在内存中执行,因此,在这种情况下,您可以选择您需要的(id在您的情况下)并执行它,使用ToList()方法来具体化您的查询之后,您将在内存中获得一个列表,因此,您可以使用 linq to 对象并根据需要使用支持的方法。
| 归档时间: | 
 | 
| 查看次数: | 16186 次 | 
| 最近记录: |