Map private fields in Entity framework core

In DDD you always want to control what is being put into your domain object. That can be done with public getters and private setters. But when it comes to collections (e.g. System.Collections.Generic.List<T>) it becomes more complicated, due to the fact the the domain object exposes an object of type List<T> which can be modified.

When we are using an ORM like Entity framework core it is quite easy to map a domain object where properties have public/protected getters and setters. But sometimes we loose control over our domain objects exposing collections to the public audience. That is why we need to make them private.

Let me show an example where the control of an domain object is being lost.

As you can see we can put in pretty much anything, or nothing as a part. There is no validation and control over the domain object.

If we define the list as a private field instead we need to have a method that adds the part. This method can then validate the object being passed to us. To show the list of parts we can simply create a getter for this.

When using Entity framework core as an ORM this can be a bit tricky to configure. We need to instruct the DBContext to look for private fields when creating the model. This can be done very easily with the “FindNavigation” method which returns an IMutableNavigation object. This object represents a navigation property which can be used to navigate a relationship in an entity.

This is really a nice feature that soon will be introduced as a fluent configuration as well. Keep an eye on the GitHub issue 6674 for Entity framework core.

Leave a Comment

Your email address will not be published. Required fields are marked *