Enhance IRepository and DbRepository with DTO support
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.
This commit is contained in:
parent
fffbdf752f
commit
f5b202c325
@ -8,9 +8,13 @@ public interface IRepository<TEntity>
|
||||
|
||||
public Task<IEnumerable<TEntity>> CreateAsync(IEnumerable<TEntity> entities, CancellationToken ct = default);
|
||||
|
||||
public Task<TEntity> CreateAsync<TDto>(TDto dto, CancellationToken ct = default);
|
||||
|
||||
public Task<IEnumerable<TEntity>> CreateAsync<TDto>(IEnumerable<TDto> dtos, CancellationToken ct = default);
|
||||
|
||||
public Task<IEnumerable<TEntity>> ReadAsync(Expression<Func<TEntity, bool>>? expression = null, CancellationToken ct = default);
|
||||
|
||||
public Task UpdateAsync<TUpdate>(TUpdate update, Expression<Func<TEntity, bool>> expression, CancellationToken ct = default);
|
||||
public Task UpdateAsync<TDto>(TDto dto, Expression<Func<TEntity, bool>> expression, CancellationToken ct = default);
|
||||
|
||||
public Task DeleteAsync<TDto>(Expression<Func<TEntity, bool>> expression, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
@ -34,18 +34,30 @@ public class DbRepository<TDbContext, TEntity> : IRepository<TEntity> where TDbC
|
||||
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<TUpdate>(TUpdate update, Expression<Func<TEntity, bool>> expression, CancellationToken ct = default)
|
||||
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(update, entity);
|
||||
Mapper.Map(dto, entity);
|
||||
Entities.Add(entity);
|
||||
}
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user