Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply all IEntityTypeConfiguration derived classes in EF Core

Does anyone know of a way or have an implementation to apply ALL classes that derive from IEntityTypeConfiguration<> to the DbContext at runtime?

There doesn't seem to be anything built in and loading each one manually via:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.ApplyConfiguration(new Table1Config())
    modelBuilder.ApplyConfiguration(new Table2Config())
    ...
    modelBuilder.ApplyConfiguration(new TableNConfig())
}

is going to prove rather tedious for a database with many tables.

like image 973
Jay Avatar asked Dec 05 '17 13:12

Jay


People also ask

How does EF support inheritance?

By default, EF maps the inheritance using the table-per-hierarchy (TPH) pattern. TPH uses a single table to store the data for all types in the hierarchy, and a discriminator column is used to identify which type each row represents.

What is ModelBuilder in Entity Framework 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.

What is the use of OnModelCreating?

The DbContext class has a method called OnModelCreating that takes an instance of ModelBuilder as a parameter. This method is called by the framework when your context is first created to build the model and its mappings in memory.

What is IEntityTypeConfiguration?

IEntityTypeConfiguration<TEntity> InterfaceAllows configuration for an entity type to be factored into a separate class, rather than in-line in OnModelCreating(ModelBuilder).


3 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 115
TanvirArjel Avatar answered Nov 08 '22 23:11

TanvirArjel


This is now built in to EF Core 2.2:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.ApplyConfigurationsFromAssembly(typeof(PersonConfiguration).Assembly);
}
like image 21
Matt Jenkins Avatar answered Nov 08 '22 23:11

Matt Jenkins


protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    var implementedConfigTypes = Assembly.GetExecutingAssembly()
        .GetTypes()
        .Where(t => !t.IsAbstract
            && !t.IsGenericTypeDefinition
            && t.GetTypeInfo().ImplementedInterfaces.Any(i =>
                i.GetTypeInfo().IsGenericType && i.GetGenericTypeDefinition() == typeof(IEntityTypeConfiguration<>)));

    foreach (var configType in implementedConfigTypes)
    {
        dynamic config = Activator.CreateInstance(configType);
        modelBuilder.ApplyConfiguration(config);
    }
}
like image 4
Jay Avatar answered Nov 08 '22 22:11

Jay