使用Entity Framework (EF) 进行数据模型设计时,正确配置实体映射关系至关重要,这有助于精确控制数据库模式的生成和数据的持久化方式。EF Core2.0和EF6中,分别通过IEntityTypeConfiguration和EntityTypeConfiguration配置实体映射关系的代码。

1、EF6中通过EntityTypeConfiguration配置实体映射关系代码

public class AccountMap : EntityTypeConfiguration<Account>
{
    public AccountMap()
    {
        ToTable("Account");
        HasKey(a => a.Id);

        Property(a => a.Username).HasMaxLength(50);
        Property(a => a.Email).HasMaxLength(255);
        Property(a => a.Name).HasMaxLength(255);
    }
}

2、EF Core 2.0中配置实体映射关系代码

class CustomerConfiguration : IEntityTypeConfiguration<Customer>
{
  public void Configure(EntityTypeBuilder<Customer> builder)
  {
     builder.HasKey(c => c.AlternateKey);
     builder.Property(c => c.Name).HasMaxLength(200);
   }
}
public class BloggingContext : DbContext
{
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
     builder.ApplyConfiguration(new CustomerConfiguration());
    }
}

EF Core 2.0文档:https://docs.microsoft.com/en-us/ef/core/what-is-new/

推荐文档