2016-02-26 76 views
0

我有一個類別表刪除多行匹配的ID - MVC Asp.Net

CategoryId | CategoryName | ParentID 

    1  | Men's  | NULL 
    2  | Women's | NULL 
    3  | Mobile  | NULL 
    4  | Computing | NULL 
    5  | Electronics | NULL 
    6  | Other  | NULL 
    7  | Shirt  | 1 
    8  | T-Shirt | 1 
    9  | Dresses | 2 
    10  |  Tops  | 2 
    11  | Nokia  | 3 
    12  | Samsung | 3 
    13  | Other Mobiles| 3 
    14  | Apple  | 13 
    15  |  Sony  | 13 

正如你可以看到,其中有NULL PARENTID值類別是熱門分類,然後有一些類別的子類別。

我想刪除類別,如果我刪除頂部類別,它的所有SubCategories也必須刪除。如果子類別被刪除,那麼頂級類別保留。

我能夠通過單獨刪除每個類別:

[HttpPost] 
public ActionResult Delete (int id) { 
    Category cat = db.Categories.Find(id); 
    db.Categories.Remove(cat) 
    return View("Index"); 
} 
+0

你看過嵌套嗎? – Strawberry

回答

0

這應該工作removeall過的

[HttpPost] 
public ActionResult Delete (int id) { 
    Category cat = db.Categories.Find(id); 
    var subCategories = db.Categories.Where(a => a.ParentId == id);   
    db.Categories.RemoveAll(subCategories); 
    db.Categories.Remove(cat) 

    return View("Index"); 
} 

方法名稱可根據您所使用的不同而不同。名稱是不同的LinqToSql和EntityFramework。不過,我想你有這個想法。

0

您可能需要使用遞歸函數來處理超過2層的層次結構。

public void DeleteCategoryRecursive(int id) 
{ 
    var parent = db.Categories.Find(id); 
    var children = db.Categories.Where(a => a.ParentID == parent.CategoryID).ToList(); 
    foreach (var child in children) 
    { 
     DeleteCategoryRecursive(child.CategoryID); 
    } 
    db.Categories.Remove(parent); 
} 

然後從你的ActionResult調用這個。

[HttpPost] 
public ActionResult Delete (int id) { 
    DeleteCategoryRecursive(int id); 
    db.SaveChanges(); 
    return View("Index"); 
}