Luca Romagnoli
Luca Romagnoli

Reputation: 12475

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?

Upvotes: 18

Views: 19161

Answers (2)

Steven
Steven

Reputation: 172835

You can simply mix Skip and First to do the trick:

mds.Skip(i).First()

Upvotes: 27

Jon Skeet
Jon Skeet

Reputation: 1503729

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?

Upvotes: 24

Related Questions