As per Command Query Separation principle, commands should return void.
I am using MediatR Command Request Handler to create an entity as follows. So how can I get back the created entity?
public class CreateCompanyCommand : IRequest
{
public string Name { get; set; } = default!;
}
public class CreateCompanyHandler : IRequestHandler<CreateCompanyCommand>
{
private readonly IRepository<Company> _repository;
public CreateCompanyHandler(IRepository<Company> repository)
{
_repository = repository;
}
public async Task<Unit> Handle(CreateCompanyCommand request, CancellationToken cancellationToken)
{
var newCompany = new Company(request.Name);
var createdItem = await _repository.AddAsync(newCompany);
return Unit.Value;
}
}
I saw this question as well as its answer here, but I am still not clear.
How can I return the createdItem? What should be the Unit.Value? Can I modify and return something custom on my own instead of Unit.Value?
CodePudding user response:
If you really want the created value back, you can change your request / handler to return it:
public class CreateCompanyCommand : IRequest<Company>
{
public string Name { get; set; } = default!;
}
public class CreateCompanyHandler : IRequestHandler<CreateCompanyCommand, Company>
{
private readonly IRepository<Company> _repository;
public CreateCompanyHandler(IRepository<Company> repository)
{
_repository = repository;
}
public async Task<Unit> Handle(CreateCompanyCommand request, CancellationToken cancellationToken)
{
var newCompany = new Company(request.Name);
var createdItem = await _repository.AddAsync(newCompany);
return newCompany;
}
}
There's nothing forcing you to not do this - commands aren't supposed to return anything in pure CQRS, but mediatr doesn't force this on you.
An alternative would be to create the id in the command (and initialize the id in the caller, or ctor of the command)
public class CreateCompanyCommand : IRequest<Company>
{
public Guid Id {get; set;}
public string Name { get; set; } = default!;
}
Call mediatr how you have in your question, then query for the Company you just created.
