Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Dynamic paging in Entity Framework

0.00/5 (No votes)
14 Apr 2014 1  
Appropriate query to fetch required no of results from DB instead of getting all at on time for binding controls like Gridview, listview etc

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.

/// <summary>
/// Pages the specified query.
/// </summary>
/// <typeparam name="T">Generic Type Object</typeparam>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="query">The Object query where paging needs to be applied.</param>
/// <param name="pageNum">The page number.</param>
/// <param name="pageSize">Size of the page.</param>
/// <param name="orderByProperty">The order by property.</param>
/// <param name="isAscendingOrder">if set to <c>true</c> [is ascending order].</param>
/// <param name="rowsCount">The total rows count.</param>
/// <returns></returns>
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;
    
    //Total result count
    rowsCount = query.Count();
    
    //If page number should be > 0 else set to first page
    if (rowsCount <= pageSize || pageNum <= 0) pageNum = 1;
    
    //Calculate nunber of rows to skip on pagesize
    int excludedRows = (pageNum - 1) * pageSize;

    query = isAscendingOrder ? query.OrderBy(orderByProperty) : query.OrderByDescending(orderByProperty);
    
    //Skip the required rows for the current page and take the next records of pagesize count
    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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here