EF Core 中的 modelBuilder.Configurations

在 中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 在 实体框架的核心。


缥缈止盈
浏览 585回答 1
1回答

梵蒂冈之花

对于 EF 核心 <= 2.1你可以写一个扩展方法如下:public static class ModelBuilderExtensions{&nbsp; &nbsp; public static void ApplyAllConfigurations(this ModelBuilder modelBuilder)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var typesToRegister = Assembly.GetExecutingAssembly().GetTypes().Where(t => t.GetInterfaces()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Any(gi => gi.IsGenericType && gi.GetGenericTypeDefinition() == typeof(IEntityTypeConfiguration<>))).ToList();&nbsp; &nbsp; &nbsp; &nbsp; foreach (var type in typesToRegister)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dynamic configurationInstance = Activator.CreateInstance(type);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; modelBuilder.ApplyConfiguration(configurationInstance);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}然后在OnModelCreating如下:protected override void OnModelCreating(ModelBuilder modelBuilder){&nbsp; &nbsp;base.OnModelCreating(modelBuilder);&nbsp; &nbsp;modelBuilder.ApplyAllConfigurations();}对于 EF Core >= 2.2从 EF Core 2.2 开始,您无需编写任何自定义扩展方法。EF Core 2.2ApplyConfigurationsFromAssembly为此添加了扩展方法。您可以按如下方式使用它:protected override void OnModelCreating(ModelBuilder modelBuilder){&nbsp; &nbsp;base.OnModelCreating(modelBuilder);&nbsp; &nbsp;modelBuilder.ApplyConfigurationsFromAssembly(typeof(UserConfiguration).Assembly); // Here UseConfiguration is any IEntityTypeConfiguration}谢谢你。
打开App,查看更多内容
随时随地看视频慕课网APP