본문 바로가기

Backend/.NET

Generic Repository Specification Pattern - Adding Pagination

반응형

One of the drawbacks about using the specification pattern is that we lose some of the functions provided by Entity Framework. Pagination 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

int Take { get; }
int Skip { get; }
bool IsPagingEnabled { get; }

Go to the specification class and implement the interface

Add the getter and setter as shown below

Add a method that sets the pagination values

protected void ApplyPaging(int skip, int take)
{
  Skip = skip;
  Take = take;
  IsPagingEnabled = true;
}

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

if (spec.IsPagingEnabled)
{
  query = query.Skip(spec.Skip).Take(spec.Take);
}

Too many parameters... let's create a class to hold the parameters as whole

Add the pagination properties in the class just created

private int MaxPage = 20;
public int PageIndex { get; set; } = 1;
private int _pageSize = 3;
public int PageSize
{
  get => _pageSize;
  set => _pageSize = (value > MaxPage) ? MaxPage : value;
}

Go to the individual specification class and add the pagination class as a parameter and add the generic expression to paginate

Go to the controller and add a sorting parameter class and pass that parameter to the individual specification class. Note that when we use a class as a parameter the parameter will be added to the body of the request. To solve this, add '[FromQuery]' to mark it as a query

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 a pagination with the specification pattern.

 

728x90
반응형