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 : IRequestHandler, TPK>, IRequestHandler>, IRequestHandler> where TDal: class, IHasIdAsPK where TDto: IHasIdAsPK where TPK : IEquatable { protected DbContext Ctx { get; } protected ILogger Logger { get; } protected IMapper Mapper { get; } protected GenericCommandHandler(DbContext ctx, ILogger logger, IMapper mapper) { Ctx = ctx; Logger = logger; Mapper = mapper; } public virtual async Task Handle(AddCommand request, CancellationToken cancellationToken) { var entity = Mapper.Map(request.Dto); Ctx.Add(entity); await Ctx.SaveChangesAsync(cancellationToken); return entity.Id; } public virtual async Task Handle(UpdateCommand request, CancellationToken cancellationToken) { var entity = await Ctx.Set().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 request, CancellationToken cancellationToken) { await Ctx.Set().Where(d => d.Id.Equals(request.Id)).ExecuteDeleteAsync(cancellationToken); } }