Skip to content

Commit

Permalink
Add generic pagiantion on generic repository #1304
Browse files Browse the repository at this point in the history
  • Loading branch information
hocinehacherouf committed Oct 4, 2022
1 parent ce82f4e commit a21db8e
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@ namespace AzureIoTHub.Portal.Infrastructure.Repositories
using Domain.Base;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Shared.Models.v1._0;
using System.Linq.Dynamic.Core;

public class GenericRepository<T> : IRepository<T> where T : EntityBase
{
Expand Down Expand Up @@ -50,5 +53,32 @@ public void Delete(object id)

_ = this.context.Set<T>().Remove(existing);
}

public async Task<PaginatedResult<T>> GetPaginatedListAsync(
int pageNumber,
int pageSize,
string[]? orderBy = null,
Expression<Func<T, bool>>? expression = null,
CancellationToken cancellationToken = default
)
{
IQueryable<T> query = this.context.Set<T>();
if (expression != null) query = query.Where(expression);

var ordering = orderBy?.Any() == true ? string.Join(",", orderBy) : null;

query = !string.IsNullOrWhiteSpace(ordering) ? query.OrderBy(ordering) : query.OrderBy(a => a.Id);

var count = await query
.AsNoTracking()
.CountAsync(cancellationToken: cancellationToken);

var items = await query
.Skip((pageNumber - 1) * pageSize)
.Take(pageSize)
.ToDynamicListAsync<T>(cancellationToken: cancellationToken);

return new PaginatedResult<T>(items, count, pageNumber, pageSize);
}
}
}
4 changes: 4 additions & 0 deletions src/AzureIoTHubPortal.Domain/IRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@
namespace AzureIoTHub.Portal.Domain
{
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Base;
using Portal.Shared.Models.v1._0;

public interface IRepository<T> where T : EntityBase
{
Expand All @@ -18,5 +20,7 @@ public interface IRepository<T> where T : EntityBase
void Update(T obj);

void Delete(object id);

Task<PaginatedResult<T>> GetPaginatedListAsync(int pageNumber, int pageSize, string[]? orderBy = null, Expression<Func<T, bool>>? expression = null, CancellationToken cancellationToken = default);
}
}

0 comments on commit a21db8e

Please sign in to comment.