In domain-driven design, we are encouraged to build rich entities which express real concepts in the domain.
Let's say we have an entity Vehicle which references an aggregate root, Person, by identity - a Vehicle is owned by a Person.
But, a Vehicle can exist at a point of time without an owner, say just after it is manufactured.
How would you model this?
One way could be with a Nullable type:
public class Vehicle : DomainEntity<Guid>
{
public Guid? Owner { get; private set; }
public Vehicle(...)
: base(Guid.NewGuid())
{
//...
}
public Vehicle(Guid owner, ...)
: base(Guid.NewGuid())
{
Owner = owner;
//...
}
}
Another way is to use multiple classes and inheritance:
public class Vehicle : DomainEntity<Guid>
{
public Vehicle(...)
: base(Guid.NewGuid())
{
//...
}
}
public class OwnedVehicle : Vehicle
{
public Guid Owner { get; private set; }
public OwnedVehicle(Guid owner, ...)
: base(Guid.NewGuid())
{
Owner = owner;
//...
}
}
I would much prefer to use the second approach, but can one really model aggregate roots like this?
What exactly would the aggregate root be; Vehicle or OwnedVehicle?
Would we now have two separate repositories or would the repository return the base type, Vehicle? This would mean that we would need to cast - not ideal.
Vehicleis owned by aPersonwouldn't it be thePersonwho'd have zero or many references to theVehiclesthey own? The example you've given is constrained by the constraints imposed by using a relational database. I.e. it's being constrained by technicalities of a persistence concern. - Adrian Thompson Phillips