如何在EF Core中配置一对一关系,两端都有FK



我有以下实体:

public class Subscription
{
public int Id { get; set; }
public int? BillingContractId { get; set; }
public BillingContract BillingContract { get; set; }
//other properties
}
public class BillingContract 
{
public int Id { get; set; }
public int SubscriptionId { get; set; }
public Subscription Subscription { get; set; }
//other properties
}

所以每个订阅可能只有一个计费合同,每个计费合同属于一个订阅。

我试图在我的dbcontext中配置这个关系:

builder.Entity<Subscription>()
.HasOne(subscription => subscription.BillingContract)
.WithOne(billingContract => billingContract.Subscription)
.HasForeignKey<BillingContract>(billingContract => billingContract.SubscriptionId)
.IsRequired(true);
builder.Entity<BillingContract>()
.HasOne(billingContract => billingContract.Subscription)
.WithOne(subscription => subscription.BillingContract)
.HasForeignKey<Subscription>(subscription => subscription.BillingContractId)
.IsRequired(false);

但是,从生成的迁移(或从快照或从实际的DB模式)中,我可以看出,只创建了Subscription表中的FK。我不能让EF在BillingContract表中创建一个FK(和索引)。我还尝试使用注释属性,结果相同。

我错过什么了吗?或者这是EF的一个bug ?

我使用的是EF Core 2.2

为了消除损坏db快照的可能性,我使用EF Core 3.1创建了一个全新的控制台项目。在添加初始迁移之后,我得到了与缺少FK相同的结果:

protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "BillingContracts",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
SubscriptionId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_BillingContracts", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Subscriptions",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
BillingContractId = table.Column<int>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Subscriptions", x => x.Id);
table.ForeignKey(
name: "FK_Subscriptions_BillingContracts_BillingContractId",
column: x => x.BillingContractId,
principalTable: "BillingContracts",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_Subscriptions_BillingContractId",
table: "Subscriptions",
column: "BillingContractId",
unique: true,
filter: "[BillingContractId] IS NOT NULL");
}

这不是EF错误。通常,两个表具有关联关系,您只需要在其中一个表中创建一个外键。双向外键是针对实体的,在数据库设计中不存在。本文档给出了详细的示例。

最新更新