您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

CreateUsersCommand.cs 1.8KB

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