我可以在CQRS中的另一个CommandHandler中调用QueryHandler/CommandHandler吗

han*_*shi 7 c# cqrs asp.net-core asp.net-core-webapi

我正在开发一个 ASP.NET Core 6.0 Web API 项目。我使用 CQRS 设计模式。

我想更新一个airlines表(代码优先 EF Core)。所以首先我需要找到航空公司的ID。

我有GetAirlineByIdQueryHandler.cs

public record GetAirlineByIdQuery(int Id, bool LoadOverview = true) : IRequest<Airline>;

public class GetAirlineByIdQueryHandler : IRequestHandler<GetAirlineByIdQuery, Airline>
{
    public async Task<Airline> Handle(GetAirlineByIdQuery request, CancellationToken cancellationToken)
    {
        var query = _techneDbContext.Airline
                .Include(d => d.X)
                .Include(d => d.Y)
                .Include(d => d.Z)
               
                .AsQueryable();

        if (request.LoadOverview)
        {
            query = query.Include(d => d.Overview);
        }

      var airline = await query.FirstOrDefaultAsync(d => d.Id == request.Id);


        if (airline == null)
        {
            throw new NotFoundException(nameof(Airline), request.Id);
        }

         return airline;
    }
}
Run Code Online (Sandbox Code Playgroud)

更新航空公司命令.cs

public class UpdateAirlineCommand : AirlineUpdateDto, IRequest<Airline>
{
    public int Id { get; set; }
}

public class UpdateAirlineCommanddHandler : IRequestHandler<UpdateAirlineCommand, Airline>
{
    // removed constructor

    public async Task<Airline> Handle(UpdateAirlineCommand request, CancellationToken cancellationToken)
    {
        // To update I have find the the id is there or not?
        // Can I call GetAirlineByIdQueryHandler here or do I need to copy the query and paste it here
    }
}
Run Code Online (Sandbox Code Playgroud)

gee*_*eek 0

通常,命令和查询在不同的模型上运行。这为您提供了优化的读取和写入数据模式。在您的示例中,查询返回将由命令更新的相同模型。在命令中使用查询的另一个缺点是使它们紧密耦合。CQRS 的巨大优势之一是将读端和写端分开。在您的示例中,GetAirlineByIdQueryHandler 中的任何更改都可能影响 UpdateAirlineCommanddHandler。