In EF6 we usually able to use this way to configure the Entity.
public class AccountMap : EntityTypeConfiguration
{
public AccountMap()
I ended with this solution:
public interface IEntityMappingConfiguration
{
void Map(ModelBuilder b);
}
public interface IEntityMappingConfiguration : IEntityMappingConfiguration where T : class
{
void Map(EntityTypeBuilder builder);
}
public abstract class EntityMappingConfiguration : IEntityMappingConfiguration where T : class
{
public abstract void Map(EntityTypeBuilder b);
public void Map(ModelBuilder b)
{
Map(b.Entity());
}
}
public static class ModelBuilderExtenions
{
private static IEnumerable GetMappingTypes(this Assembly assembly, Type mappingInterface)
{
return assembly.GetTypes().Where(x => !x.IsAbstract && x.GetInterfaces().Any(y => y.GetTypeInfo().IsGenericType && y.GetGenericTypeDefinition() == mappingInterface));
}
public static void AddEntityConfigurationsFromAssembly(this ModelBuilder modelBuilder, Assembly assembly)
{
var mappingTypes = assembly.GetMappingTypes(typeof (IEntityMappingConfiguration<>));
foreach (var config in mappingTypes.Select(Activator.CreateInstance).Cast())
{
config.Map(modelBuilder);
}
}
}
Sample Use:
public abstract class PersonConfiguration : EntityMappingConfiguration
{
public override void Map(EntityTypeBuilder b)
{
b.ToTable("Person", "HumanResources")
.HasKey(p => p.PersonID);
b.Property(p => p.FirstName).HasMaxLength(50).IsRequired();
b.Property(p => p.MiddleName).HasMaxLength(50);
b.Property(p => p.LastName).HasMaxLength(50).IsRequired();
}
}
and
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.AddEntityConfigurationsFromAssembly(GetType().Assembly);
}