我有两个DbContext。 BaseDbContext
和从BaseDbContext
继承而来的FemaleDbContext
。
public class BaseDbContext : DbContext
{
public BaseDbContext(DbContextOptions options) : base(options) { }
public virtual DbSet<Person> Person { get; set; }
public virtual DbSet<House> House { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Person>().ToTable("Person", "dbo");
modelBuilder.Entity<House>().ToTable("House", "dbo");
modelBuilder.Entity<Person>().HasOne(e => e.House).WithMany(e => e.Persons);
modelBuilder.Entity<House>().HasMany(e => e.Persons).WithOne(e => e.House);
}
}
目标是为Person
实体扩展另一个属性。我不想使用阴影属性,因为它太动态了。因此,我正在尝试使用TPH使其工作。这是我的其他情况:
public class FemaleDbContext : BaseDbContext
{
public DbSet<Female> Female { get; set; }
public FemaleDbContext(DbContextOptions<FemaleDbContext> options) : base(options) { }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Female>().HasBaseType<Person>();
base.OnModelCreating(modelBuilder);
}
}
如您所见,我的子上下文应使用Female
实体而不是Person
。问题是,当我在SubDbContext上运行this.Context.Female.ToList()
时,仅返回数据库内Female
字段内值为Discriminator
的实体。返回该表中值为Person
的实体。但是我想得到每个实体。
另外,这是我的实体:
public class Person
{
public int Id { get; set; }
public string Firstname { get; set; }
public string Middlename { get; set; }
public string Lastname { get; set; }
}
public class Female : Person
{
public bool? IsPregnant { get; set; }
}
如何配置DbContext,使this.Context.Female.ToList()
返回Females
和Persons
。请注意,this.Context.Person.ToList()
已经返回了所有内容,不仅返回了Persons