简体   繁体   English

如何在两端使用 FK 在 EF Core 中配置一对一关系

[英]How to configure one-to-one relationship in EF Core with FK on both ends

I have following entities:我有以下实体:

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
}

So each subscription might have only one billing contract and each billing contract belongs to a single subscription.因此,每个订阅可能只有一个计费合同,并且每个计费合同属于一个订阅。

I'm trying to configure this relationship in my dbcontext:我正在尝试在我的 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);

But from the generated migration(or from the snapshot or from the actual DB schema) I can tell that only FK in Subscription table is created.但是从生成的迁移(或从快照或从实际的数据库模式)我可以看出只有Subscription表中的 FK 被创建。 I cannot make EF to create a FK(and index) in the BillingContract table.我无法让 EF 在BillingContract表中创建 FK(和索引)。 I also tried to use annotation attributes with the same result.我还尝试使用具有相同结果的注释属性。

Did I miss something?我错过了什么? Or it's a bug in EF?或者它是EF中的一个错误?

I'm using EF Core 2.2我正在使用 EF Core 2.2

To eliminate a possibility of a corrupted db snapshot I created a brand new console project using EF Core 3.1.为了消除数据库快照损坏的可能性,我使用 EF Core 3.1 创建了一个全新的控制台项目。 After adding initial migration I have the same result with missing FK:添加初始迁移后,我得到与缺少 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");
}

This is not an EF bug.这不是 EF 错误。 Usually, two tables have an association relationship, and you only need to create one foreign key in one of the tables.通常,两张表是有关联关系的,只需要在其中一张表中创建一个外键即可。 The two-way foreign key is for the entity and does not exist in the database design.双向外键用于实体,在数据库设计中不存在。 This docuement has give the detail example.文档给出了详细的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM