I\'m migrating a Entity Framework 6.1.3 Code First library to Entity Framework Core with C# and .NET Framework 4.7.
I\'ve been searching about Entity Framework Core
The EF6 setup is creating a so called One-To-One Shared Primary Key Association where the PK of the dependent entity is also a FK to principal entity.
The things have changed in EF Core. It supports naturally both shared PK and FK one-to-one associations. Also optional/required are not used to determine the principal and dependent ends of the association. IsRequired
is used to control if the dependent entity can exists w/o principal and applies only whith separate FK. While HasForeignKey
and HasPrincipalKey
are used to determine the principal and dependent ends of the association and also map the dependent FK and principal PK / Alternate Key.
With that being said, the equivalent EFC configuration is as follows:
builder.HasOne(ag_ch => ag_ch.Code)
.WithOne(c => c.AggregationChild)
.HasForeignKey<AggregationChildren>(ag_ch => ag_ch.AggregationChildrenId)
.OnDelete(DeleteBehavior.Restrict);
So we start with defining the relationship using HasOne
+ WithOne
.
Then HasForeignKey<AggregationChildren>(ag_ch => ag_ch.AggregationChildrenId)
to tell EF that (1) AggregationChildren
is the dependent end of the relationship, and (2) that the PK AggregationChildrenId
should also be used as FK.
Finally, OnDelete(DeleteBehavior.Restrict)
is the EFC equivalent of the EF6 WillCascadeOnDelete(false)
. The other options like ClientSetNull
and SetNull
apply only when the dependent has a separate optional FK, which is not the case with shared PK association.
Reference: Relationships