删除与id匹配的多行 - MVC Asp.Net

时间:2016-02-26 16:47:02

标签: mysql asp.net asp.net-mvc

我有一个分类表

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值的类别是Top Categories,然后是该类别的SubCategories。

我想删除类别,如果我删除顶级类别,也必须删除其所有子类别。如果SubCategory被删除,那么Top Category将保留。

我可以通过以下方式单独删除每个类别:

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

2 个答案:

答案 0 :(得分:0)

这应该有效

[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");
}

RemoveAll的方法名称可能因您使用的内容而异。名称是不同的LinqToSql和EntityFramework。我猜你有这个主意。

答案 1 :(得分: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");
}