0

I am developing with Entity Framework (Database First and Code First). Most of the time, I am using entities in my domain models, mapped to dedicated tables. In DDD, there is the concept of ValueObjects, that should have no identity and should be immutable. Based on your experience with DDD, how do you use ValueObjects ? Is that a concept that emerges from creating the model (for instance, when it deals with read-only data, parameters...) or is there any strategic behaviour that is expected or deductible from stating that an object should be designed like a ValueObject (or not), or should be immutable (or not) ?

Ruben Bartelink
  • 59,778
  • 26
  • 187
  • 249
Rénald
  • 1,412
  • 12
  • 29
  • 1
    *Value Objects* are super-useful in DDD. Here's a [comprehensive example](http://blog.ploeh.dk/2015/01/19/from-primitive-obsession-to-domain-modelling). However, I don't think this pattern is compatible with Entity Framework. Domain Models should be persistent-agnostic anyway, so if Entity Framework prevents you from modelling things properly, you'll have to choose: DDD or EF. You can't have both. – Mark Seemann May 06 '15 at 19:48

2 Answers2

1

There are couple of good examples of value objects on SO, check this question.

Value objects equality is established not by checking if they have the same id, but comparing values itself.

One more thing to consider is that EF is not supporting value objects properly (NHibernate does).

Community
  • 1
  • 1
Alexey Zimarev
  • 17,944
  • 2
  • 55
  • 83
1

As Alexey told with Entity Framework you have a problem (perhaps solved in the next version). To have EF populate your properties, the properties have to be public and settable. This makes it impossible to implement them as value objects. EF should be enhanced that it can load in (attributed) private properties or fields as well (as for example DataContractSerializer does that even don't use any constructor) to enable that. To come close to value objects with EF you could do the following:

Model your value objects as [ComplexType] in EF. Then they are not stored in an own table but the fields are embedded in any containing entity table. That comes close to the value semantic.

For immutability you could make your setters to allow one set only. The drawback is that the immutability is only enforced at runtime then. Another way would be to define interfaces for the classes that only have getters and use only this interfaces outside the dal. A third way would be to use the EF classes just as DTOs and fill them in your domain model objects (with true value objects).

Holger Thiemann
  • 1,042
  • 7
  • 17