EFCore实现了Table-Per-Concrete-Type,具有抽象基类的流畅映射假设您有两个派生自抽象基类的实体,并且您希望实现Table-Per-Concrete-Typ EF Core实现了Table-Per-Concrete-Type,具有抽象基类的流畅映射
假设您有两个派生自抽象基类的实体,并且您希望实现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 People { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); // Entity base class mapping(only once) modelBuilder.Entity(e => { e.Property(x => x.Name) .IsRequired() .HasMaxLength(100); }); modelBuilder.Entity(e => { e.Property(x => x.Title) .IsRequired() .HasMaxLength(100); }); } }
这是你的问题的答案..
您需要为BaseClass编写配置:
public class EntityBaseConfiguration : IEntityTypeConfiguration where TBase : EntityBase { public virtual void Configure(EntityTypeBuilder 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,它inheritance自EntityBase,如下所示:
public class PersonConfig : BaseConfig { public override void Configure(EntityTypeBuilder builder) { base.Configure(builder); builder.Property(e => e.Name) .HasColumnType("varchar(100)") .IsRequired(); } }要在dbContext中调用配置,可以调用ApplyConfiguration:
上述就是C#学习教程:EF Core实现了Table-Per-Concrete-Type,具有抽象基类的流畅映射分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注编程笔记
public class PeopleDbContext : DbContext { public DbSet People { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.ApplyConfiguration(new PersonConfig()); } }