Closed chuki2 closed 3 years ago
You can use this example.
public class UpdateCityCommand : IRequestWrapper<bool>
{
public int Id { get; set; }
public string Name { get; set; }
public bool Active { get; set; }
}
public class UpdateCityCommandHandler : IRequestHandlerWrapper<UpdateCityCommand, bool>
{
private readonly IApplicationDbContext _context;
private readonly IMapper _mapper;
public UpdateCityCommandHandler(IApplicationDbContext context, IMapper mapper)
{
_context = context;
_mapper = mapper;
}
public async Task<ServiceResult<bool>> Handle(UpdateCityCommand request, CancellationToken cancellationToken)
{
var entity = await _context.Cities.FindAsync(request.Id);
if (entity == null)
{
throw new NotFoundException(nameof(City), request.Id);
}
if (!string.IsNullOrEmpty(request.Name))
entity.Name = request.Name;
entity.Active = request.Active;
await _context.SaveChangesAsync(cancellationToken);
return ServiceResult.Success(true);
}
}
Also if you don't want to return any results.
public class UpdateCityCommand : IRequest
{
public int Id { get; set; }
public string Name { get; set; }
public bool Active { get; set; }
}
public class UpdateCityCommandHandler : IRequestHandler<UpdateCityCommand>
{
private readonly IApplicationDbContext _context;
private readonly IMapper _mapper;
public UpdateCityCommandHandler(IApplicationDbContext context, IMapper mapper)
{
_context = context;
_mapper = mapper;
}
public async Task<Unit> Handle(UpdateCityCommand request, CancellationToken cancellationToken)
{
var entity = await _context.Cities.FindAsync(request.Id);
if (entity == null)
{
throw new NotFoundException(nameof(City), request.Id);
}
if (!string.IsNullOrEmpty(request.Name))
entity.Name = request.Name;
entity.Active = request.Active;
await _context.SaveChangesAsync(cancellationToken);
return Unit.Value;
}
}
Have a nice coding 😊
Great, thanks for that example!
Based on this code
Any I idea how I can return
ServiceResult
withoutDto
? I just want to returnpublic async Task<ServiceResult> Handle(UpdateCityCommand request, CancellationToken cancellationToken)
In some case, I just want to tell success only
Thanks in advance.