Get the total count of pages. | Get the real page number. | Using Skip and Take to Page | The Actual Paging Controls
Ok so the last two posts have been arguably useless, maybe more so than anything else here, but they were somewhat needed because now I am going to show how to Linq, the Entity Framework, and well that’s it I think.
public static IList<ToolItem> GetSomeTools(String name, Int32 numberToShow, Int32 pageNumber, out Int32 realPage, out Int32 totalCountOfPages) { //EntityContext.Context is just a singletonish version of the //Entities class. Most people would use // using (ToolEntities context = new ToolEnties()) Int32 totalCount = EntityContext.Context.ToolItems .Count(item => item.Name == name); //This is the method from the first post of this series //Just getting the count of pages based on numberToShow and //item totalCount totalCountOfPages = TotalCountOfPages(totalCount, numberToShow); //This is the method from the second post of this series //Basically getting the best possible page if the page number //is higher than the totalCountOfPages or lower than 0 realPage = GetRealPage(totalCountOfPages, pageNumber); returnValue = EntityContext.Context.ChatRooms .Where(item => item.Name == name ) .OrderBy(item => item.Name) .Skip(numberToShow * realPage) .Take(numberToShow) .ToList(); return returnValue.ToList(); }
Really simple yes? It follows like this:
Say I’m on page 1, which for this would be zero or pageNumber – 1. So I want to grab the first 20 items from the database. Well that means I want to start at 0 and grab 20. Now if you want this all to be done with some kind of conditional thing that either handles the first page or the other pages, you actually want to skip the same way no matter what the page number is. This is taken care of by numberToShow * realPage since even at 0 this works. After all 0 * anything is 0 and therefore you will be Skipping 0 items. So in other words, you’re at the start. Next you want to Take the amount of items you need, which is 20. Next time around you’ll start at 20 Skip(numberToShow 20 * realPage 1) and take the next 20. Nice thing is, even if you say Take 20 and there are only 2 left, it doesn’t care. It will just grab those two.
And there you have it, how to page with the Entity Framework and minimal amount of work. I know I hate taking other people’s methods (Like the TotalCountOfPages and GetRealPage methods), don’t know why. So sorry if I am forcing you to do so. However, the two methods I gave are semi important to this.
You might wonder why realPage and totalCountOfPages, well this is useful stuff when knowing what page is next for paging controls. Next post I’ll show those off but I’ll warn you, they are nothing spectacular.