Rod
Rod

Reputation: 15423

Is there a linq equivalent to raw sql for paging

I think the following efficiently works whether there are 10 records or 10 million records. Is there a linq equivalent that works like this?

    class Program
    {
        static void Main(string[] args)
        {
            using (var ctx = new pubsEntities())
            {
                //this will throw an exception
                var studentName = ctx.Database.SqlQuery<employee>(@"
;with CTE AS
(
SELECT *, ROW_NUMBER() over(order by emp_id) AS RowNumber
FROM employee
)
SELECT * FROM CTE
WHERE RowNumber > 2 AND RowNumber <= (2 + 4)
                ").ToList();
            }
        }
    }

Upvotes: 0

Views: 108

Answers (1)

Adam Wells
Adam Wells

Reputation: 581

You can use IQueryable<T>.Skip(x).Take(x) to simulate Paging.

Its pretty simple. If we're looking at your code, you'd want something like this:

var pageSize = 100;
var startPage = 2;
var skipAmount = pageSize * startPage;
ctx.Database.Employee.Skip(skipAmount).Take(pageSize);

Upvotes: 1

Related Questions