TPC 映射:MapInheritedProperties() 强制键继承

TPC mapping: MapInheritedProperties() force key inheritance

问题是 child 的 PK 是 parent 的密钥,尽管我们已经修改(Table 每个 Class 使用的映射)。

public class Entity
{
    [Key]
    public Guid EntityId { get; set; }    
}

public class VersionedEntity: Entity
{
    public Guid VersionId { get; set; }    
}

OnModelCreating 包含:

modelBuilder.Entity<VersionedEntity>().Map(m =>
{
   m.MapInheritedProperties();
});
modelBuilder.Entity<VersionedEntity>().HasKey(e => new { e.EntityId , e.HistoryId});

因此,我们将获得仍然包含 one-column PK (EntityId) 的 VersionedEntity。

m.MapInheritedProperties() replace/remove "inhereted" parent 键映射后我们有可能吗?

不,你没有。原因是 EF 对整个继承树有一个实体键定义。在我看来,它甚至应该为第二个 HasKey 语句抛出错误,而不是默默地忽略它。

具有一个实体键定义的原因是您可能(但可能不会)通过一个 DbSet<Entity> 公开所有实体。如果是这样,应该可以做到...

context.Entities.Find(Guid.Parse(someGuid));

如果一个子类型具有不同类型的键,这是不可能的。

如果您需要继续使用此模型,最好让 EF 忽略基 class 并分别映射每个类型,而不是映射继承。在这种情况下使用 base EntityTypeConfiguration 可能会有所帮助。