ReferentialConstraint 中的从属 属性 映射到存储生成的列。 TPT 继承中的第 'Id' 列

A dependent property in a ReferentialConstraint is mapped to a store-generated column. Column 'Id' in TPT inheritance

我首先使用 EF 代码,我有以下实体:

我正在使用 TPT 方法进行继承,以创建一对一或零关系,编写了以下代码:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Order>()
                .HasOptional(x => x.ProductionInstruction)
                .WithRequired(x => x.Order);
}

我写了下面的代码来保存一个ProductionInstruction:

var pi = new ProductionInstruction();
/* set pi properties */
ctx.ProductionInstructions.Add(pi);
ctx.SaveChanges();

ctx.SaveChanges() 运行:

时出现以下错误

A dependent property in a ReferentialConstraint is mapped to a store-generated column. Column: 'Id'.

有什么方法可以在我的两个实体之间实现 1..0-1 而不会出现上述错误?

在 Entity Framework 中,与所需主体的一对一映射是通过为依赖项提供一个主键来实现的,该主键也是主体的外键。依赖者从主体复制其主键。

在你的例子中,EF 希望 ProductionInstruction.Id 成为 Order.Id 的外键,它的值应该从它所属的 Order 中复制。但是,由于继承关系,ProductionInstruction.Id是一个标识列(store-generated),所以不能在代码中设置。

您要么必须删除继承,以便 ProductionInstruction.Id 可以映射为不是存储生成的,要么将映射更改为可选的。后者会给 ProductionInstruction 一个单独的外键给 Order.