【问题标题】:EF Core implementing Table-Per-Concrete-Type with fluent mapping of abstract base classEF Core 使用抽象基类的流畅映射实现 Table-Per-Concrete-Type
【发布时间】:2016-04-01 10:35:09
【问题描述】:

假设您有两个从抽象基类派生的实体,并且您希望实现 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);
      });
  }

}

【问题讨论】:

  • 你有什么尝试吗?我有这样的设置,并且 Id 是按约定提取的。
  • 是的,当我尝试在 dbcontext 中映射(流利)EntityBase 类时,ef 为 EntityBase 类创建了另一个表。在此之前,我使用流利的 nhibernate 实现,并且使用 ClassMap 可以正常工作。另外,我使用了 ef 6 “builder.Types(..)”。它按我的意愿工作。但是使用 ef core 我做不到。

标签: c# entity-framework-core


【解决方案1】:

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");
    }
}

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

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());
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-04
    • 2019-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多