5

I'm creating page with pagination, and got method that takes argument page and numberOfElementsPerPage.

In this method im using Linq to Entities to load elements for page:

public List<Item> GetElements(int page, int numberOfElementsPerPage)
{
    return DataContext.Items.OrderBy(x => x.Id).Skip((page-1)*numberOfElementsPerPage).Take(numberOfElementsPerPage);
}

What I want to ask, how does this Skip/Take works? Does it take first all records from database, order and then Skip/Take? If yes I think this is pretty bad solution if the database got 100000 records for example or even more. So whats the best solution?

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
CSharpBeginner
  • 1,625
  • 5
  • 22
  • 36
  • No, the EF query provider will translate this to SQL and the paging will be executed by the database. This is the best solution. – Charles Mager Jun 27 '15 at 11:14

3 Answers3

2

So whats the best solution?

This is the best solution.

If yes I think this is pretty bad solution

You are right, had it been implemented that way, it would be a pretty bad solution. Fortunately, it is not implemented that way: the values from Skip and Take are passed to your RDBMS server in a way specific to the SQL dialect, at which point the database decides how to find and serve you the records. In case of SQL Server, syntax similar to this one is used:

SELECT ...
FROM ...
WHERE ...
...
OFFSET <skip-value> ROWS
FETCH NEXT <take-value> ROWS ONLY;
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

If it's Entity Framework DataContext then it generates appropriate SQL which retrieves only records you need. You can use SQL profiler to verify it.

Disappointed
  • 1,100
  • 1
  • 9
  • 21
0

I agree with all answers and I just want to add that you can actually see the generated SQL query to confirm. Please check this post

How do I view the SQL generated by the entity framework?

Community
  • 1
  • 1
Carlos
  • 241
  • 5
  • 11