entitydomain-driven-designauto-increment

Domain Driven Design Auto Incremented Entity Key


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.

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.

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


Solution

  • 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.

    And before you ask: No, you won't run out of GUIDs :-)

    Sequential IDs with ID reservation

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

    Note that both approaches for sequential IDs require a DB round-trip before you even start creating the entity. This is why the random IDs are usually simpler. So if you can, use random IDs.

    DB-generated IDs

    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.