design-patterns - 存储库/模型中的业务逻辑好吗?

标签 design-patterns model domain-driven-design

如果您有一个业务规则,其中表中的前 30 个项目永远不会被用户(或 UI)看到,您是否应该将此过滤器放在存储库的 GetAll() 中?意思是,存储库是否会处理数据过滤、数据成型以像 ViewModel 或 Controller 一样交还给调用者?我听说模型应该很厚,而 Controller /虚拟机应该很轻。

我遇到的问题是另一个与我共享项目的开发人员使他的所有存储库(每个表一个)都使用相同的实现,该实现只是将 LinqToSql 类型的属性复制到域类型。除了通过提供的 Func 更新和删除或获取数据之外,存储库本身没有逻辑。

另一方面,我为每个表创建了一个存储库(从 T 的 IRepository 继承),并将特定逻辑放在我认为需要逻辑来交回域对象的一些(不是全部)中。

所以在我的例子中,业务逻辑可以在存储库中完成,在他的例子中,它必须由用户完成,可以是服务或直接 ViewModel。哪个更受欢迎?

最佳答案

If you have a business rule where the first 30 items in table will never be seen by the user (or UI) should you put this filter in the Repository's GetAll()?

首先,这听起来不像是商业规则。业务规则用ubiquitous language表示除非您在数据库引擎上工作,否则这种语言没有像“表”这样的词。

回答你的主要问题,过滤逻辑绝对可以存在于存储库中。这就是repository是为了:封装存储、检索和搜索。关于存储库,需要了解的最重要的事情之一是它的接口(interface)属于领域层,而它的实现属于数据访问层。因此,在您的情况下,代码将如下所示:

域:

// repository interface:
public interface Orders{ 
   IList<Order> GetDelinquent();
}

数据访问:

public SqlOrders : Orders{ 
   IList<Order> GetDelinquent(){
      // do whatever needs to be done to find
      // delinquent orders in sql database.
      // filter first 30 records for example
   }
}

请注意,存储库界面使域成为焦点(我们不会说“除前 30 条记录外的所有记录”,我们说“拖欠”)。

The issue I'm running into is another developer who is sharing a project with me made all of his repositories (one per table) simply all use the same implementation that simply copies properties of a LinqToSql type to a domain type. There's no logic in the repository itself other than updating and deleting or getting data by a Func supplied.

I on the other hand created a repository (that inherited from IRepository of T) for each table and put specific logic in some (not all) where I felt logic was needed to hand back the domain objects.

通用存储库接口(interface)通常不是一个好主意,它过于以数据为中心,过于 CRUDy,请参阅 this answer获取详细信息和链接。

So in my case, business logic could be done in the repository, in his case it has to be done by the user which could be a service or the ViewModel directly. Which is more preferred?

业务逻辑和数据访问逻辑有很大区别。您希望避免将业务逻辑放入存储库实现中。此逻辑属于域对象。

关于design-patterns - 存储库/模型中的业务逻辑好吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9370000/

相关文章:

architecture - 在域驱动设计中将通用序列化类放在哪里?

java - Comparator 在域驱动的 MVC 世界中处于什么位置?

asp.net-mvc-3 - SelectList 中的本地化枚举字符串

entity-framework - 使用 ado Entity Framework 时在 DDD 中组织我的域对象

bash - 在 awk 中在文件中搜索时使用变量作为搜索模式时面临的问题

c# - 单例设计模式与静态类

ruby-on-rails - 保存 Rails 模型的所有属性

java - MVC : Should this function be in the Controller or in the Model

java - 动态创建 boolean 值列表

.net - 使用委托(delegate)的优点?