0

我读过一次:

“除非你有充分的理由,否则不要将实体作为 getter 和 setter 的袋子,并将它们的方法放在另一层中”

我的客户、订单、...对象只是从 SqlDataReaders 获取数据。他们只有 getter 和 setter。

我的第一个问题是当有人在实体中实现方法时遵循哪种设计方法,这些方法在做什么?

4

2 回答 2

4

这种思维方式来自领域驱动设计社区。

In DDD you create a Domain Model that captures the functionality that your users request. You design your entities as having functionality and the data they need for it. You group them together in aggregates and you have separate classes that are responsible for construction (Factories) and querying (Repositories).

If you only have getters/setters you have an 'Anemic Domain Model'. Martin Fowler wrote about it in this article.

The problem with an Anemic Domain model is that you have the overhead of mapping your database to objects but not the benefits of it. If you don't use your entities as a real domain model, why don't you just use a DataTable or something for your data and keep your business logic in separate functions? An Anemic Domain model is an anti-pattern that should be avoided.

You also mention that you map the entities yourself. This blog explains why using an Object-Relational Mapping tool can really help. If you use Entity Framework with a Code First approach you can write a clean domain model with both data and functionality and map it to your database without much hassle. Then you will have the best of both worlds.

于 2012-07-27T17:14:38.833 回答
1

当您将方法作为模型的一部分时,您应该只包含模型特定类型的逻辑。例如,考虑一个银行账户:

public class Account {
   public AccountId Id { get; set; }
   public Person Customer {get; set; }

   public void Credit(Money amount) { ... }
   public void Debit(Money amount) { ... } 

}

Credit 和 Debit 是特定于模型的逻辑(您不会在应用程序的其他任何地方找到它们),并且应该封装在 Account 类中。

您还提到您在模型类中使用 SqlDataReader 从数据库中获取数据。这是一个很大的反模式。以下是您将遇到的一些问题:

  1. 违反单一职责原则 - 该模型现在负责表示数据并从数据库中获取数据。
  2. 在你的模型中查询孩子怎么样?它变得混乱。
  3. 您将无法轻松更改数据访问权限。

保持模型精益。将数据访问逻辑放在一个存储库中,即AccountRepository。

于 2012-07-27T17:08:55.790 回答