Developer 02 6916e169b1 Add mapping methods to IRepository and DbRepository
Updated the `IRepository<TEntity>` interface to include two new mapping methods: `Map<TSource>(TSource source)` and `Map<TDto>(TEntity source)`.

Implemented these methods in the `DbRepository<TDbContext, TEntity>` class, utilizing a `Mapper` for conversions between source types and entity types, as well as between entity types and DTOs.
2025-04-17 13:01:51 +02:00

71 lines
2.3 KiB
C#

using AutoMapper;
using DigitalData.Core.Abstractions.Infrastructure;
using Microsoft.EntityFrameworkCore;
using System.Linq.Expressions;
namespace DigitalData.Core.Infrastructure;
public class DbRepository<TDbContext, TEntity> : IRepository<TEntity> where TDbContext : DbContext where TEntity : class
{
protected internal readonly TDbContext Context;
protected internal readonly DbSet<TEntity> Entities;
protected internal readonly IMapper Mapper;
public DbRepository(TDbContext context, Func<TDbContext, DbSet<TEntity>> queryFactory, IMapper mapper)
{
Context = context;
Entities = queryFactory(context);
Mapper = mapper;
}
public virtual async Task<TEntity> CreateAsync(TEntity entity, CancellationToken ct = default)
{
Entities.Add(entity);
await Context.SaveChangesAsync(ct);
return entity;
}
public virtual async Task<IEnumerable<TEntity>> CreateAsync(IEnumerable<TEntity> entities, CancellationToken ct = default)
{
Entities.AddRange(entities);
await Context.SaveChangesAsync(ct);
return entities;
}
public virtual async Task<IEnumerable<TEntity>> ReadAsync(Expression<Func<TEntity, bool>>? expression = null, CancellationToken ct = default)
=> expression is null
? await Entities.AsNoTracking().ToListAsync(ct)
: await Entities.AsNoTracking().Where(expression).ToListAsync(ct);
public virtual async Task UpdateAsync<TUpdate>(TUpdate update, Expression<Func<TEntity, bool>> expression, CancellationToken ct = default)
{
var entities = await Entities.Where(expression).ToListAsync(ct);
foreach (var entity in entities)
{
Mapper.Map(update, entity);
Entities.Add(entity);
}
await Context.SaveChangesAsync(ct);
}
public virtual async Task DeleteAsync<TDto>(Expression<Func<TEntity, bool>> expression, CancellationToken ct = default)
{
var entities = await Entities.Where(expression).ToListAsync(ct);
foreach (var entity in entities)
{
entities.Remove(entity);
}
await Context.SaveChangesAsync(ct);
}
public TEntity Map<TSource>(TSource source) => Mapper.Map<TEntity>(source);
public TDto Map<TDto>(TEntity entity) => Mapper.Map<TDto>(entity);
}