2017-06-21 114 views
-1

我有一個我想要刪除的父項。它看起來像這樣:c中的遞歸刪除#

-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(); 


    } 

這不工作,我不知道爲什麼。我不知道如何讓我的循環。

+2

定義「這是行不通的」 –

+1

另外,如果您有菜單項,那麼在數據庫中級聯刪除的效率應該高出許多倍。 – flq

+1

級聯刪除將是更好的方法,並且如果您能夠 –

回答

0

Got it!

這是我的最終代碼:

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()是一個循環。

謝謝大家!