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

杀马特。学长 韩版系。学妹 提交于 2020-01-03 12:24:30

问题


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?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/22815693/how-do-you-set-entity-framework-to-cascade-on-delete-with-optional-foreign-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!