Patrick Desjardins Blog
Patrick Desjardins picture from a conference

How to register Model Builder without having to manually add them one by one

Posted on: 2014-01-31

When you are using Entity Framework, you must have a class that inherit DbContext class at some point. Multiple options is offer to you to register to Entity Framework (EF) definition of your entities.

The one we see in tutorial is based on the overridden method OnModelCreation that has a single parameter of type DbModelBuilder. This is the entry point for all way to proceed with registration. Nevertheless, in tutorial the configuration is done directly in the method. The following code shows how it is usually done. For the purpose of being short, only a single primary key is defined for a single entity. The fact is that method can become very big.

public class MyDbContext : DbContext { protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<YourEntity>().HasKey(d => d.Id); base.OnModelCreating(modelBuilder); } } 

This is why, the best practice is to have a single class for every entity configuration. This is done by inheriting every classes by EntityTypeConfiguration.

public class YourEntityConfiguration : EntityTypeConfiguration<YourEntity> { public YourEntityConfiguration() { this.HasKey(d => d.Id); } } 

Once you have your classes defined, the OnModelCreating can register them.

public class MyDbContext : DbContext { protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Configurations.Add(new YourEntityConfiguration()); base.OnModelCreating(modelBuilder); } } 

The problem is that you have to remember to register the entity and also that this method can become very huge on big project. Concerning the possibility to forget to register, Entity Framework (EF) will raise an exception saying that it does not know the entity type. It is not a big deal and the message is quite easy to understand. However, having to add this line of code become something to do in a big list of things to do. To keep it simpler, Entity Framework team thought that we could simply specify which assembly every configuration are and to look up for every classes that inherit the EntityTypeConfiguration.

 public class MyDbContext : DbContext { protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Configurations.AddFromAssembly(Assembly.GetAssembly(GetType())); //Current Assembly base.OnModelCreating(modelBuilder); } } 

The above example shows that configurations are added from an assembly. It takes a single parameter that is the assembly to look up. If you want the current assembly, use Assembly.GetAssembly(GetType()).