Get the total number of records when doing pagination
Asked Answered
S

2

24

To get a page from a database I have to execute something like this:

var cs = ( from x in base.EntityDataContext.Corporates
   select x ).Skip( 10 ).Take( 10 );

This will skip the first 10 rows and will select the next 10.

How can I know how many rows would result because of the query without pagination? I do not want to run another query to get the count.

Sectarian answered 5/1, 2010 at 19:52 Comment(0)
B
35

To get the total number of records before skip/take you have to run a separate query. Getting the actual number returned would use Count(), but wouldn't result in another query if the original query was materialized.

var q = from x in base.EntityDataContext.Corporates 
        select x;

var total = q.Count();
var cs = q.Skip(10).Take(10);
var numberOnSelectedPage = cs.Count();
Balsamiferous answered 5/1, 2010 at 19:56 Comment(2)
Is this separation of 2 query results in lower perfomence for lots of data and complex where conditions?Vicinage
We are looking for something equivalent to COUNT(1) OVER(). like in sql i can write this query: SELECT name, overall_count = COUNT(1) OVER() FROM sys.all_objects ORDER BY name OFFSET (@PageNum-1)*@PageSize ROWS FETCH NEXT @PageSize ROWS ONLY; Can I write the same with linq/EF?Turdine
E
20

Bottom line: you have to run two queries. You simply can't get around it.

Here's a good way to do it, however, that caches the original LINQ query and filter, making for less copy/paste errors:

var qry = from x in base.EntityDataContext.Coporates select x;
var count = qry.Count();
var items = qry.Skip(10).Take(10).ToList();
Exemplification answered 5/1, 2010 at 19:58 Comment(4)
I just thought about doing so - but a question; will calling the q.Count(); load all records in memory?Sectarian
No, q.Count() will generate an SQL SELECT COUNT(*) query.Stallard
No. Calling q.Count() will result in SQL along the lines of SELECT count(*) where ..., which will only return an integer value. No records will be loaded into memory.Exemplification
HAHA you simply cant get around it. I figured out this solution but didn't trust myself!Ultraconservative

© 2022 - 2024 — McMap. All rights reserved.