Updated IRepository<TEntity> to include new generic methods for creating and reading entities from DTOs. Modified UpdateAsync to accept DTOs instead of generic types. Implemented corresponding methods in DbRepository<TDbContext, TEntity> for mapping DTOs to entities during creation and updating processes.
79 lines
2.6 KiB
C#
79 lines
2.6 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 Task<TEntity> CreateAsync<TDto>(TDto dto, CancellationToken ct = default)
|
|
{
|
|
var entity = Mapper.Map<TEntity>(dto);
|
|
return CreateAsync(entity, ct);
|
|
}
|
|
|
|
public virtual Task<IEnumerable<TEntity>> CreateAsync<TDto>(IEnumerable<TDto> dtos, CancellationToken ct = default)
|
|
{
|
|
var entities = dtos.Select(dto => Mapper.Map<TEntity>(dto));
|
|
return CreateAsync(entities, ct);
|
|
}
|
|
|
|
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<TDto>(TDto dto, Expression<Func<TEntity, bool>> expression, CancellationToken ct = default)
|
|
{
|
|
var entities = await Entities.Where(expression).ToListAsync(ct);
|
|
|
|
foreach (var entity in entities)
|
|
{
|
|
Mapper.Map(dto, 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);
|
|
}
|
|
}
|