使用LINQ to SQL简单级联删除自引用表

时间:2013-09-05 12:47:06

标签: c# sql sql-server linq

  

DELETE语句与SAME TABLE REFERENCE约束冲突   “FK_AuthCategories_Parent”。冲突发生在数据库“MyDB”中,   表“dbo.AuthCategories”,   列'ParentID'。

如果我尝试删除表中具有父引用的自引用FK的所有内容,我得到上面的错误,我首先需要基本上删除子代(即它尝试删除有子代的子项,这会打破FK)。

var dc = from c in db.AuthCategories
         select c;
db.AuthCategories.DeleteAllOnSubmit(dc);
db.SubmitChanges();

是否有一个简单的LINQ to SQL查询,它会在处理级联删除时删除表中的所有内容?

  • 不想使用SQL Server服务器端解决方案,如Triggers或ON DELETE CASCADE
  • 需要使用LINQ to SQL,而不是EF
  • 希望尽可能简单,如果可能的话,

这是表结构:

[Table(Name = "AuthCategories")]
public class AuthCategory
{
    [Column(IsPrimaryKey = true, IsDbGenerated = true)]
    public int ID { get; set; }

    [Column]
    public string Name { get; set; }

    [Column]
    private int? ParentID { get; set; }
    private EntityRef<AuthCategory> parent;
    [Association(IsForeignKey = true, ThisKey = "ParentID")]
    public AuthCategory Parent
    {
        get { return parent.Entity; }
        set { parent.Entity = value; }
    }
}

1 个答案:

答案 0 :(得分:2)

好的,咖啡开了,这很有效:

在课堂上添加一个儿童IEnumerable:

private EntitySet<AuthCategory> children = new EntitySet<AuthCategory>();
[Association(Storage = "children", OtherKey = "ParentID")]
public IEnumerable<AuthCategory> AuthCatChildren
{
    get { return children; }
}
public IEnumerable<AuthCategory> Children
{
    get { return (from x in AuthCatChildren select x).AsEnumerable(); }
}

现在您可以先通过while循环删除孩子:

// Loop, Deleting all rows with no children (which would delete childless parents and nested grandchild/children)
int loop = 1;
while (loop > 0)
{
    var dbList = from c in db.AuthCategories.ToList()
                    where c.Children.Count() == 0
                    select c;
    loop = dbList.Count();
    db.AuthCategories.DeleteAllOnSubmit(dbList);
    db.SubmitChanges();
}