如何设置实体框架以使用可选外键在删除时进行级联? [英] How do you set Entity Framework to cascade on delete with optional foreign key?

查看:49
本文介绍了如何设置实体框架以使用可选外键在删除时进行级联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将Entity Framework设置为使用可选的外键在删除时进行级联。我先使用代码,我的模型如下所示:

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?

推荐答案

在这里似乎要怪MSSQL。因为我的表是自引用的,所以不可能将delete的级联设置为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.

相反,我最后要做的是递归地手动标记每个孩子要删除,然后调用SaveChanges()并让EntityFramework整理其余部分。

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

这篇关于如何设置实体框架以使用可选外键在删除时进行级联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆