KoogleApp/Koogle.Infrastructure_OLD/Repositories/Repository.cs

85 lines
2.6 KiB
C#

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;
/// <summary>
/// Generische Repository-Implementierung für grundlegende CRUD-Operationen.
/// </summary>
/// <typeparam name="T">Der Entitätstyp, muss von BaseEntity erben.</typeparam>
public class Repository<T> : IRepository<T> where T : BaseEntity
{
/// <summary>
/// Der Datenbank-Kontext.
/// </summary>
protected readonly ApplicationDbContext Context;
protected readonly IDbContextFactory<ApplicationDbContext> ContextFactory;
/// <summary>
/// Das DbSet für die Entität.
/// </summary>
protected readonly DbSet<T> DbSet;
/// <summary>
/// Erstellt eine neue Repository-Instanz.
/// </summary>
/// <param name="context">Der Datenbank-Kontext.</param>
public Repository(IDbContextFactory<ApplicationDbContext> contextFactory)
{
ContextFactory = contextFactory;
Context = contextFactory.CreateDbContext();
DbSet = Context.Set<T>();
}
/// <inheritdoc />
public virtual async Task<T?> GetByIdAsync(int id, CancellationToken cancellationToken = default)
{
return await DbSet.FindAsync(new object[] { id }, cancellationToken);
}
/// <inheritdoc />
public virtual async Task<IReadOnlyList<T>> GetAllAsync(CancellationToken cancellationToken = default)
{
return await DbSet.ToListAsync(cancellationToken);
}
/// <inheritdoc />
public virtual async Task<T> AddAsync(T entity, CancellationToken cancellationToken = default)
{
await DbSet.AddAsync(entity, cancellationToken);
await Context.SaveChangesAsync(cancellationToken);
return entity;
}
/// <inheritdoc />
public virtual async Task<T> UpdateAsync(T entity, CancellationToken cancellationToken = default)
{
var res = DbSet.Update(entity);
await Context.SaveChangesAsync(cancellationToken);
return res.Entity;
}
/// <inheritdoc />
public virtual async Task<T?> 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;
}
}