EF Core中的modelBuilder.Configurations.AddFromAssembly

Tan*_*jel 6 c# entity-framework-core asp.net-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);
}
Run Code Online (Sandbox Code Playgroud)

是否有任何类似 modelBuilder.Configurations.AddFromAssembly 实体框架核心。

谢谢。

Tan*_*jel 5

对于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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在OnModelCreating如下:

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

   modelBuilder.ApplyAllConfigurations();
}
Run Code Online (Sandbox Code Playgroud)

对于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
}
Run Code Online (Sandbox Code Playgroud)

谢谢。

  • 对于 2019 年 12 月发布的 EF Core 3.1,命令行必须为“modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());” (3认同)