0
votes

I have entity class:

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; }
}

and 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);
    }
}

how use WillCascadeOnDelete in model?

The exception message is the following one:

Introducing FOREIGN KEY constraint 'FK_dbo.Menus_dbo.Menus_ParentID' on table 'Menus' 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. See previous errors.

1

1 Answers

0
votes

You can not use cascading on self-related entities. It's just not possible.

UPDATE:

See why not:

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

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

and yep, you are in a cycle.