Using Code First Model Configurations Classes
In the past I explained how to use the Code First Fluent API in order to configure and shape your EDM during runtime. One of the problems that might raise when you use the Fluent API as I showed in the previous post is that the OnModelCreating method might become bloated and hard to read. This is the time to get familiar with another model configuration option which is built inside Code First.
Model Configurations Classes
When you use Code First you will probably configure the creation of the model in some way. You can use the Code First Fluent API in order to do that. When you use the Fluent API the place that you will use it is the OnModelCreating method in the DbContext class. In very big models that might be a problem. Quickly you will find yourself having a very big and bloated method which holds all the configurations. This is the time for refactoring your code to use model configurations. There are two major classes that you will use: the generic EntityTypeConfiguration and ComplexTypeConfiguration. Both of the classes lives in the System.Data.Entity.ModelConfiguration assembly.
Lets revisit the DbContext from the previous post:
If I want to use the EntityTypeConfiguration I’ll create a new class for Department configuration. The class will inherit from EntityTypeConfiguration<Department> and in its constructor I’ll use the Fluent API for configurations. The following code sample shows the DepartmentTypeConfiguration class:
Now that we have the class we will wire it into the ModelBuilder by using the Add method of its Configuration collection. The following code sample show you how to do that:
During runtime we will get the same EDM whether we use the first method with the configurations inside the OnModelCreating method or the second method of EntityTypeConfiguration.
When you use Code First you get a lot of configuration options. If your model is small you can create all the configurations inside the OnModelCreating method. When the model starts to grow you can use the ModelConfiguration classes in order to divide your implementation to small objects with configuration responsibility.