EF Core Mapping EntityTypeConfiguration

后端 未结 15 1262
花落未央
花落未央 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:54

    In Entity Framework Core 2.0:

    I took Cocowalla's answer and adapted it for v2.0:

        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)
            {
                // Types that do entity mapping
                var mappingTypes = assembly.GetMappingTypes(typeof(IEntityTypeConfiguration<>));
    
                // Get the generic Entity method of the ModelBuilder type
                var entityMethod = typeof(ModelBuilder).GetMethods()
                    .Single(x => x.Name == "Entity" &&
                            x.IsGenericMethod &&
                            x.ReturnType.Name == "EntityTypeBuilder`1");
    
                foreach (var mappingType in mappingTypes)
                {
                    // Get the type of entity to be mapped
                    var genericTypeArg = mappingType.GetInterfaces().Single().GenericTypeArguments.Single();
    
                    // Get the method builder.Entity
                    var genericEntityMethod = entityMethod.MakeGenericMethod(genericTypeArg);
    
                    // Invoke builder.Entity to get a builder for the entity to be mapped
                    var entityBuilder = genericEntityMethod.Invoke(modelBuilder, null);
    
                    // Create the mapping type and do the mapping
                    var mapper = Activator.CreateInstance(mappingType);
                    mapper.GetType().GetMethod("Configure").Invoke(mapper, new[] { entityBuilder });
                }
            }
    
    
        }
    

    And it's used in the DbContext like this:

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.AddEntityConfigurationsFromAssembly(GetType().Assembly);
        }
    

    And this is how you create an entity type configuration for an entity:

        public class UserUserRoleEntityTypeConfiguration : IEntityTypeConfiguration
        {
            public void Configure(EntityTypeBuilder builder)
            {
                builder.ToTable("UserUserRole");
                // compound PK
                builder.HasKey(p => new { p.UserId, p.UserRoleId });
            }
        }
    

提交回复
热议问题