创建数据库时 EF Core 关系抛出错误

EF Core relationship throwing error when creating the database

我有一个 Address class,我在 Customer class 和 Order class 中使用:

public class Address
{
    public Customer Customer { get; set }
    ...
}

public class Customer
{
    ...
    public List<Address> Addresses { get; set;}
}

public class Order
{
    ...
    public Customer Curstomer { get; set; }
    public Address BillingAddress { get; set;}
    public Address ShippingAddress { get; set;}
}

我成功创建了迁移,但是当我尝试 update-database 时,出现以下错误:

Introducing FOREIGN KEY constraint 'FK_Order_Address_ShippingAddressId' on table 'Order' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could not create constraint or index. See previous errors.

建立这种关系的正确方法是什么?这个建模是否正确?因为我觉得 Address 是与 Customer 相关的 属性,但我也在 Order 上使用它,但复制了 [=18] 中的地址=] table 好像也不对。

要解决此问题,请将迁移中外键 onDeleteReferentialAction 更改为 Cascade 以外的内容。 Restrict 可能是一个不错的选择。它看起来像这样:

constraints: table =>
            {
                table.PrimaryKey("PK_Order", x => x.Id);
                table.ForeignKey(
                    name: "FK_Orders_BillingAddress_BillingAddressId",
                    column: x => x.BillingAddressId,
                    principalTable: "Addresses",
                    principalColumn: "Id",
                    onDelete: ReferentialAction.Cascade);
            }

只需将其更改为 Restrict 或其他选择即可。

为什么?

如果您有 Cascade,假设您要删除 OrderBillingAddress。这将尝试将删除级联到 Order,然后将 its 删除级联到 ShippingAddress,然后将尝试级联 that 删除回订单等等,因此 SQL 服务器在循环级联删除时正确出错。

另见这个问题:Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths - why?