存储库中是否应该有特定于实体的方法?

Should there be entity-specific methods in the repositories?

我一直在阅读存储库模式以及如何正确实施它。

有一个重要问题让我感到困惑。

假设我们有一个具有基本操作(如 Add()、Remove()、GetById() 等)的通用存储库,并且我们还有每个实体的特定存储库(例如 ProductRepository、UserRepository 等)

我们是否应该在特定的存储库中定义与实体相关的操作?例如,在ProductRepository中,是否应该声明GetProductsInCategory()、GetProductsByBrandId()等方法,还是由服务层负责?

那里有很多信息相互矛盾,例如this answer claims that the answer to the question that I just asked is No, but on the other hand in this tutorial video(有很多观点)导师声称我的问题的答案是.

我真的很困惑我们必须在存储库中实现的实际方法和操作。

Say we have a generic repository with basic operations like Add(), Remove(), GetById()

如果这些成员没有暴露在数据访问层之外,这是可以的。基本上,。但是,因为这不是你的核心问题,我就不在这里细说了。

and we also have a specific repository per entity (e.g. ProductRepository, UserRepository, etc.)

这是很好的做法。

Should we define entity-related operations in the specific repositories or not? For example, in the ProductRepository, should I declare methods like GetProductsInCategory(), GetProductsByBrandId(), etc.

这些函数必须是特定存储库的一部分。事实上,这就是特定存储库存在的目的。

or is this the responsibility of the service layer?

这是基于意见的。
;您删除完整的存储库层并在服务中执行所有这些操作。
没有;抽象存储库中的数据库逻辑并使您的服务数据库不可知。让他们专注于业务逻辑。

所以选择权在你。

answer you linked 建议避免在存储库中创建过多筛选方法的替代方法。

Instead it is better to have a query method on the repository which takes a Specification. You can pass different implementations of the Specification to retrieve the products.

虽然我个人不同意它(它会泄漏调用层中的数据访问组件,因为您必须从外部接受 Specification 实例),如果您有太多不同的过滤条件,它可能会有所帮助。
关于该答案的另一点是,显然(该问题被标记为这样),它是在 DDD 方面进行讨论。你没有在你的问题中提到 DDD。
总的来说,我不同意答案中的大多数说法; 个人.

I'm really confused about the actual methods and operations that we have to implement in a repository.

特定 存储库应实现您的调用层所需的方法和操作。如果该层需要 GetProductsInCategory()GetProductsByBrandId() 等方法,您应该实现这些方法。如上所述,这就是特定存储库存在的原因。