LINQ to Entities does not recognize the method 'System.Linq.IQueryable`

前端 未结 2 1883
感动是毒
感动是毒 2020-12-30 22:16

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 
             


        
2条回答
  •  囚心锁ツ
    2020-12-30 22:26

    You could just select the Id and after it create your own anonymous object using linq to objects, for sample:

    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)
    

    Problably this is happen because Entity Framework does not support this kind of query using linq as linq could do in memory, so, in this case, you could select just you need (id in your case) and execute it, using ToList() method to concretize your query and after that you will have a list on memory, so, you can use linq to objects and use the supported method as you want.

提交回复
热议问题