Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with value objects in Entity Framework?

Tags:

How do I persist value objects in Entity Framework without polluting my domain model? EF (well, relational DBs in general) require me to define a key - which my value objects don't have out of the box, for example

public class Tag : ValueObject<Tag>
{
   private readonly string name;

   public Tag(string name)
   {
      this.name = name;
   }

   public string Name { get { return this.name; }}
}

On the other hand, I shouldn't address persistence concerns in the model. Am I really supposed to create another class that includes all the fields from the value object plus a key property and then map them to each other? I'd rather not.

Is there maybe a more elegant solution?

like image 426
Thorsten Westheider Avatar asked May 23 '15 03:05

Thorsten Westheider


People also ask

How should you implement a value object?

The first characteristic was already discussed. Immutability is an important requirement. The values of a value object must be immutable once the object is created. Therefore, when the object is constructed, you must provide the required values, but you must not allow them to change during the object's lifetime.

What is a value object in C#?

A value object is an object without an explicit identifier. Its first main characteristic is that it does not require an identity. The second principal characteristic is that value objects must be immutable. It means that once value object properties are initialized, we can't change their values.

Why do we need value objects?

Value Objects can be especially useful as a means for describing concepts in an application that have intrinsic rules but which are not themselves entities. In many applications, some concepts that are described as entities would be better off implemented as value objects.


1 Answers

Vaughn Vernon writes about Persisting Value Objects (page 248) in his excellent book Implementing Domain-Driven Design.

ORM and Single Value Objects

The basic idea is to store each of the attributes of the Value in separate columns of the row where its parent Entity is stored. Said another way, a single Value Object is denormalized into its parent Entity's row. There are advantages to employing convention for column naming to clearly identity and standardize the way serialized objects are named.

ORM and Many Values Backed by a Database Entity

A very straightforward approach to persisting a collection of Value instances using an ORM and a relational database is to treat the Value type as an entity in the data model. (...) To accomplish this we can employ a Layer Supertype.

Sample bounded contexts in C# can be found here: https://github.com/VaughnVernon/IDDD_Samples_NET

like image 52
Martin4ndersen Avatar answered Nov 14 '22 15:11

Martin4ndersen