Using IEntityTypeConfiguration config classes to configure Entity Framework entity mappings

When using Entity Framework, storing mapping configurations inline directly in OnModelCreating can make our DbContext class cumbersome and less readable especially when we override the defaults at lot.

Thankfully it’s possible to separate out our mapping configurations into dedicated per entity config classes by implementing IEntityTypeConfiguration<TEntity>.

This can create a more structured and organized codebase and below is an example of how it’s done.

Click on the image for a larger view in a new window.

Entity Framework IEntityTypeConfiguration example

We can see that we have two approaches to registering implementers of IEntityTypeConfiguration<TEntity> in the OnModelCreating method:

  1. Declare each one explicitly.
  2. Register all config classes automatically by using ApplyConfigurationsFromAssembly.

The 2nd approach is obviously more ideal as you don’t have to explicitly register a new config class every time you create a new entity which is a nice little maintenance win.

What do you think?

What approach to configuration do you like to use?
Inline or configuration via classes which implement IEntityTypeConfiguration?

Where do you store you configuration classes?

Many devs keep them in the same general folder as the DbContext but I like to kept them in the same file as the the domain entity itself. Although plenty of devs will say this is ‘polluting the domain’ 🤷🏻‍♂️ I find it really useful as often the domain and the mappings will change together.

Leave a Reply

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