使用WillCascadeOnDelete

时间:2014-05-21 10:08:08

标签: c# asp.net-mvc entity-framework code-first

我有实体类:

public class Menu
{
    public int ID { get; set; }
    public string Title { get; set; }
    [ForeignKey("UserID")]
    public virtual User User { get; set; }
    public virtual int UserID { get; set; }
    public virtual int? ParentID { get; set; }
    public virtual Menu Parent { get; set; }

    public virtual ICollection<Menu> Children { get; set; }
}

和confige class:

public class MenuConfig : EntityTypeConfiguration<Menu>
{
    public MenuConfig()
    {
        HasOptional(x => x.Parent).WithMany(x =>x.Children)
            .HasForeignKey(x=>x.ParentID).WillCascadeOnDelete();
        Property(x => x.Title).HasMaxLength(200);
    }
}

如何在模型中使用WillCascadeOnDelete?

异常消息如下:

  

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

1 个答案:

答案 0 :(得分:0)

您无法在自相关实体上使用级联。这是不可能的。

<强>更新

了解原因:

obj1.Children = obj2, obj3
obj2.Children = obj4, obj5
obj5.Children = obj1, someOtherObjs

deleting obj1 -----------<-----------
    should delete obj2              |
        should delete obj5          |
            should delete obj1 -->---

,是的,你处于一个循环中。