Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you set Entity Framework to cascade on delete with optional foreign key?

I'm attempting to set Entity Framework to cascade on delete with an optional foreign key. I'm using code first, and my model looks like this:

public class Node
{
    [Key]
    public int ID { get; set; }

    [ForeignKey("Parent")]
    public int? ParentID { get; set; }
    public virtual Node Parent { get; set; }
}

I've seen plenty of solutions that suggest, "Just make the foreign key required," but this will not work for me because the parent node may be null.

Does a solution exist that doesn't involve manually deleting child nodes before parent nodes?

like image 596
Charles W Avatar asked Apr 02 '14 15:04

Charles W


People also ask

How do I enable cascade delete in Entity Framework?

Cascade delete is enabled by default in Entity Framework for all types of relationships such as one-to-one, one-to-many and many-to-many.

How does foreign key on delete cascade work?

A foreign key with cascade delete means that if a record in the parent table is deleted, then the corresponding records in the child table will automatically be deleted. This is called a cascade delete in SQL Server.


1 Answers

Is this what you are looking for?

Entity Framework (EF) Code First Cascade Delete for One-to-Zero-or-One relationship

From the above, it would be something like (but I have not tried it):

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{

    modelBuilder.Entity<Node>()
        .HasOptional(a => a.Parent)
        .WithOptionalDependent()
        .WillCascadeOnDelete(true);
}
like image 162
user25398 Avatar answered Oct 21 '22 22:10

user25398