Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

UpdateUserCommand.cs 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. using AutoMapper;
  2. using BlackRock.Reporting.API.Core.Interfaces;
  3. using BlackRock.Reporting.API.Core.Models;
  4. using BlackRock.Reporting.API.Mediator.UserMediator.Dto;
  5. using BlackRock.Reporting.API.Mediator.UserMediator.Model;
  6. using MediatR;
  7. namespace BlackRock.Reporting.API.Mediator.UserMediator.Commands
  8. {
  9. public class UpdateUserCommand : IRequest<Result<UserDto>>
  10. {
  11. public UserCommand User { get; set; }
  12. public int Id { get; set; }
  13. }
  14. public class UpdateUserCommandHandlers : IRequestHandler<UpdateUserCommand, Result<UserDto>>
  15. {
  16. private readonly ILogger<UpdateUserCommandHandlers> logger;
  17. private readonly IMapper mapper;
  18. private readonly IUnitOfWork unitOfWork;
  19. public UpdateUserCommandHandlers(ILogger<UpdateUserCommandHandlers> logger, IMapper mapper, IUnitOfWork unitOfWork)
  20. {
  21. this.unitOfWork = unitOfWork;
  22. this.mapper = mapper;
  23. this.logger = logger;
  24. }
  25. public async Task<Result<UserDto>> Handle(UpdateUserCommand command, CancellationToken cancellationToken)
  26. {
  27. if (command.Id <= 0)
  28. throw new ArgumentException($"Parameter {nameof(command.Id)} must not be grater than 0");
  29. logger.LogInformation("Updating user ...");
  30. try
  31. {
  32. var user = await unitOfWork.UsersRepository.GetByIdAsync(command.Id);
  33. mapper.Map<UserCommand, User>(command.User, user);
  34. unitOfWork.UsersRepository.Update(user);
  35. await unitOfWork.SaveChangesAsync();
  36. var updatedUser = mapper.Map<User, UserDto>(user);
  37. logger.LogInformation($"User with id {user.Id} has been updated successfully");
  38. return new Result<UserDto> { Data = updatedUser };
  39. }
  40. catch (Exception ex)
  41. {
  42. return new Result<UserDto> { IsSuccess = false, Error = "Faild to update data in DB." };
  43. }
  44. }
  45. }
  46. }