在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
之类的东西。
谢谢。
答案 0 :(得分:3)
您编写如下扩展方法:
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为此添加了ApplyConfigurationsFromAssembly
扩展方法。您可以按如下方式使用它:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.ApplyConfigurationsFromAssembly(typeof(UserConfiguration).Assembly); // Here UseConfiguration is any IEntityTypeConfiguration
}
谢谢。