简体   繁体   中英

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?

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

It looks as though MSSQL is to blame here. Because my table is self-referencing, It is impossible to set cascade on delete to true.

Instead, what I ended up doing was manually marking each child for deletion recursively, then calling SaveChanges() and letting EntityFramework sort out the rest.

Here is a simple code sample to illustrate:

void Delete(bool recursive = false)
{
    if(recursive)
        RecursiveDelete();

    if(this.Parent != null)
        this.Parent.Children.Remove(this);

    using(var db = new MyContext())
    {
        db.SaveChanges();
    }
}
void RecursiveDelete()
{
    foreach(var child in Children.ToArray())
    {
        child.RecursiveDelete();
        Children.Remove(child);
    }

    using(var db = new MyContext())
    {
        db.Nodes.Attach(this);
        db.Entry(this).State = EntityState.Deleted();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM