域驱动设计自动递增实体密钥 [英] Domain Driven Design Auto Incremented Entity Key

查看:75
本文介绍了域驱动设计自动递增实体密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅从域驱动设计开始,我已经了解到您应该将模型保持在有效状态,并且在创建类的新实例时,建议将所有必需的属性用作构造函数参数.

Just starting with Domain Driven Design and I've learned that you should keep your model in a valid state and when creating a new instance of a class it's recomended to put all required attributes as constructor parameters.

但是,当使用自动增量键时,当我从持久层调用Add方法时,我只有这个新ID.如果我实例化没有键的对象,我认为它们将处于无效状态,因为它们需要某种唯一的标识符.

But, when working with auto incremented keys I just have this new ID when I call an Add method from my persistent layer. If I instanciate my objects without a key, I think they will be in a invalid state because they need some sort of unique identifier.

在创建我的实体的新实例之前,我应该如何实现我的体系结构以获取ID?

How should I implement my architecture in order to have my IDs before creating a new instance of my entity ?

推荐答案

生成的随机ID

这里的实用方法是使用随机ID 并在实例化实体(例如实例化实体)之前生成它们.在工厂. GUID是常见的选择.

Generated Random IDs

The pragmatic approach here is to use random IDs and generate them before instantiating an entity, e.g. in a factory. GUIDs are a common choice.

在您问:不,您不会用完GUID :-)

如果由于某种原因必须使用顺序ID,那么您仍然可以选择:

If you must use a sequential ID for some reason, then you still have options:

  • 查询数据库上的序列以获取下一个ID.这取决于您的数据库产品,例如Oracle就有它们.)
  • 使用自动增量键创建一个表,该表仅用作键保留表.要获取ID,请在该表中插入一行-生成的密钥现在已为您保留,因此您可以将其用作实体的ID.

请注意,这两种用于顺序ID的方法都需要进行DB往返,然后才能开始创建实体.这就是为什么随机ID通常更简单的原因.因此,如果可以的话,请使用随机ID.

另一种可能性是忍受这样一个事实,即您在创建时没有ID,而只有在对DB的插入操作成功时才​​具有ID.以我的经验,这使实体创建难以使用,因此我避免使用它.但是对于非常简单的情况,这可能是一种有效的方法.

Another possibility is to just live with the fact that you don't have the ID at creation time, but only when the insert operation on the DB succeeds. In my experience, this makes entity creation awkward to use, so I avoid it. But for very simple cases, it may be a valid approach.

这篇关于域驱动设计自动递增实体密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆