实体框架6自引用实体上的代码优先级联删除

时间:2014-03-27 07:55:31

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

        set
        {
            _sections = value;
        }
    }

    public string Title { get; set; }

    public string Description { get; set; }

    public Section ParentSection { get; set; }

    public int? ParentSectionId { get; set; }
}

在模型创建方面,我有一个配置:

modelBuilder.Entity<Section>().HasOptional(x => x.ParentSection).WithMany(p => p.Sections).HasForeignKey(d => d.ParentSectionId);

我试图进行级联删除,但是我收到了以下错误: &#34; DELETE语句与SAME TABLE REFERENCE约束冲突&#34; FK_dbo.Section_dbo.Section_ParentSectionId&#34;。

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

1 个答案:

答案 0 :(得分:5)

如果你谷歌你的问题你会看到很多其他人有同样的问题,原因是因为SQL Server无法处理自引用实体的级联删除,我发现在实体框架中没有解决方案通过设置一些属性。我知道使用代码首先在自引用实体上模拟级联删除的唯一方法是编写一个递归方法,在收集主键,外键和递归信息级别时迭代子进程。构建此列表后,按递归级别按降序顺序遍历它,在每次迭代中,您将获得该递归级别的所有记录,循环访问该集合并一次删除一个。我使用存储过程执行此操作,该存储过程使用递归公用表表达式返回此列表。我希望这会有所帮助。