EF Core通过抽象基类的流畅映射实现逐表类型 [英] EF Core implementing Table-Per-Concrete-Type with fluent mapping of abstract base class

查看:162
本文介绍了EF Core通过抽象基类的流畅映射实现逐表类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有两个从抽象基类派生的实体,并且想要实现Table-Per-Concrete-Type。像这样的实体:

Suppose that you have two entities derived from an abstract base class and you want implement Table-Per-Concrete-Type. Entities like below:

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类仅对所有实体映射一次。如何更改下面的代码:

And you don’t want to use attribute in the abstract base class(EntityBase), you want to map EntityBase class in dbcontext only once for all entities. How to change the code below :

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

}


推荐答案

此处是对您问题的答案。

您需要为BaseClass编写配置:

You need to write Configurations for your 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继承的foreach表:

After that, you can write your concrete Configuration-Class foreach Table which inherits from EntityBase like so:

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 :

To invoke your configuration in your dbContext you can call ApplyConfiguration:

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

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

这篇关于EF Core通过抽象基类的流畅映射实现逐表类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆