gpt4 book ai didi

entity-framework - 在领域驱动设计中为模型属性设置默认值的最佳实践?

转载 作者:行者123 更新时间:2023-12-04 12:34:05 25 4
gpt4 key购买 nike

在 DDD 中为新实体设置默认属性的最佳方法是什么?另外,为复杂属性(例如集合)设置默认状态的最佳方法是什么?

我的感觉是默认值应该在模型本身中,因为它们是一种业务规则形式(“默认情况下,我们希望 X 是 Y 和 Z”),并且域代表业务。使用这种方法,模型本身的静态“GetNew()”方法可能会起作用:

public class Person {    public string Name { get; set; }    public DateTime DateOfBirth { get; set; }    public bool IsAlive { get; set; }    public List Limbs { get; set; }    public static Person GetNew() {        return new Person() {             IsAlive = true,            Limbs = new List() { RightArm, LeftArm, RightLeg, LeftLeg }        }    }}

Unfortunately in our case, we need the collection property to be set to all members of another list, and as this model is decoupled from its Repository/DbContext it doesn't have any way of loading them all.

Crappy solution would be to pass as parameter :

public static Person GetNew(List<Limb> allLimbs) {
return new Person() {
IsAlive = true,
Limbs = allLimbs
}
}

或者有没有更好的方法来为简单和复杂的模型属性设置默认值?

最佳答案

这是 factory pattern in DDD 的一个实例.它可以是专用类,例如 PersonFactory或静态方法,如您的示例所示。我更喜欢静态方法,因为我认为没有必要创建一个全新的类。

至于初始化集合,GetNew将集合作为参数的方法是我会采用的方法。它声明了一个重要的约束——要创建一个新的个人实体,您需要该集合。集合实例将由托管特定用例的应用程序服务提供。更一般地说,默认值可以存储在数据库中,在这种情况下,应用程序服务将调用存储库以获得所需的值。

关于entity-framework - 在领域驱动设计中为模型属性设置默认值的最佳实践?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14616611/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com