Template
47 lines
1.6 KiB
C#
47 lines
1.6 KiB
C#
using System.Linq.Expressions;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using RT.Domain.Entities;
|
|
using RT.Infrastructure.Repositories;
|
|
using RT.Infrastructure.Data;
|
|
|
|
namespace RT.Infrastructure.Repositories;
|
|
|
|
public abstract class BaseRepository<T>(AppDbContext db) : IRepository<T> where T : BaseEntity
|
|
{
|
|
protected readonly DbSet<T> Set = db.Set<T>();
|
|
|
|
public virtual Task<T?> GetByIdAsync(Guid id, CancellationToken ct = default)
|
|
=> Set.FirstOrDefaultAsync(e => e.Id == id && !e.IsDeleted, ct);
|
|
|
|
public virtual async Task<IEnumerable<T>> GetAllAsync(CancellationToken ct = default)
|
|
=> await Set.Where(e => !e.IsDeleted).ToListAsync(ct);
|
|
|
|
public virtual Task<int> CountAsync(Expression<Func<T, bool>>? predicate = null, CancellationToken ct = default)
|
|
=> predicate is null
|
|
? Set.CountAsync(e => !e.IsDeleted, ct)
|
|
: Set.Where(e => !e.IsDeleted).CountAsync(predicate, ct);
|
|
|
|
public virtual async Task InsertAsync(T entity, CancellationToken ct = default)
|
|
{
|
|
await Set.AddAsync(entity, ct);
|
|
await db.SaveChangesAsync(ct);
|
|
}
|
|
|
|
public virtual async Task UpdateAsync(T entity, CancellationToken ct = default)
|
|
{
|
|
entity.UpdatedAt = DateTime.UtcNow;
|
|
Set.Update(entity);
|
|
await db.SaveChangesAsync(ct);
|
|
}
|
|
|
|
public virtual async Task RemoveAsync(T entity, CancellationToken ct = default)
|
|
{
|
|
entity.IsDeleted = true;
|
|
entity.UpdatedAt = DateTime.UtcNow;
|
|
await db.SaveChangesAsync(ct);
|
|
}
|
|
|
|
public Task SaveChangesAsync(CancellationToken ct = default)
|
|
=> db.SaveChangesAsync(ct);
|
|
}
|