Spaces:
Sleeping
Sleeping
File size: 1,398 Bytes
8fb6238 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | using ClipForge.Core.Entities;
using ClipForge.Core.Interfaces;
using ClipForge.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
namespace ClipForge.Infrastructure.Repositories;
public class BaseRepository<T> : IRepository<T> where T : BaseEntity
{
protected readonly AppDbContext _context;
protected readonly DbSet<T> _dbSet;
public BaseRepository(AppDbContext context)
{
_context = context;
_dbSet = context.Set<T>();
}
public async Task<T?> GetByIdAsync(Guid id, CancellationToken ct = default)
=> await _dbSet.FindAsync([id], ct);
public async Task<IReadOnlyList<T>> GetAllAsync(CancellationToken ct = default)
=> await _dbSet.OrderByDescending(e => e.CreatedAt).ToListAsync(ct);
public async Task<T> AddAsync(T entity, CancellationToken ct = default)
{
await _dbSet.AddAsync(entity, ct);
await _context.SaveChangesAsync(ct);
return entity;
}
public async Task UpdateAsync(T entity, CancellationToken ct = default)
{
_dbSet.Update(entity);
await _context.SaveChangesAsync(ct);
}
public async Task DeleteAsync(Guid id, CancellationToken ct = default)
{
var entity = await GetByIdAsync(id, ct);
if (entity is not null)
{
_dbSet.Remove(entity);
await _context.SaveChangesAsync(ct);
}
}
}
|