[英]EF Core implementing Table-Per-Concrete-Type with fluent mapping of abstract base class
假设您有两个派生自抽象基类的实体,并且您希望实现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);
});
}
}
这是你的问题的答案..
您需要为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());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.