2

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

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

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

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

  • 不想使用 SQL 服务器端解决方案,例如触发器或 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; }
    }
}
4

1 回答 1

2

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

在类中添加一个 Children 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();
}
于 2013-09-05T13:22:19.467 回答