C# 实体框架6自引用实体上的代码第一级级联删除

C# 实体框架6自引用实体上的代码第一级级联删除,c#,entity-framework,ef-code-first,C#,Entity Framework,Ef Code First,我有一个实体: public class Section : SortableEntity { private ICollection<Section> _sections; public ICollection<Section> Sections { get { return _sections ?? (_sections = new HashSet<Section>());

我有一个实体:

public class Section : SortableEntity
{
    private ICollection<Section> _sections;

    public ICollection<Section> Sections
    {
        get
        {
            return _sections ?? (_sections = new HashSet<Section>());
        }

        set
        {
            _sections = value;
        }
    }

    public string Title { get; set; }

    public string Description { get; set; }

    public Section ParentSection { get; set; }

    public int? ParentSectionId { get; set; }
}
公共类部分:可排序实体
{
私人ICollection\u部门;
公共收集组
{
得到
{
返回_sections??(_sections=newhashset());
}
设置
{
_截面=值;
}
}
公共字符串标题{get;set;}
公共字符串说明{get;set;}
公共部分ParentSection{get;set;}
public int?ParentSectionId{get;set;}
}
在创建模型时,我有一个配置:

modelBuilder.Entity<Section>().HasOptional(x => x.ParentSection).WithMany(p => p.Sections).HasForeignKey(d => d.ParentSectionId);
modelBuilder.Entity().HasOptional(x=>x.ParentSection).WithMany(p=>p.Sections).HasForeignKey(d=>d.ParentSectionId);
我试图进行级联删除,但出现以下错误: DELETE语句与相同的表引用约束“FK_dbo.Section_dbo.Section_ParentSectionId”冲突


如何在自引用实体上配置级联删除?

如果你在谷歌上搜索你的问题,你会看到无数其他人也有同样的问题,原因是SQL Server无法处理自引用实体上的级联删除,而我在实体框架中找不到只通过设置某些属性即可解决此问题的解决方案我知道的唯一一种方法是,首先使用代码在自引用实体上模拟级联删除,即编写一个递归方法,在收集主键、外键和递归级别信息时遍历子级。一旦建立了此列表,在每次迭代中按递归级别降序遍历它获取该级别递归的所有记录,循环遍历该集合,然后一次删除一条记录。我使用一个存储过程完成了此操作,该存储过程使用递归公共表表达式返回此列表。我希望这会有所帮助。

我认为您不能在实体框架中完成此操作,因为您不能在SQL Server中对自引用表使用级联删除但我可能错了。