EF Core中的modelBuilder.Configurations.AddFromAssembly

时间:2018-08-14 13:29:58

标签: c# asp.net-core entity-framework-core ef-core-2.1

EntityFramework 6.x中,如果我们有很多EntityConfiguration类,则可以按如下方式在OnModelCreating(ModelBuilder modelBuilder)中分配所有这些类,而不是一一对应:

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

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

实体框架核心中是否有 modelBuilder.Configurations.AddFromAssembly 之类的东西。

谢谢。

1 个答案:

答案 0 :(得分:3)

对于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
}

谢谢。