在域模型中实例化集合是否被认为是一个好的实践?

发布于 2024-11-18 14:05:13 字数 532 浏览 7 评论 0原文

我在网上看到这些类型的模型有很多样本。

public class User
{
    public long Id { get; set; }
    public string Name{ get; set; }
    public virtual ICollection<Product> Products { get; set; }
}

像下面的代码一样在构造函数中实例化集合是否被认为是一个好习惯?若有,原因为何?模型中的对象怎么样?

public class User
{
    public User()
    {
        Products = new List<Product>();
    }
    public long Id { get; set; }
    public string Name{ get; set; }
    public virtual ICollection<Product> Products { get; set; }
}

I see these types of model is many samples online.

public class User
{
    public long Id { get; set; }
    public string Name{ get; set; }
    public virtual ICollection<Product> Products { get; set; }
}

Is it considered a good practice to instantiate a collection in the constructor like the code below? If so what are the reasons? How about objects in the model?

public class User
{
    public User()
    {
        Products = new List<Product>();
    }
    public long Id { get; set; }
    public string Name{ get; set; }
    public virtual ICollection<Product> Products { get; set; }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

卖梦商人 2024-11-25 14:05:13

好吧,我想说这取决于具体情况,但在这种情况下,产品将通过存储库从数据库中填充,因此很可能是某种 ORM,因此构造函数中不需要初始化新的 List。 Products 的 null 含义表示列表尚未加载。另一方面,假设您的对象必须初始化此集合。对于简单对象,DDD 表示构造函数非常适合这些事情,但对于复杂对象,请将构造移至工厂。

Well, I would say it depends on the situation, but Products in this case would be filled from the database, via a repository, so most probably ORM of some sort, so no initialization to new List would be needed in the constructor. The meaning of null for Products is indicative that the list isn't loaded yet. On the other hand, let's say that your object must have this collection initialized. For simple objects DDD says constructors are perfectly fine to to these things, but in case of complex objects, move the construction to the Factory.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文