C# – Entity unique identifier in domain driven design

cdomain-driven-design

I'm just learning DDD and a question raised in my mind about unique identifiers in an entity.

Consider this simple method that checks the uniqueness of an entity to prevent duplication:

    private bool IsDuplicate(BoardGame boardGame)
    {
        //It's either this
        if (Games.Any(x => x.Id == boardGame.Id)) return true;

        //Or this
        if (Games.Any(x => x.Name == boardGame.Name && x.Price == boardGame.Price)) return true;

        return false;
    }

The first method is very clean and readable.
The problem is we usually don't have the value of Id
before the item is persisted somehow
because it is handled by the ORM.

The second method is the way how an object is considered unique
from a domain point of view. We can evaluate this uniqueness before
persisting the object
But the downside is it gets messy when an entity's uniqueness becomes more complicated.

Now the question is, isn't that Id field redundant?
don't we have to check this uniqueness with domain perspective anyway?
why not having, say, a composite/compound key in ORM/Persistence side?

Of course this is an example. The name or price could change, but remember, I said that in the domain perspective, the name should be unique.

Consider having a Member entity, with his/her SSN as a unique identifier.

Best Answer

I'm just learning DDD and a question raised in my mind about unique identifiers in an entity.

Identity, especially identity of real world objects, is much more subtly difficult than the DDD literature suggests.

In most cases, identity is really correlation. How do I get my car back from the valet? I show the valet a ticket stub with a number that matches the number he has attached to my car keys. Since the numbers match, this must be the "same" ticket, and therefore I must be the person that has claim to the car.

Gregor Hohpe's patterns work includes a discussion of correlation identifiers.

Correlation identifiers are often domain data, not something arbitrarily created by the ORM. We produce some distinguishing identifier at the beginning of a conversation, and then use that same identifier to track other contributions to the same conversation.

And yes, when you are in a domain where these identifiers may be re-used, there is the extra burden of keeping track of which "entity" the identifier is supposed to represent.

Now the question is, isn't that Id field redundant?

Only if the fields you are comparing to are immutable. Entities tend not to be immutable, but instead transition from one state to another during their lifetimes. Halloway's Perception and Action is a good overview.