EF Core Mapping EntityTypeConfiguration

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

    I followed a similar approach to the way Microsoft implemented ForSqlServerToTable

    using extension method...

    the partial flag is required if you want to use the same class name in multiple files

    public class ConsignorUser
    {
        public int ConsignorId { get; set; }
    
        public string UserId { get; set; }
    
        public virtual Consignor Consignor { get; set; }
        public virtual User User { get; set; }
    
    }
    
    public static partial class Entity_FluentMappings
    {
        public static EntityTypeBuilder AddFluentMapping (
            this EntityTypeBuilder entityTypeBuilder) 
            where TEntity : ConsignorUser
        {
           entityTypeBuilder.HasKey(x => new { x.ConsignorId, x.UserId });
           return entityTypeBuilder;
        }      
    }
    

    Then in the DataContext OnModelCreating make your call for each extension...

     public class DataContext : IdentityDbContext
    {
    
        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
            // Customize the ASP.NET Identity model and override the defaults if needed.
            // For example, you can rename the ASP.NET Identity table names and more.
            // Add your customizations after calling base.OnModelCreating(builder);
    
            builder.Entity().AddFluentMapping();
            builder.Entity().AddFluentMapping();           
    
        }
    

    This way we are following the same pattern used by the other builder methods.

    What do you thing?

提交回复
热议问题