EF Code First Cascade删除具有多个一对多关系的条目

时间:2016-02-17 19:05:56

标签: c# entity-framework code-first

我有以下表格:

public class Household
{
  [Key]
  public int Id { get; set; }

  // other stuff

  public virtual ICollection<Debt> Debts
    {
        get { return this.debts; }
        set { this.debts = value; }
    }
}

public class Expense
{
    [Key]
    public int Id { get; set; }

    //other stuff

    public virtual ICollection<Debt> Debts
    {
        get { return this.debts; }
        set { this.debts = value; }
    }
}
public class Debt
{
    [Key]
    public int Id { get; set; }

    //other stuff

    [Required]
    public int HouseholdId { get; set; }

    public virtual Household Household { get; set; }

    [Required]
    public int ExpenseId { get; set; }

    public virtual Expense Expense { get; set; }
}

正如我们所看到的,每一笔债务都属于特定的家庭和特定的费用,因此是两个一对多的关系(一个家庭 - 多个债务,一个费用 - 许多债务)。我目前正在尝试为这两种关系实现级联删除,这意味着如果我要删除一个Household或一个Expense,它的所有相关债务也将被删除。我正在尝试使用OnModelCreating()方法,但收效甚微。这就是我尝试过的:

    modelBuilder.Entity<Debt>()
.HasRequired(h => h.Expense)
.WithMany(b => b.Debts)
.HasForeignKey(h => h.ExpenseId)
.WillCascadeOnDelete(true);

    modelBuilder
.Entity<Debt>()
.HasRequired(h => h.Household)
.WithMany(b => b.Debts)
.HasForeignKey(h => h.HouseholdId)
.WillCascadeOnDelete(true);

如果我将两个WillCascadeDelete都设为TRUE,则会出现以下异常

 Introducing FOREIGN KEY constraint '' on table  
may cause cycles or multiple cascade paths. 
Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints

但是,如果其中一个WillCascadeDelete为FALSE(无关紧要),一切正常,除了已关闭CASCADE DELETE的关系。例如,如果我关闭Debt-&gt; Household one,我可以删除费用并且其债务会自动级联删除,但如果我尝试删除一个Household,我会收到外键异常。

有什么方法可以为两种关系启用CASCADE DELETE?提前谢谢。

0 个答案:

没有答案