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
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:
As a nice reference here is the list of all Linq statements built in to the framework and a listing if it is compatible or not.
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.