SPMS_API/SPMS.Infrastructure/Persistence/Repositories/Repository.cs
SEAN 787190f512 feat: Generic Repository 및 UnitOfWork 패턴 구현 (#18)
- IRepository<T> 구현체: CRUD, 페이징, 조건 검색 지원
- IUnitOfWork 구현체: 트랜잭션 관리 (Begin/Commit/Rollback)
- Program.cs에 DI 등록 (AddScoped)

Closes #18
2026-02-09 14:44:31 +09:00

71 lines
2.1 KiB
C#

using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;
using SPMS.Domain.Entities;
using SPMS.Domain.Interfaces;
namespace SPMS.Infrastructure.Persistence.Repositories;
public class Repository<T> : IRepository<T> where T : BaseEntity
{
protected readonly AppDbContext _context;
protected readonly DbSet<T> _dbSet;
public Repository(AppDbContext context)
{
_context = context;
_dbSet = context.Set<T>();
}
public async Task<T?> GetByIdAsync(long id)
=> await _dbSet.FindAsync(id);
public async Task<IReadOnlyList<T>> GetAllAsync()
=> await _dbSet.ToListAsync();
public async Task<IReadOnlyList<T>> FindAsync(Expression<Func<T, bool>> predicate)
=> await _dbSet.Where(predicate).ToListAsync();
public async Task<(IReadOnlyList<T> Items, int TotalCount)> GetPagedAsync(
int page, int size,
Expression<Func<T, bool>>? predicate = null,
Expression<Func<T, object>>? orderBy = null,
bool descending = true)
{
IQueryable<T> 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<int> CountAsync(Expression<Func<T, bool>>? predicate = null)
=> predicate is null
? await _dbSet.CountAsync()
: await _dbSet.CountAsync(predicate);
public async Task<bool> ExistsAsync(Expression<Func<T, bool>> 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);
}