我不能删除所有孩子的root ... 这段代码错了,但我找不到解决方案。
id - 是我想删除的标记根。
public void RemoveLeaf(int id)
{
using (var context = new TreeDBtestEntities())
{
using(var dbContextTransaction = context.Database.BeginTransaction())
{
try
{
var root = context.DynamicTrees.Where(x => x.Id == id).FirstOrDefault();
int? idLeaf = root.Id;
while (idLeaf != null)
{
context.DynamicTrees.RemoveRange(context.DynamicTrees.Where(x => x.Id == id));
var result = context.DynamicTrees.Where(x => x.ParentId == idLeaf).FirstOrDefault();
if (result != null)
RemoveLeaf(result.Id);
idLeaf = null;
context.SaveChanges();
}
dbContextTransaction.Commit();
}
catch
{
dbContextTransaction.Rollback();
}
}
}
}
我想删除所有孩子的父母。此代码删除父级,只删除一些子级。
你能帮助我吗?
答案 0 :(得分:0)
我相信您可以删除递归并仅使用RemoveRange
context.DynamicTrees.RemoveRange(context.DynamicTrees.Where(x => x.Id == id || x.ParentId == id));
context.SaveChanges();