-1

In EF, when having to deal with indexes, we need to convert the entity collection to a list as IQueryable or IEnumerable do not implement any indexer (it would be meaningless due to the deferred execution mechanism). When having a pretty large collection using ToList for using indexes would be heavy.

This is why I sometimes need to look up entities by the row number (not the identity / primary key). For example, I have one record, I want to get its row number (position in the sorted table) and get the next record.

Can this be achieved in Entity Framework? I can send SQL queries to do this, but I'm curious if there is a Linqish and EF specific approach to do this.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Arnold Zahrneinder
  • 4,788
  • 10
  • 40
  • 76

1 Answers1

1

This is possible through tweaking the DbContex and adding a fake entity that corresponds to the row number. This entity can be exploited for using the built-in ROW_NUMBER() function in SQL. For instance:

public class RowNumber{
    public Int64 Row_Number {get; set;}
} 

followed by adding these two the DbContext

public virtual DbSet<RowNumber> RowNumber {get; set;}

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<RowNumber>(x => {
            x.HasKey(e => e.Row_Number);
        });
 ...
}

Now we can make the following query:

var rowNumber = dbContext.Set<RowNumber>().FromSql("SELECT Row_Number FROM (SELECT ROW_NUMBER() OVER(ORDER BY [Column] DESC) AS Row_Number, [Column] FROM [Table]) AS Query WHERE [Column] = {0}").ToList();

And yeah this is more efficient and of higher performance!

Arnold Zahrneinder
  • 4,788
  • 10
  • 40
  • 76