I'm using EF code first, I have following entities:
I'm using TPT
method for inheritance, to create one-to-one or zero relation, wrote following code:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Order>()
.HasOptional(x => x.ProductionInstruction)
.WithRequired(x => x.Order);
}
I write following code to save a ProductionInstruction
:
var pi = new ProductionInstruction();
/* set pi properties */
ctx.ProductionInstructions.Add(pi);
ctx.SaveChanges();
I get following error when ctx.SaveChanges()
run:
A dependent property in a ReferentialConstraint is mapped to a store-generated column. Column: 'Id'.
Is there any way to implement 1..0-1 between my two entities, without above error?
In Entity Framework, a one-to-one mapping with a required principal is implemented by giving the dependent a primary key that's also a foreign key to the principal. The dependent copies its primary key from the principal.
In your case, EF wants ProductionInstruction.Id
to be a foreign key to Order.Id
, and its value should be copied from the Order
it belongs to. However, because of the inheritance, ProductionInstruction.Id
is an identity column (store-generated), so it can't be set in code.
You either have to remove the inheritance, so ProductionInstruction.Id
can be mapped as not store-generated, or change the mapping to optional on both sides. The latter will give ProductionInstruction
a separate foreign key to Order
.