Reputation: 2832
In a studied domain, a Car
may have many Tire
s and according to DDD concepts, Car
is an aggregate root
while Tire
is a Value Object
. '
Consider the following model:
class Car
{
public int Id {get;set;}
public virtual ICollection<Tire> Tires {get;set;}
}
[ComplexType]
class Tier
{
public string Manufacturer {get;set;}
public int Diameter {get;set;}
}
I'm afraid EF 6.0 + cannot implement this model. Am I right? Any way to implement Collection of Value Objects?
Upvotes: 2
Views: 1463
Reputation: 6491
Complex types, according to MSDN documentation, cannot participate in associations and cannot contain navigation properties so this is not the right way. With EF the only way is to have 2 tables (with an Id on the Tires table). You can also hide Id of the Tires table, you can insert a unique index on the foreign key of the Cars table but when you check if two tires are equal you need to check if both properties are equal.
Upvotes: 2
Reputation: 2745
This is a common issue with normalized persistence (which includes the SQL server which you access through EF). Entity framework makes it more difficult by not allowing you to have a protected key though.
One way is to have a Tires table which has an id, which will form part of a foreign key relationship with car. However, the idea of a unique key violates the fact that value objects should not rely on id's and should be compared by value. Being diligent, overriding Equals, and only comparing by value will allow you work with this solution; it does not matter if the actual objects are different as long as the equality comparison would return true if two tires matched. It is not pretty, I agree, but with EF it seems to be the only solution. If I am wrong, please someone correct me. If you go this route, remember to map your domain data to your DTO's in a way that the Id is removed. That way you keep the fact that tires have an id isolated.
Another solution is to serialize the tires using Json before being sent to SQL db (and then deserialize it back on read), but that is not something that I would personally suggest if you need to query on information in the tires (for example give me all cars that use this kind of tyre).
PS: Vaughn Vernon discusses this particular issue with Hibernate for Java in this book: http://www.amazon.co.uk/Implementing-Domain-Driven-Design-Vaughn-Vernon/dp/0321834577 Please read, it will solve a lot of the issues or questions you may have on the subject.
Upvotes: 2