I have a main entity class PurchasePlanEntity
and a detail entity class PurchasePlanDetailEntity
, which have a one-to-many relationship. I explicitly defined the foreign key in the DbContext class, but after using migrations, two shadow foreign keys PurchasePlanEntityOrgId
and PurchasePlanEntityPurcPlanId
were still generated in the table. Additionally, two foreign key constraints FK_purchasePlanDetailEntity_purchasePlan_PurchasePlanEntityPurcPlanId_PurchasePlanEntityOrgId
and FK_purchasePlanDetailEntity_purchasePlan_purcPlanId_orgId
were created. Why is this happening even though I have explicitly configured the foreign keys?
// main entity class.
[Table("purchasePlan")]
public class PurchasePlanEntity
{
[Column("purcPlanId")]
public string? PurcPlanId { get; set; }
[Column("orgId")]
public string? OrgId { get; set; }
public List<PurchasePlanDetailEntity> DetailList { get; } = new();
}
// detail entity class.
[Table("purchasePlanDetailEntity")]
public class PurchasePlanDetailEntity
{
[Column("purcPlanDetlId")]
public string? PurcPlanDetlId { get; set; }
#region foreign-key
[Column("purcPlanId")]
public string? PurcPlanId { get; set; }
[Column("orgId")]
public string? OrgId { get; set; }
#endregion
public PurchasePlanEntity PurchasePlanEntity { get; set; } = null!;
}
// explicit foreign key configuration.
modelBuilder.Entity<PurchasePlanEntity>()
.HasMany<PurchasePlanDetailEntity>()
.WithOne()
.HasForeignKey(e => new { e.PurcPlanId, e.OrgId });
// explicit primary key configuration.
modelBuilder.Entity<PurchasePlanDetailEntity>()
.HasKey(e => new { e.PurcPlanId, e.OrgId, e.PurcPlanDetlId });
I was expecting EF Core to use the foreign keys I explicitly defined to describe the one-to-many relationship between them. Even after consulting the official documentation, I still haven’t been able to understand why this is happening. It confuses me a lot. Thanks in advance.