DDD和持久性。再次持久性、DDD

2023-09-06 10:24:46 作者:你打不过我的

我挣扎与持久性的领域驱动设计。据我了解,领域模型不应该是持久的感知。比方说,我建立了一个简单的待办事项列表应用程序。我有如下界面任务:

I am struggling with persistence in Domain Driven Design. As far as I understand, domain model should never be persistent-aware. Let's say I am building a simple todo-list application. I have a task with following interface:

interface ITask
{
   bool IsCompleted {get;}
   string Description {get;}

   void Complete();
   void ChangeDescription(string description);
}

和一般的执行应该是这样的:

And the generic implementation should look like this:

class SimpleTask : ITask
{
    public SimpleTask(string description)
    {
       ChangeDescription(description);
    }

    public bool IsCompleted { get; private set; }
    public string Description { get; private set; }

    public void Complete()
    {
       IsCompleted = true;
    }

    public void ChangeDescription(string description)
    {
       // some validation here
       // ...
       Description = description;
    }
}

我想有一个描述是必要的 - 因为它是一个业务规则。所以,从这一刻开始,如果我想通过串行我会失败,因为没有参数的构造函数提供了保存这个对象。而且我不应该提供,因为没有持久性意识的规则吧。如果我在DTO \ POCO的表单模型我的任务,我将结束与另一个问题 - 所谓贫血模型。此外,我不想制定者提供一些属性。

I want to have a description be necessary - because it's a business rule. So from this moment if I want to save this object via serializers I will fail because no parameterless constructor provided. And I shouldn't provide it because of no persistance-aware rule. If I model my task in a form of DTO\POCO I will end up with another problem - so called anemic model. Moreover, I don't want to provide setters to some properties.

那么,是解决这一切?我可以创建一个紧密耦合的保护程序,将知道如何保存和恢复工作状态。但我只能访问公共属性和方法,如果任务的内部逻辑将是复杂的,不可能救什么\恢复?我应该标志着在任务中的所有领域内,有可能保存对象的内部状态?是不是有点儿code无持续性感知规则的气味和侵犯?

So where is the solution to all of this? I can create a tightly-coupled saver that will know how to save and restore task state. But I can access only public properties and methods, what if internal logic of task will be complex and impossible to save\restore? Should I mark all fields in task internal and have a possibility to save inner state of object? Isn't it kinda code smell and violation of no persistence-aware rule?

你怎么解决这个问题?

推荐答案

从我的理解,实体框架要少得多灵活比Hibernate的,所以你将不得不作出的模式多一点妥协。沃恩弗农,实施领域驱动设计(IDDD)的作者显示保持自我的好方法封装的实体,而使其易于使用实体框架要坚持自己的状态。

From my understanding, Entity Framework is much less flexible than Hibernate so you will have to make a bit more compromises in the model. Vaughn Vernon, the author of Implementing Domain-Driven Design (IDDD) shows a great way of keeping self-encapsulated entities while making it easy to persist their state using Entity Framework.

如果你可以使用你选择的持久存储,您不妨使用href="https://vaughnvernon.co/?p=942" rel="nofollow">不同的策略一个