1

I have a Customer which can have sereval address. Sereval customers can possibily live at the same address. So in my relational database a classic many to many relationship.

As :

  • An address can not change (a customer can change address);
  • It does not involve any logic with side effect.
  • And the equility between two adress is determine only with the values in it.

I argue address is a good candidate to be a value object.

However I need (or maybe not) to persist my customers address and to do so I need to add an Id.

I am a little bit confused and struggled, I think pure domain logic and common sens tell me is a value object but the technology constraint makes that an address has an Id.

Is it fine to store value object?

2

An address object (which refers to a street address) can be modeled either as a value object or as an entity. The trade-off lies mostly in the database/storage layer.

If you design your storage to assign an ID to your address object, you are effectively choosing to treat your address objects as entities.

If you want to treat addresses as value objects, you can store them within the Customer table (which limits you to a fixed number of addresses per customer), or in a table without a primary key, but with a foreign key linking it to the Customer table. This means that you can't represent the situation that multiple customers share an address, as each customer will get its own address records in the storage.

1

Having multiple value objects of the same type relate to an Entity is a common use-case.

What I usually do is to model my value objects differently, and try to understand if it's better to have a collection of value objects relate to the entity.

So in your case, your value object is actually an AddressCollection value object (in your code) and you can chose to store it as serialised data in your DB (same table of your entity) or in a separate table, where the id of each row can (and it should) be the composition of the values of the row.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.