- Added UpdateAsync<TDto>(TDto dto, IQueryable<TEntity> query, ...) overload - Added DeleteAsync(IQueryable<TEntity> query, ...) overload - Expression-based methods now delegate to the IQueryable overloads - Reduces code duplication and allows more flexible queries
68 lines
2.3 KiB
C#
68 lines
2.3 KiB
C#
using DigitalData.Core.Abstraction.Application.Repository;
|
|
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;
|
|
|
|
public IEntityMapper<TEntity> Mapper { get; }
|
|
|
|
public DbRepository(TDbContext context, Func<TDbContext, DbSet<TEntity>> queryFactory, IEntityMapper<TEntity> 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 IQueryable<TEntity> Read() => Entities.AsQueryable();
|
|
|
|
public IQueryable<TEntity> ReadOnly() => Entities.AsNoTracking();
|
|
|
|
public virtual Task UpdateAsync<TDto>(TDto dto, Expression<Func<TEntity, bool>> expression, CancellationToken ct = default) => UpdateAsync(dto, Entities.Where(expression), ct);
|
|
|
|
public virtual async Task UpdateAsync<TDto>(TDto dto, IQueryable<TEntity> query, CancellationToken ct = default)
|
|
{
|
|
var entities = await query.ToListAsync(ct);
|
|
|
|
for (int i = entities.Count - 1; i >= 0; i--)
|
|
{
|
|
Mapper.Map(dto, entities[i]);
|
|
Entities.Update(entities[i]);
|
|
}
|
|
|
|
await Context.SaveChangesAsync(ct);
|
|
}
|
|
|
|
public virtual Task DeleteAsync(Expression<Func<TEntity, bool>> expression, CancellationToken ct = default) => DeleteAsync(Entities.Where(expression), ct);
|
|
|
|
public virtual async Task DeleteAsync(IQueryable<TEntity> query, CancellationToken ct = default)
|
|
{
|
|
var entities = await query.ToListAsync(ct);
|
|
|
|
for (int i = entities.Count - 1; i >= 0; i--)
|
|
{
|
|
Entities.Remove(entities[i]);
|
|
}
|
|
|
|
await Context.SaveChangesAsync(ct);
|
|
}
|
|
} |