EF Core Mapping EntityTypeConfiguration

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

    This is what I am doing in a project I'm currently working on.

    public interface IEntityMappingConfiguration where T : class
    {
        void Map(EntityTypeBuilder builder);
    }
    
    public static class EntityMappingExtensions
    {
         public static ModelBuilder RegisterEntityMapping(this ModelBuilder builder) 
            where TMapping : IEntityMappingConfiguration 
            where TEntity : class
        {
            var mapper = (IEntityMappingConfiguration)Activator.CreateInstance(typeof (TMapping));
            mapper.Map(builder.Entity());
            return builder;
        }
    }
    

    Usage:

    In your Context's OnModelCreating method:

        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
    
            builder
                .RegisterEntityMapping()
                .RegisterEntityMapping();
        }
    

    Example mapping class:

    public class UserMapping : IEntityMappingConfiguration
    {
        public void Map(EntityTypeBuilder builder)
        {
            builder.ToTable("User");
            builder.HasKey(m => m.Id);
            builder.Property(m => m.Id).HasColumnName("UserId");
            builder.Property(m => m.FirstName).IsRequired().HasMaxLength(64);
            builder.Property(m => m.LastName).IsRequired().HasMaxLength(64);
            builder.Property(m => m.DateOfBirth);
            builder.Property(m => m.MobileNumber).IsRequired(false);
        }
    }
    

    One other thing I like to do to take advantage of the folding behavior of Visual Studio 2015 is for an Entity called 'User', you name your mapping file 'User.Mapping.cs', Visual Studio will fold the file in the solution explorer so that it is contained under the entity class file.

提交回复
热议问题