EF Core Mapping EntityTypeConfiguration

后端 未结 15 1265
花落未央
花落未央 2020-11-30 18:26

In EF6 we usually able to use this way to configure the Entity.

public class AccountMap : EntityTypeConfiguration
{
    public AccountMap()
           


        
15条回答
  •  甜味超标
    2020-11-30 18:53

    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);
    }
    

提交回复
热议问题