Apply all IEntityTypeConfiguration derived classes in EF Core

瘦欲@ 提交于 2020-01-13 11:07:32

问题


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.


回答1:


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.




回答2:


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);
    }
}



回答3:


This is now built in to EF Core 2.2:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.ApplyConfigurationsFromAssembly(typeof(PersonConfiguration).Assembly);
}


来源:https://stackoverflow.com/questions/47654500/apply-all-ientitytypeconfiguration-derived-classes-in-ef-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!