using System.Linq.Expressions; using Microsoft.EntityFrameworkCore; using SPMS.Domain.Entities; using SPMS.Domain.Interfaces; namespace SPMS.Infrastructure.Persistence.Repositories; public class Repository : IRepository where T : BaseEntity { protected readonly AppDbContext _context; protected readonly DbSet _dbSet; public Repository(AppDbContext context) { _context = context; _dbSet = context.Set(); } public async Task GetByIdAsync(long id) => await _dbSet.FindAsync(id); public async Task> GetAllAsync() => await _dbSet.ToListAsync(); public async Task> FindAsync(Expression> predicate) => await _dbSet.Where(predicate).ToListAsync(); public async Task<(IReadOnlyList Items, int TotalCount)> GetPagedAsync( int page, int size, Expression>? predicate = null, Expression>? orderBy = null, bool descending = true) { IQueryable query = _dbSet; if (predicate is not null) query = query.Where(predicate); var totalCount = await query.CountAsync(); if (orderBy is not null) query = descending ? query.OrderByDescending(orderBy) : query.OrderBy(orderBy); else query = query.OrderByDescending(e => e.Id); var items = await query .Skip((page - 1) * size) .Take(size) .ToListAsync(); return (items, totalCount); } public async Task CountAsync(Expression>? predicate = null) => predicate is null ? await _dbSet.CountAsync() : await _dbSet.CountAsync(predicate); public async Task ExistsAsync(Expression> predicate) => await _dbSet.AnyAsync(predicate); public async Task AddAsync(T entity) => await _dbSet.AddAsync(entity); public void Update(T entity) => _dbSet.Update(entity); public void Delete(T entity) => _dbSet.Remove(entity); }