Search code examples
c#entity-frameworklinqlinq-to-sqlsql-to-linq-conversion

Convert paging logic from SQL to Linq


I am totally new to Linq. I need to convert paging logic from SQL to Linq. My paging logic in SQL is:

where num BETWEEN ((@pageNumber-1)*@pageSize) + 1 and (@pageSize * @pageNumber)

So, if pageNumber is 2 and pageSize is 30, my query will pull records from row 31 up-to row 60.

I implemented same logic in LINQ, but it pulls wrong no of records:

query.Skip(pageNumber - 1).Take(pageSize * pageNumber).AsQueryable();

Can someone please, tell me what is wrong in my LINQ query.


Solution

  • You have to multiply what you skip by the page size, the same way as in SQL, and take the desired rows next. So for you it would be like:

    query.Skip((pageNumber - 1)*pageSize).Take(pageSize).AsQueryable();