Entity Framework entity configuration with Fluent API

If you’re using the Code First approach in Entity Framework accepting the default mappings can result in an inefficient DB design which wastes space as EF will for example convert C# strings to nvarchar(max) columns in SQL Server.

Fortunately we can configure the mappings quite easily using either the Entity Framework Fluent API or the Data Annotations approach. This posts looks at the EF Fluent API approach.

To configure our entity models with the Entity Framework Fluent API we have four options shown below…

  1. Inline mappings are probably what most people do. They get the job done but OnModelCreating can get really large very quickly.

  2. Moving configs to a separate class and referencing the class from OnModelCreating is a nice way to keep OnModelCreating small. Need to explicitly reference a config class for each entity.

  3. Similar to 2 but the class can be anywhere in the assembly. Need to explicitly reference a config class for each entity.

  4. The last approach is my favourite, this will apply configs from anywhere in the assembly. This can be done as all config classes implement IEntityTypeConfiguration. Using this approach means with don’t have to amend our OnModelCreating method every time we add or delete entities.

In general when configuring entities using the Fluent API I prefer the separate class approach. Personally I like to put the config mapping classes in the same file as the entity as this results in a good developer experience as it’s easy to see what config applies to particular properties.

Many developers think that using the Data Annotation approach ‘pollutes’ the domain layer so I think keeping entity and entity config together is a good practical compromise… but as always do what works for your team 😊 …

Leave a Reply

Your email address will not be published.