C# 使用LINQ到SQL的简单级联删除自引用表
DELETE语句与同一个表引用约束冲突 “FK_AuthCategories_Parent”。数据库“MyDB”中发生冲突, 表“dbo.AuthCategories”, 列“ParentID” 如果我试图删除一个表中的所有内容,该表的ParentID具有自引用FK,则会出现上面的错误,即我需要首先删除子项(即,它尝试删除具有子项的父项,该子项会破坏FK) 是否有一个简单的LINQ到SQL查询,它将在处理级联删除时删除表中的所有内容C# 使用LINQ到SQL的简单级联删除自引用表,c#,sql,sql-server,linq,C#,Sql,Sql Server,Linq,DELETE语句与同一个表引用约束冲突 “FK_AuthCategories_Parent”。数据库“MyDB”中发生冲突, 表“dbo.AuthCategories”, 列“ParentID” 如果我试图删除一个表中的所有内容,该表的ParentID具有自引用FK,则会出现上面的错误,即我需要首先删除子项(即,它尝试删除具有子项的父项,该子项会破坏FK) 是否有一个简单的LINQ到SQL查询,它将在处理级联删除时删除表中的所有内容 不希望使用SQL server端解决方案,例如触发器或删除级
- 不希望使用SQL server端解决方案,例如触发器或删除级联
- 需要使用LINQ到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; }
}
}
[表(Name=“authcombicates”)]
公共类AuthCategory
{
[列(IsPrimaryKey=true,IsDbGenerated=true)]
公共int ID{get;set;}
[专栏]
公共字符串名称{get;set;}
[专栏]
private int?ParentID{get;set;}
私人实体REF父母;
[关联(IsForeignKey=true,ThisKey=“ParentID”)]
公共类别父级
{
获取{return parent.Entity;}
设置{parent.Entity=value;}
}
}
好的,开始喝咖啡了,这样可以:
将子级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(); }
}
L2S对自引用级联删除没有本机支持-出于好奇,为什么不想在_DELETE_级联上使用?当您的表中有一百万行时,删除代码将如何执行?好吧,您可以在\u delete\u CASCADE上使用
,但是这个循环提供了更多的控制/可以扩展到只删除某些父/子项,而不是强制地清除所有内容。这很公平,虽然我仍然认为,只要你走过几百排,你就会撞上一堵墙!
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(); }
}
// 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();
}