当不同实体的工作非常不同时,我应该如何管理通用存储库模式? [英] How should I manage Generic Repository Pattern when the works of different entities are pretty much different?

查看:48
本文介绍了当不同实体的工作非常不同时,我应该如何管理通用存储库模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是存储库模式的新手.

I am new to Repository pattern.

当我管理多个实体(例如:客户、订单等)的 CRUD 操作时,就可以了.我正在制作一个界面,我正在制作一个通用存储库.这符合我的目的,因为 CRUD 操作对他们来说很常见.

When I am managing the CRUD operations of several entities (like: customers, orders etc) then its fine. I am making an interface, I am making a Generic repository. And that serves my purpose, because CRUD operation is common for them.

我的问题是:

当几个实体的职责完全不同,他们之间没有共同的方法时,我该怎么办?我应该为这些特定目的增加接口和存储库的数量吗?或者在最佳实践方面是否有更好的解决方案?

When the duties of several entities are totally different, there is no common method between them, in this case what should I do? Should I increase the number of interfaces and repositories for those specific purposes? Or is there any better solution in terms of best practices?

推荐答案

当不同实体的工作非常不同时,我应该如何管理通用存储库模式?

这是Generic Repository模式的核心问题;这就是为什么它被认为是 -模式.

This is the core problem with Generic Repository pattern; that is why it is considered an anti-pattern.

我在此处阅读了此内容:

无论我尝试过什么聪明的机制,我总是遇到同样的问题:存储库是正在建模的域的一部分,而该域不是通用的.不是每个实体都可以删除,不是每个实体都可以添加,不是每个实体都有一个存储库.查询千差万别;存储库 API 变得与实体本身一样独特.

No matter what clever mechanism I tried, I always ended up at the same problem: a repository is a part of the domain being modeled, and that domain is not generic. Not every entity can be deleted, not every entity can be added, not every entity has a repository. Queries vary wildly; the repository API becomes as unique as the entity itself.

为什么通用存储库是反模式的?

  1. 存储库是正在建模的域的一部分,该域不是通用的.
    • 并非每个实体都可以删除.
    • 并非每个实体都可以添加
    • 并非每个实体都有存储库.
    • 查询千差万别;存储库 API 变得与实体本身一样独特.
    • 对于 GetById(),标识符类型可能不同.
    • 无法更新特定字段 (DML).
  1. A repository is a part of the domain being modeled, and that domain is not generic.
    • Not every entity can be deleted.
    • Not every entity can be added
    • Not every entity has a repository.
    • Queries vary wildly; the repository API becomes as unique as the entity itself.
    • For GetById(), identifier types may be different.
    • Updating specific fields (DML) not possible.
  • 大多数 ORM 公开的实现与通用存储库非常相似.
  • 存储库应该使用 ORM 公开的通用查询机制为实体实现 SPECIFIC 查询.
  • 如果您接受作为参数的谓词标准,则需要从服务层提供.如果这是 ORM 特定的类,则会将 ORM 泄漏到服务中.

我建议你阅读这些(1234,5) 文章解释了为什么通用存储库是一种反模式.

I suggest you read these (1, 2, 3, 4, 5) articles explaining why generic repository is an anit-pattern.

更好的方法是:

  1. 跳过通用存储库.实施具体的代码库.
  2. 使用通用存储库作为抽象基础存储库.从中派生出所有具体的存储库.

无论如何,不​​要将通用存储库暴露给调用代码.另外,不要从具体的存储库中公开 IQueryable.

In any case, do not expose generic repository to calling code. Also, do not expose IQueryable from concrete repositories.

这篇关于当不同实体的工作非常不同时,我应该如何管理通用存储库模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆