2014-03-27 78 views
4

我有一个实体:实体框架6代码优先级联删除自引用实体

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

我试图做一个级联删除,并且出现以下错误: “DELETE语句与SAME TABLE REFERENCE约束冲突”FK_dbo.Section_dbo.Section_ParentSectionId“。

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

+5

我不认为你可以在Entity Framework中做到这一点,因为你不能在SQL SERVER的自引用表上使用CASCADE DELETE ......但我可能是错的。 –

回答

4

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