The Fluent API is one of the preferred ways to achieve the EntityType Configurations EF Core. In our previous tutorial on Fluent API in Entity Framework Core, We showed you how to configure an entity. We put all our configurations in the DbContext
class. In this tutorial, we will show how to move the configurations to separate configuration classes using the IEntityTypeConfiguration
Interface.
Table of Contents
Entity Type Configuration in Context file
We use the Modelbuilder
class to configure the Entities. We get the reference to the Modlebuilder
class by overriding the OnModelCreating
method of the DbContext
object.
For Example,
1 2 3 4 5 6 7 8 9 | protected override void OnModelCreating(ModelBuilder modelBuilder) { //Configure domain classes using modelBuilder here modelBuilder.Entity<Employee>() .HasKey(e => e.EmployeeID); } |
The above code shows how to configure the employee entity in the OnModelCreating
method. We can put all our Fluent API Configuration commands in the OnModelCreating
method. But as the application grows it will become very cumbersome to manage all the configuration in one place.
It is better to put the configuration information to a separate class and call it from the OnModelCreating
method.
EntityType Configuration Interface
The IEntityTypeConfiguration
is introduced in EF Core 2.0. The interface has the method Configure
, which we must implement in a separate configuration class for an entity type. Then we invoke the ApplyConfiguration
method of the modelbuilder
passing the instance of the newly created configuration class.
Separate Configuration File per entity
The following code shows how to move the configuration out of ModelBuilder
class
First, create a separate class EmployeeConfiguration
which implements the IEntityTypeConfiguration
interface.
Then, create the method Configure
and put all the configuration of the Employee entity.
1 2 3 4 5 6 7 8 9 | public class EmployeeConfiguration : IEntityTypeConfiguration<Employee> { public void Configure(EntityTypeBuilder<Employee> builder) { builder.HasKey(e => e.EmployeeID); } } |
Finally, use the ApplyConfiguration
of the modelbuilder
and pass it the instance of the just created EmployeeConfiguration
class.
1 2 3 4 5 6 7 8 9 | protected override void OnModelCreating(ModelBuilder modelBuilder) { //Configure domain classes using modelBuilder here modelBuilder.ApplyConfiguration<Employee>(new EmployeeConfiguration()); } |
Thats it.
Bulk Register Configurations
If you have many models, you will end up with many configuration files. You also have to remember to add the configuration file in the OnModelCreating
method.
You can use the ApplyConfigurationsFromAssembly
extension method, which uses the reflection to find all the configuration files and registers them automatically.
1 2 3 4 5 6 | protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.ApplyConfigurationsFromAssembly(typeof(EmployeeConfiguration).Assembly); } |