EF Core - Entity Mapping Configuration

c# entity-framework entity-framework-core

Question

In previous versions of EF, you could configure all of your entity maps on the DbContext like this :-

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

                base.OnModelCreating(modelBuilder);
            }

However in the latest EF Core it seems you have to add each mapping individually like this :-

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

            base.OnModelCreating(modelBuilder);
        }

Is there no similar way of add Entity Maps, as this is tedious.

1
0
3/1/2018 9:51:59 AM

Accepted Answer

This do the same of the AddFromAssembly of EF6:

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);
}
0
3/1/2018 11:11:11 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow