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

UpdateAllUsersCommand.cs 2.1KB

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