EF Core实现了Table-Per-Concrete-Type,具有抽象基类的流畅映射

时间:2016-04-01 10:35:10

标签: c# entity-framework-core

假设您有两个派生自抽象基类的实体,并且您希望实现Table-Per-Concrete-Type。实体如下:

public abstract class EntityBase
{
   public int Id { get; set; }

   public string CreatedBy { get; set; }

   public DateTime CreatedAt { get; set; }
}

public class Person : EntityBase
{
   public string Name { get; set; }
}
public class PersonStatus : EntityBase
{
   public string Title { get; set; }
}

并且您不希望在抽象基类(EntityBase)中使用属性,您希望仅在所有实体的dbcontext 中映射EntityBase类。如何更改以下代码:

public class PeopleDbContext : DbContext
{
   public DbSet<Person> People { get; set; }

   protected override void OnModelCreating(ModelBuilder modelBuilder)
   {
      base.OnModelCreating(modelBuilder);

      // Entity base class mapping(only once)

      modelBuilder.Entity<Person>(e =>
      {
        e.Property(x => x.Name)
            .IsRequired()
            .HasMaxLength(100);
      });
      modelBuilder.Entity<PersonStatus>(e =>
      {
        e.Property(x => x.Title)
            .IsRequired()
            .HasMaxLength(100);
      });
  }

}

1 个答案:

答案 0 :(得分:2)

Here是您问题的答案。

您需要为BaseClass编写配置:

public class EntityBaseConfiguration<TBase> : IEntityTypeConfiguration<TBase>
    where TBase : EntityBase
{
    public virtual void Configure(EntityTypeBuilder<TBase> builder)
    {
        builder.HasKey(b => b.Id);
        builder.Property(b => b.CreatedBy)
            .HasColumnType("varchar(50)");
        builder.Property(b => b.CreatedAt)
            .HasColumnType("datetime2");
    }
}

之后,您可以编写具体的Configuration-Class foreach Table,它继承自EntityBase,如下所示:

public class PersonConfig : BaseConfig<Person>
{
    public override void Configure(EntityTypeBuilder<Person> builder)
    {
        base.Configure(builder);
        builder.Property(e => e.Name)
            .HasColumnType("varchar(100)")
            .IsRequired();
    }
}

要在dbContext中调用配置,可以调用ApplyConfiguration:

public class PeopleDbContext : DbContext
{
    public DbSet<Person> People { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.ApplyConfiguration(new PersonConfig());
    }
}