Search code examples
c#asp.net-mvc-3paginationrepository-pattern

Need some tips on how to create a paging mechanism on a single table using Repository pattern


I have a simple table called News.

I'm using Entity Framework to generate a model for me, and I'm using the Repository pattern to access each News record.

Assume a simple model, where PublishDate is a DateTime property:

News
--------
NewsID
Title
Body
PublishDate 

I need to figure out a paging mechanism for retrieving these records.

Something like:

public IQueryable<News> FindNews(int? page)
{
    //Something here?
}

Any tips or working example code? I need to fetch the latest 5 news records if no page is selected, but if a page is selected fetch the appropriate records for that page.

I can't provide any more code as I don't know where to begin.


Solution

  • Try

    public IQueryable<News> FindNews(int? page)
    {
        IQueryable<News> news = db.News.OrderByDescending(n => n.PublishDate);
    
        if (page != null)
           news = news.Skip(page.Value * 5);
    
        return news.Take(5);
    }