[英]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.