Search code examples
c#linqentity-frameworkentity

LINQ to Entities does not recognize the method ElementAt


I'm using the method Queryable.ElementAt(Int32) to get a specific element of a query's result.

IQueryable<MyEntity> entities = db.MyEntities.Where(p => p.ForeignKey == id);

MyEntity entity = entities.ElementAt(i);

But I'm getting the following error:

LINQ to Entities does not recognize the method 'MyEntity ElementAt[MyEntity] (System.Linq.IQueryable`1[MyEntity], Int32)' method, and this method cannot be translated into a store expression.

Why am I getting this error and how can I fix it?


Solution

  • Are you happy to fetch all the "earlier" results? If so, either call ToList() to cache them, or AsEnumerable() to fetch them on each call, with the AsEnumerable just being a way to force the compiler to call Enumerable.ElementAt instead of Queryable.ElementAt.

    There may be a better way (e.g. using Take or Skip) though - could you give more information about the bigger picture?