Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

modelBuilder.Configurations.AddFromAssembly in EF Core

In EntityFramework 6.x, if we have lots of EntityConfiguration classes then we can assign all of them in OnModelCreating(ModelBuilder modelBuilder) as follows instead of one by one:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
   base.OnModelCreating(modelBuilder);

   modelBuilder.Configurations.AddFromAssembly(typeof(MyDbContext).Assembly);
}

Is there anything like modelBuilder.Configurations.AddFromAssembly in Entity Framework Core.

like image 286
TanvirArjel Avatar asked Aug 14 '18 13:08

TanvirArjel


People also ask

What is a ModelBuilder in Entity Framework Core?

The ModelBuilder is the class which is responsible for building the Model. The ModelBuilder builds the initial model from the entity classes that have DbSet Property in the context class, that we derive from the DbContext class. It then uses the conventions to create primary keys, Foreign keys, relationships etc.

What is ModelBuilder in .NET core?

In Entity Framework Core, the ModelBuilder class acts as a Fluent API. By using it, we can configure many different things, as it provides more configuration options than data annotation attributes.


1 Answers

For EF Core <= 2.1

You can write an extension method as follows:

public static class ModelBuilderExtensions
{
    public static void ApplyAllConfigurations(this ModelBuilder modelBuilder)
    {
        var typesToRegister = Assembly.GetExecutingAssembly().GetTypes().Where(t => t.GetInterfaces()
            .Any(gi => gi.IsGenericType && gi.GetGenericTypeDefinition() == typeof(IEntityTypeConfiguration<>))).ToList();

        foreach (var type in typesToRegister)
        {
            dynamic configurationInstance = Activator.CreateInstance(type);
            modelBuilder.ApplyConfiguration(configurationInstance);
        }
    }
}

Then in the OnModelCreating as follows:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
   base.OnModelCreating(modelBuilder);

   modelBuilder.ApplyAllConfigurations();
}

For EF Core >= 2.2

From EF Core 2.2 you don't need to write any custom extension method. EF Core 2.2 added ApplyConfigurationsFromAssembly extension method for this purpose. You can just use it as follows:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
   base.OnModelCreating(modelBuilder);

   modelBuilder.ApplyConfigurationsFromAssembly(typeof(UserConfiguration).Assembly); // Here UseConfiguration is any IEntityTypeConfiguration
}

Thank you.

like image 59
TanvirArjel Avatar answered Oct 31 '22 16:10

TanvirArjel