多个级联路径 Entity Framework

Multiple cascade paths Entity Framework

我的代码优先Entity Framework模型如下:

在我的数据库中,我有 customerspurchasesitems

因此,在使用 FluentAPI 配置我的实体时,我有以下配置:

public class PurchaseConfiguration : EntityTypeConfiguration<Purchase>
{
    public PurchaseConfiguration (string schema = "dbo")
    {
        ToTable(schema + ".Purchase");
        HasKey(p => p.PurchaseId);
        Property(p => p.Name);

        HasMany(p => p.PurchasedItems) //This is an ICollection of PurchaseItem in the Purchase class
            .WithRequired(pi => pi.Purchase)
            .HasForeignKey(pi => pi.PurchaseId)
            .WillCascadeOnDelete(true);
    }
}

public class ItemConfiguration : EntityTypeConfiguration<Item>
{
    public ItemConfiguration (string schema = "dbo")
    {
        ToTable(schema + ".Item");
        HasKey(i => i.ItemId);
        Property(i => i.Name);

        HasMany(i => i.PurchasedItems)
            .WithRequired(pi => pi.Item)
            .HasForeignKey(pi => pi.ItemId)
            .WillCascadeOnDelete(true);
    }
}

public class PurchasedItemConfiguration : EntityTypeConfiguration<PurchasedItem>
{
    public PurchasedItemConfiguration (string schema = "dbo")
    {
        ToTable(schema + ".PurchasedItem");
        HasKey(rp => rp.PurchasedItemId);
    }
}

我希望它的行为方式是,当您在数据库上删除 purchased item 时,与 purchaseitem 相关的信息不会丢失。但是,如果从数据库中删除 itempurchase,则 purchaseditem 也会被删除。

但是,当我尝试更新数据库时出现以下异常:

Introducing FOREIGN KEY constraint 'FK_dbo.PurchasedItem_dbo.Item_ItemId' on table 'PurchasedItem' 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.

你得到一个循环是因为 Customer 有许多 Purchase 和许多 Item,并且每个实体都有到 PurchasedItem 的级联路径。如果客户有很多 PurchasedItem 而不是 Item - 你是这个意思吗? -- 这也会产生一个循环。

级联方向:

          +----------+      
          | Customer |      
          +--+----+--+      
             |    |         
             |    |         
+--------+   |    |   +----+
|Purchase| <-+    +-> |Item|
+----+---+            +--+-+
     |                   |  
     |                   |  
     |  +-------------+  |  
     +> |PurchasedItem| <+  
        +-------------+