EF核心 - 实体映射配置

时间:2018-03-01 09:51:59

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

在以前版本的EF中,您可以在DbContext上配置所有实体地图,如下所示: -

  protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                modelBuilder.Configurations.AddFromAssembly(typeof(MyDbContext).Assembly);

                base.OnModelCreating(modelBuilder);
            }

然而,在最新的EF Core中,您似乎必须单独添加每个映射: -

protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.ApplyConfiguration(new UserMap());
            modelBuilder.ApplyConfiguration(new AddressMap());

            base.OnModelCreating(modelBuilder);
        }

是否有类似添加实体地图的方式,因为这很乏味。

1 个答案:

答案 0 :(得分:0)

这与EF6的AddFromAssembly相同:

var configurations = typeof(MyDbContext).Assembly.GetTypes()
                .Where(t => t.BaseType != null && t.BaseType.IsGenericType && t.BaseType.GetGenericTypeDefinition() == typeof(System.Data.Entity.ModelConfiguration.EntityTypeConfiguration<>));

foreach (var config in configurations)
{
    dynamic instance = System.Activator.CreateInstance(config);
    modelBuilder.Configurations.Add(instance);
}