This video is available to students only

Adding Sorting Feature to the API

In this lesson, we're going to add sorting feature to our API

Adding Sorting to the API#

Since we're building an e-learning application, customers would like the search results to appear in some sort of a way. They might want to see courses which are highly rated, or the least expensive ones. For that, we will add the sorting feature to our API.

It would have been much easier if we were not using Generic Repository; we would just go to our Repository and add OrderBy to the chain with the required parameter. Since we're not using that, let's go to ISpecification class. We have support for the Criteria and the Include statement; we can simply create two more. One of them will order in an ascending way, the other one in the descending way. Let's create Expression which will take function of type t and will return an object. Let's call it Sort followed by a getter. We can copy it once more and replace Sort with SortByDescending.

Our Base specification does not look happy, so let's go there and use quick fix to implement interface. We can get rid of throw new NotImplementedException and write a getter and a private setter; same goes for SortByDescending Expression. We are using private set because we do not want to set it outside of this class. Like the InludeMethod, we will create two more protected methods to set our OrderBy & OrderByDescending. We can simply copy it, and call the first one SortMethod and change expression to sortExpression. Inside the method, we can write Sort is equal to sortExpression. Now, we will be lazy and copy it one more time. This time, replace SortMethod with SortByDescendingMethod and sortExpression with sortDescendingExpression. Inside the method, SortByDescending will be equal to the sortDescendingExpression.


This will be taken care of now with our GetQueryMethod which is inside SpecificationEvaluator class so that this can be added to our IQueryable. Let's go there, and like we're checking for a criteria, we can check if Sorting request is available. What we can do is copy it and check if spec.Sort is null. If not, we will use query.OrderBy and inside, we will pass the spec.Sort. Same goes for the SortByDescending. Let's copy it one more time and replace sort with SortByDescending and orderBy with OrderByDescending. In get by id methods, we're passing id to the specifications which will then use this in the criteria to search for that particular id.

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