I need an EF query to get the row number of a specific entity.
I've looked at this, and this.
Currently I have it working in this way:
private DbContext Context;
public int GetRowNumberQuery<TEntity>(int entityId)
{
var allEntities = this.Context.Set<TEntity>().ToList();
return allEntities
.Select((entity, index) => new { Index = index, Entity = entity })
.Where(x => x.Entity.Id == entityId)
.Select(x => x.Index)
.SingleOrDefault();
}
Obviously, this is very inefficient as it gets a list of all entities before selecting the index. If I remove the .ToList() in the first line, making the whole thing a LINQ query, it fails at the first Select with NotSupportedException saying:
LINQ to Entities does not recognize the method 'System.Linq.IQueryable
1[<>f__AnonymousType1
2[System.Int32,MyEntityType]] Select[MyEntityType,<>f__AnonymousType12](System.Linq.IQueryable
1[MyEntityType], System.Linq.Expressions.Expression1[System.Func
3[MyEntityType,System.Int32,<>f__AnonymousType1`2[System.Int32,MyEntityType]]])' method, and this method cannot be translated into a store expression.
Can you please tell me how to get the ROW_NUMBER of a specific entity? Or is it impossible like this pretty old question suggests?