This video is available to students only

Finishing pagination to the API

In this lesson, we're going to finish pagination

Now we are getting paginated results, but there are some additional information I would like to add to the response — information such as the total count, page size and the page index — that will give us more flexibility in the frontend, I think. What I'll do is create a new Pagination class. Inside the helpers folder, I will make it generic so that it can be used by any Entity type. Let's constrain this again by writing where T : class.

In the pagination class, I will add four properties. First one is the PageIndex of type int. Next will be the PageSize; type int again. We need count as well of type int. Finally, we want to return the data which we are returning already. This will be IReadOnlyList of type t which will be replaced by the actual type which is CourseDto. In case of CoursesController, we will call this data. Let's create a constructor with all these properties.

API/Helpers/Pagination.cs

Talking about the Count property, we will create a new specification whose responsibility will be to give us just the count. We want to count the number of results after all the other filters are applied. For example, customer is looking for a course with rating more than 4.5 and price below $20. We want to first of all, do all this filtering and finally count the result. Although we have created an ApplyPagination method, its job is to give us the result by skipping and taking, not counting them.

Let's create a new method which will count the results for us. Let's go to the IGenericRepository and create a new method, Task of type int because it will return an integer; let's call it CountResultAsync and pass ISpecification of type t. We need specification because we want the count after all the filters have been applied. Let's go to Generic Repository and implement the new interface. Let's make it async and remove this line and write return await ApplySpec method with the specification and use the CountAsync method. That's it.

Entity/Interfaces/IGenericRepository.cs

Start a new discussion. All notification go to the author.