- Incremented version numbers in project files for updates. - Marked `ICRUDRepository` as obsolete; use `IRepository` instead. - Improved parameter names and signatures in `IRepository`. - Changed access modifiers in `DbRepository` for broader access. - Updated `CreateAsync` and `UpdateAsync` methods for async operations. - Implemented `ReadAsync` and `DeleteAsync` methods in `DbRepository`. - Minor whitespace change in `.csproj` files. - Retained package description in `DigitalData.Core.Infrastructure.csproj`.
67 lines
2.2 KiB
C#
67 lines
2.2 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);
|
|
}
|
|
}
|