在EF Core中应用所有IEntityTypeConfiguration派生类

时间:2017-12-05 13:11:19

标签: c# entity-framework entity-framework-core

有没有人知道某种方法或有实现在运行时将IEntityTypeConfiguration<>派生的所有类应用到DbContext

似乎没有内置任何内容并通过以下方式手动加载每个:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.ApplyConfiguration(new Table1Config())
    modelBuilder.ApplyConfiguration(new Table2Config())
    ...
    modelBuilder.ApplyConfiguration(new TableNConfig())
}
对于具有许多表的数据库来说,

将变得相当繁琐。

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:2)

现在已内置到EF Core 2.2:

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

答案 2 :(得分:2)

对于EF Core <= 2.1

您可以编写如下扩展方法:

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

然后在OnModelCreating中进行如下操作:

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

   modelBuilder.ApplyAllConfigurations();
}

对于EF Core> = 2.2

EF Core 2.2中,您无需编写任何自定义扩展方法。 EF Core 2.2为此添加了ApplyConfigurationsFromAssembly扩展方法。您可以按如下方式使用它:

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

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

谢谢。