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) { this.ctx = ctx; this.logger = logger; this.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); } }