我有一个我想删除的父母。它看起来像这样:
-Parent
- Child 1
-Subchild 1
-Subchild 2
当我删除父级时,我还要删除Subchild。这是我的代码:
public void DeleteMenu(int id)
{
var item = this.db.Menus.Single(x => x.Id == id);
//DELETE FOREIGN KEYS
//MenuLanguageSet
var languages = from listLanguages in this.db.MenuLanguageSet
where listLanguages.idMenu == id
select listLanguages;
foreach (var itemLanguages in languages)
{
this.db.MenuLanguageSet.Remove(itemLanguages);
}
//Accesses
var accesses = from listAccesses in this.db.Accesses
where listAccesses.menuId == id
select listAccesses;
foreach (var itemAccesses in accesses)
{
this.db.Accesses.Remove(itemAccesses);
}
//DELETE CHILD
//Menus
var menusChild = from listmenus in this.db.Menus
where listmenus.parentId == id
select listmenus;
foreach (var child in menusChild)
{
DeleteMenu(child.Id);
}
//delete parent
this.db.Menus.Remove(item);
this.db.SaveChanges();
}
这不起作用,我不知道为什么。我不知道如何制作循环。
答案 0 :(得分:0)
知道了!
这是我的最终代码:
public void DeleteMenu(int id)
{
this.RecursiveDeleteMenu(id);
this.db.SaveChanges();
}
public void RecursiveDeleteMenu(int id)
{
var item = this.db.Menus.Single(x => x.Id == id);
//DELETE FOREIGN KEYS
//MenuLanguageSet
var languages = from listLanguages in this.db.MenuLanguageSet
where listLanguages.idMenu == id
select listLanguages;
foreach (var itemLanguages in languages)
{
this.db.MenuLanguageSet.Remove(itemLanguages);
}
//Accesses
var accesses = from listAccesses in this.db.Accesses
where listAccesses.menuId == id
select listAccesses;
foreach (var itemAccesses in accesses)
{
this.db.Accesses.Remove(itemAccesses);
}
//DELETE CHILD
//Menus
var menusChild = from listmenus in this.db.Menus
where listmenus.parentId == id
select listmenus;
foreach (var child in menusChild)
{
RecursiveDeleteMenu(child.Id);
}
//delete parent
this.db.Menus.Remove(item);
}
我收到错误New transaction is not allowed because there are other threads running in the session
,因为this.db.SaveChanges()
处于循环中。
谢谢大家!