Introduction
There are some applications where we need to display large sets of data. In order to display this large sets of data we usually follow the approach of Data paging.
In ASP.NET there are data bound controls like Gridview, listview etc that can facilitate paging.
The problem with this databound controls is that they perform paging on complete datasets.
The asp.net databound controls brings the complete datasets and then perform paging at the application serverside. This can led to network overload and server memory consuming every time user requests new data page.
Paging done at the database level is the best technique to optimize performance. Inorder to achieve this we have to build the appropriate query that will return only the required page result items.
Using the code
The following is an implementation of a simple extension method to offer paging functionality to simple Enitity framework or Linq to Sql query providers.
private static IQueryable<T> PagedResult<T, TResult>(IQueryable<T> query, int pageNum, int pageSize,
Expression<Func<T, TResult>> orderByProperty, bool isAscendingOrder, out int rowsCount)
{
if (pageSize <= 0) pageSize = 20;
rowsCount = query.Count();
if (rowsCount <= pageSize || pageNum <= 0) pageNum = 1;
int excludedRows = (pageNum - 1) * pageSize;
query = isAscendingOrder ? query.OrderBy(orderByProperty) : query.OrderByDescending(orderByProperty);
return query.Skip(excludedRows).Take(pageSize);
}
Example to use:
Lets assume a simple query that returns some articles from an Articles table.
We will call this method to get the first 20 items for the first page.
var articles = (from article in Articles
where article.Author == "Abc"
select article);
int totalArticles;
var firstPageData = PagedResult(articles, 1, 20, article => article.PublishedDate, false, out totalArticles);
or simply for any entity
var context = new AtricleEntityModel();
var query = context.ArticlesPagedResult(articles, <pageNumber>, 20, article => article.PublishedDate, false, out totalArticles);
Accordingly this method can be invoked by passing the page number for other pages.