본문 바로가기

Backend/.NET

Generic Repository Specification Pattern - Adding Sorting

반응형

One of the drawbacks about using the specification pattern is that we lose some of the functions provided by Entity Framework. Sorting the result is one of them and we will see how we can manually create the feature with the specification pattern.

Creating a Generic Repository Pattern

 

Relational DB - Getting Data including Data from Other Entities (Generic Repository Pattern)

Let's see how we can get data from a primary entity that has reference to other entities with the generic repository pattern Implementation Creating an Application How to create .NET web-API Setting up development tools When working with .NET, we need tool

jin-co.tistory.com

Add the methods to the specification interface

Expression<Func<T, object>> OrderBy { get; }
Expression<Func<T, object>> OrderByDesc { get; }

Go to the specification class and implement the interface

Add the getter and setter as shown below

Add methods that sorts the result (one ascending and the other descending)

protected void AddOrderBy(Expression<Func<T, object>> orderByExpression)
{
  OrderBy = orderByExpression;
}
    
protected void AddOrderByDesc(Expression<Func<T, object>> orderByDescExpression)
{
  OrderByDesc = orderByDescExpression;
}

Go to the specification evaluator class under infrastructure folder and add the codes shown below

if (spec.OrderBy != null)
{
  query = query.OrderBy(spec.OrderBy);
}
      
if (spec.OrderByDesc != null)
{
  query = query.OrderByDescending(spec.OrderByDesc);
}

Go to the individual specification class and add a sorting parameter and the generic expression to sort


※ We can use a condition and expand to more search options

if (!string.IsNullOrEmpty(sort))
{
  switch (sort)
  {
    case "quantityAsc":
      AddOrderBy(i => i.Quantity);
      break;
    case "quantityDesc":
      AddOrderByDesc(i => i.Quantity);
      break;
    default:
      AddOrderBy(i => i.Name);
      break;
  }
}


Go to the controller and add a sorting parameter and pass that parameter to the individual specification class

Run

Move to the API folder

cd /API

And run the app

dotnet watch

In this writing, we have seen one of ways to add sorting with the specification pattern.

 

728x90
반응형

'Backend > .NET' 카테고리의 다른 글

Generic Repository Specification Pattern - Adding Pagination  (0) 2023.04.24
Generic Repository Specification Pattern - Adding Filtering  (0) 2023.04.24
Swagger  (0) 2023.04.19
Using Static Files  (0) 2023.04.19
Data Transfer Object (DTO)  (0) 2023.04.19