gpt4 book ai didi

c# - 为什么 GetByID 是命令而不是查询?

转载 作者:太空宇宙 更新时间:2023-11-03 19:45:30 25 4
gpt4 key购买 nike

请参阅以下文章:https://www.codeproject.com/Articles/555855/Introduction-to-CQRShttp://enterprisecraftsmanship.com/2015/04/20/types-of-cqrs/ .这是一些代码:

public class CustomerRepository
{
public void Save(Customer customer) { /* … */ }
public Customer GetById(int id) { /* … */ }
public IReadOnlyList<CustomerDto> Search(string name) { /* … */ }
}

它们都将 GetByID 描述为命令,即在这两种情况下,方法返回域对象 (Customer) 而不是 DTO 对象 (CustomerDTO)。为什么是这样? GetByID 从数据库返回数据。它应该是一个查询,即返回 CustomerDTO,不是吗?

25/09/17 更新

假设我从数据库中检索了一个产品。然后我想在产品上运行一些方法(更改实例变量),然后将更改保存回数据库。我会这样做吗:

ProductDTO productDTO = ProductRepository.GetProduct(1);
DomainProduct domainProduct = AutoMapper.Mapper.Map<DomainProduct>(DomainProduct);
domainProduct.RunSomeMethod();

或者这个:

DomainProduct domainProduct = ProductRepository.GetProduct(1);
domainProduct.RunSomeMethod();

第一个代码片段防止对写入数据库的命中,(我认为 CQRS 应该防止对写入数据库的读取命中)?但是,GetByID 也会命中写入数据库。

哪个片段支持CQRS?两个?

最佳答案

但你的标题不正确。GetById 不是两篇文章中的命令(它不可能是 command 无论如何,可能是命令处理程序或命令方法).但是,它在命令端使用

更新后:

这是正确的:

DomainProduct domainProduct = ProductRepository.GetProduct(1);
domainProduct.RunSomeMethod();

The first fragment of code prevents hits on the write database, (I thought CQRS was suppose to prevent read hits on the write database)? However, GetByID also hits the write database.

它防止在读模型上写,在写模型上读。但是,您可以从写入持久性加载写入模型(聚合根)以便向其发送命令 - 这就是 GetProduct(id) 的目的。

在您的情况下,DomainProduct 不应有任何查询方法(即 getter),只有命令方法(即 activate())。这就是您防止写入模型读取的方法:没有任何查询方法。 CQRS 是应用于所有模型上的任何方法的 CQS。此限制适用于域实体;任何其他对象(即存储库)都可以在写入端具有查询方法(如 GetProduct(id))。

关于c# - 为什么 GetByID 是命令而不是查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46296030/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com