Do you keep your domain layer independent of the data access concerns?

Last updated by Brady Stroud [SSW] about 1 month ago.See history

The domain layer should be independent of data access concerns. The domain layer should only change when something within the domain changes, not when the data access technology changes. Doing so ensures that the system will be easier to maintain well into the future since changes to data access technologies won't impact the domain, and vice versa.

This is often a problem when building systems that leverage Entity Framework, as it's common for data annotations to be added to the domain model. Data annotations, such as the Required or MinLength attributes, support validation and help Entity Framework to map objects into the relational model. In the next example, data annotations are used within the domain model:

domain layer 1
Bad Example: Domain is cluttered with data annotations

As you can see in the above example, the domain is cluttered with data annotations. If the data access technology changes, we will likely need to change all entities as all entities will have data annotations. In the following example, we will remove the data annotations from the entity and instead use a special configuration type:

domain layer 2

domain layer 3

domain layer 3
Good Example: Domain is lean, configuration for entity is contained within a separate configuration type

This is a big improvement! Now the customer entity is lean, and the configuration can be added to the persistence layer, completely separate of the domain. Now the domain is independent of data access concerns.

Learn more about this approach by reading about self-contained configuration for code first.

Figure: Database implementation is a Infrastructure concern not a Domain concern

Jason Taylor
Matt Wicks
We open source. Powered by GitHub