Files
predavanja/Events-WebApi/Events.WebAPI.Handlers.EF/CommandHandlers/Generic/GenericCommandHandler.cs
2026-05-12 02:20:00 +02:00

57 lines
1.9 KiB
C#

using MobilityOne.Common.Commands;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Events.WebAPI.Contract.Command;
using Events.WebAPI.Contract.DTOs;
using AutoMapper;
namespace Events.WebAPI.Handlers.EF.CommandHandlers.Generic;
public class GenericCommandHandler<TDal, TDto, TPK> : IRequestHandler<AddCommand<TDto, TPK>, TPK>,
IRequestHandler<UpdateCommand<TDto>>,
IRequestHandler<DeleteCommand<TDto, TPK>>
where TDal: class, IHasIdAsPK<TPK>
where TDto: IHasIdAsPK<TPK>
where TPK : IEquatable<TPK>
{
protected DbContext ctx { get; }
protected ILogger logger { get; }
protected IMapper mapper { get; }
protected GenericCommandHandler(DbContext ctx, ILogger logger, IMapper mapper)
{
this.ctx = ctx;
this.logger = logger;
this.mapper = mapper;
}
public virtual async Task<TPK> Handle(AddCommand<TDto, TPK> request, CancellationToken cancellationToken)
{
var entity = mapper.Map<TDto, TDal>(request.Dto);
ctx.Add(entity);
await ctx.SaveChangesAsync(cancellationToken);
return entity.Id;
}
public virtual async Task Handle(UpdateCommand<TDto> request, CancellationToken cancellationToken)
{
var entity = await ctx.Set<TDal>().FindAsync(request.Dto.Id);
if (entity != null)
{
mapper.Map(request.Dto, entity);
await ctx.SaveChangesAsync(cancellationToken);
}
else
{
logger.LogError($"UpdateCommand<{typeof(TDto).Name}> : Invalid id #{request.Dto.Id}");
throw new ArgumentException($"Invalid id: {request.Dto.Id}");
}
}
public virtual async Task Handle(DeleteCommand<TDto, TPK> request, CancellationToken cancellationToken)
{
await ctx.Set<TDal>().Where(d => d.Id.Equals(request.Id)).ExecuteDeleteAsync(cancellationToken);
}
}