多个级联路径实体框架

时间:2015-06-09 22:56:16

标签: entity-framework ef-code-first ef-migrations

我的代码优先实体框架模型如下:

在我的数据库中,我有customerspurchasesitems

  • customer可能有多个purchases
  • 每个purchase可能包含多个purchased_item
  • 每个purchased_item都会引用item

因此,在使用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也会被删除。

但是,当我尝试更新我的数据库时,我得到以下异常:

  

在表'PurchasedItem'上引入FOREIGN KEY约束'FK_dbo.PurchasedItem_dbo.Item_ItemId'可能会导致循环或多个级联路径。指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY约束   无法创建约束或索引。查看以前的错误。

1 个答案:

答案 0 :(得分:1)

您正在获得一个周期,因为Customer有许多Purchase和许多Item,并且每个实体都有PurchasedItem的级联路径。如果客户有多个PurchasedItem而不是Item - 那是什么意思? - 这也会创造一个循环。

级联方向:

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