Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

DeleteUsersCommand.cs 1.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. using AutoMapper;
  2. using BlackRock.Reporting.API.Core;
  3. using BlackRock.Reporting.API.Models;
  4. using MediatR;
  5. namespace BlackRock.Reporting.API.Mediator
  6. {
  7. public class DeleteUsersCommand : IRequest<Result<Guid>>
  8. {
  9. public Guid Id { get; }
  10. public DeleteUsersCommand(Guid id)
  11. {
  12. this.Id = id;
  13. }
  14. }
  15. public class DeleteUsersCommandHandlers : IRequestHandler<DeleteUsersCommand, Result<Guid>>
  16. {
  17. private readonly ILogger<DeleteUsersCommandHandlers> logger;
  18. private readonly IMapper mapper;
  19. private readonly IUsersRepository repository;
  20. private readonly IUnitOfWork unitOfWork;
  21. public DeleteUsersCommandHandlers(ILogger<DeleteUsersCommandHandlers> logger, IMapper mapper, IUsersRepository repository, IUnitOfWork unitOfWork)
  22. {
  23. this.unitOfWork = unitOfWork;
  24. this.repository = repository;
  25. this.mapper = mapper;
  26. this.logger = logger;
  27. }
  28. public async Task<Result<Guid>> Handle(DeleteUsersCommand command, CancellationToken cancellationToken)
  29. {
  30. if (command.Id == Guid.Empty)
  31. throw new ArgumentException($"Parameter {nameof(command.Id)} must not be null or empty");
  32. logger.LogInformation("Deleting user ...");
  33. try
  34. {
  35. var user = await repository.GetByIdAsync(command.Id);
  36. repository.Remove(user);
  37. await unitOfWork.SaveChangesAsync();
  38. logger.LogInformation($"User with id {user.Id} has been deleted successfully");
  39. return new Result<Guid> { Data = command.Id };
  40. }
  41. catch (Exception ex)
  42. {
  43. return new Result<Guid> { IsSuccess = false, Error = "Faild to delete data from DB." };
  44. }
  45. }
  46. }
  47. }