简体   繁体   English

如何使用可选外键将实体框架设置为删除级联?

[英]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. 我正在尝试将Entity Framework设置为使用可选的外键在delete上级联。 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 实体框架(EF)代码优先级联删除一对一或零关系

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. 看起来MSSQL应该归咎于此。 Because my table is self-referencing, It is impossible to set cascade on delete to true. 因为我的表是自引用的,所以不可能将delete上的级联设置为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. 相反,我最终做的是递归地手动标记每个子项以进行删除,然后调用SaveChanges()并让EntityFramework对其余部分进行排序。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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