using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Koogle.Domain.Entities; using Koogle.Domain.Interfaces; using Koogle.Infrastructure.Data; using Microsoft.EntityFrameworkCore; namespace Koogle.Infrastructure.Repositories; /// /// Generische Repository-Implementierung für grundlegende CRUD-Operationen. /// /// Der Entitätstyp, muss von BaseEntity erben. public class Repository : IRepository where T : BaseEntity { /// /// Der Datenbank-Kontext. /// protected readonly ApplicationDbContext Context; protected readonly IDbContextFactory ContextFactory; /// /// Das DbSet für die Entität. /// protected readonly DbSet DbSet; /// /// Erstellt eine neue Repository-Instanz. /// /// Der Datenbank-Kontext. public Repository(IDbContextFactory contextFactory) { ContextFactory = contextFactory; Context = contextFactory.CreateDbContext(); DbSet = Context.Set(); } /// public virtual async Task GetByIdAsync(int id, CancellationToken cancellationToken = default) { return await DbSet.FindAsync(new object[] { id }, cancellationToken); } /// public virtual async Task> GetAllAsync(CancellationToken cancellationToken = default) { return await DbSet.ToListAsync(cancellationToken); } /// public virtual async Task AddAsync(T entity, CancellationToken cancellationToken = default) { await DbSet.AddAsync(entity, cancellationToken); await Context.SaveChangesAsync(cancellationToken); return entity; } /// public virtual async Task UpdateAsync(T entity, CancellationToken cancellationToken = default) { var res = DbSet.Update(entity); await Context.SaveChangesAsync(cancellationToken); return res.Entity; } /// public virtual async Task DeleteAsync(int id, CancellationToken cancellationToken = default) { var entity = await DbSet.FindAsync(new object[] { id }, cancellationToken); if (entity != null) { entity.IsDeleted = true; entity.ModifiedAt = DateTime.UtcNow; await Context.SaveChangesAsync(cancellationToken); return entity; } return null; } }