我在代码优先项目(EF5)中使用了"每个类型的表"层次结构.我的派生类覆盖默认的主键名称,从数据库的角度清楚地标识这种关系,如下所示:
/* change primary keys to Chair.ProductId and Table.ProductId */
modelBuilder.Entity<Chair>()
    .Property(x => x.Id)
    .HasColumnName("ProductId");
modelBuilder.Entity<Table>()
    .Property(x => x.Id)
    .HasColumnName("ProductId");
Run Code Online (Sandbox Code Playgroud)
使用以下类作为示例:
[Table("Product")]
public class Product
{
   public int Id {get; set;}
   /* generic product properties */
}
[Table("Chair")]
public class Chair : Product
{
     /* specific chair properties */
}
[Table("Table")]
public class Table : Product
{
     public virtual ICollection<Chair> Chairs {get; set;}
     /* specific table properties */
}
Run Code Online (Sandbox Code Playgroud)
这导致属性Table.Chairs上的以下错误:在MetaDataWorkspace中不存在指定为此MSL的一部分的列'Id'.
我有点理解,因为EF可能没有看到主席产品的PK被改变了......(并且仍假设它被称为'Id')但我无法弄清楚我如何指示EF使用备用密钥.
谢谢,
PS.是的,我知道,如果我不更改PK的名称,它可以工作......但可以使用EF Fluent API完成吗?