Timothy Ghanem Timothy Ghanem - 1 month ago 5
C# Question

IQueryable.Skip And IQueryable.Take Upper Bound

I am using Entity Framework to query a database and i use the following:

context
.MyTable
.Where(...)
.Where(...)
.OrderBy(...)
.Skip((int)numberOfItemsToSkip)
.Take((int)numberOfItemsToTake)
.ToArray();


My question is about the part
Skip((int)numberOfItemsToSkip)
. It only accepts an
Int32
argument which has an upper bound of
Int32.MaxValue
. Now, what if the
MyTable
contains more than
Int32.MaxValue
records. The reason i say this is because the database i have is HUGE and grows substantially and that's why i came across the case that
Int32.MaxValue
might not be enough. My database is hosted on SQL Server.

So, is there any built-in way to pass a
Int64
argument instead? I can go ahead and do something manual, but my question is about something from within Entity Framework.

Answer

You can try to repeat Skip several times:

context
    .MyTable
    .Where(...)
    .Where(...)
    .OrderBy(...)//you forgot it
    .Skip(numberOfItemsToSkip1)
    .Skip(numberOfItemsToSkip2)
    .Take(numberOfItemsToTake)
    .ToArray();

Resulted SQL (EF 6.1.3, SQL Server 2012):

SELECT *
    FROM [dbo].[Table]
    WHERE ....
    ORDER BY ...
    OFFSET numberOfItemsToSkip1 + numberOfItemsToSkip2 ROWS FETCH NEXT numberOfItemsToTake ROWS ONLY
Comments