实体框架6代码优先级联自我引用实体删除 [英] Entity Framework 6 Code-First cascade delete on self referencing entity

查看:171
本文介绍了实体框架6代码优先级联自我引用实体删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实体:

  public class Section:SortableEntity 
{
private ICollection& ; _sections;

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

set
{
_sections = value;
}
}

public string标题{get;组; }

public string描述{get;组; }

public Section ParentSection {get;组; }

public int? ParentSectionId {get;组; }
}



在模型创建时我有一个配置:



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

我试图进行级联删除,我得到以下错误:
DELETE语句与SAME TABLE REFERENCE约束FK_dbo.Section_dbo.Section_ParentSectionId冲突。



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

解决方案

如果你的Google你的问题,你会看到一个gazillion其他人有同样的问题,原因是因为SQL Server无法处理级联删除自我引用的实体,我没有发现在实体框架中的解决方案,它只是通过设置一些属性。我知道模拟自我引用实体使用代码的级联删除的唯一方法是编写一个递归方法迭代当你收集主键,外键和递归信息级别时,一旦这个列表构建完成,循环通过它按递归级别降序排序,在每次迭代中,您将获得该递归级别的所有记录,循环收集并一次删除一个。我使用一个存储过程,使用递归公共表表达式返回此列表。我希望这有助于。


I have an entity:

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

And on model creating I have a configuration:

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

I'm trying to make a cascade delete and I'm getting a following error: "The DELETE statement conflicted with the SAME TABLE REFERENCE constraint "FK_dbo.Section_dbo.Section_ParentSectionId".

How can I configure cascade delete on self-referencing entity?

解决方案

If you Google your question you'll see a gazillion other people have the same issue, the reason is because SQL Server can not handle cascade deletes on self referencing entities and I've found no solution within entity framework that does it simply by setting some property. The only way I know to emulate a cascade delete on self referencing entities using code first is to write a recursive method that iterates through the children as you collect primary keys, foreign keys, and level of recursion information. Once this list is built, loop through it ordered by level of recursion in descending order, in each iteration you get all records for that level of recursion, loop though that collection and delete them one at a time. I did this with a stored procedure that returned this list using a recursive common table expression. I hope this helps.

这篇关于实体框架6代码优先级联自我引用实体删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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