我有一个类别表
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 值的类别是顶级类别,然后是该类别的子类别。
我想删除类别,如果我删除顶级类别,则其所有子类别也必须删除。如果子类别被删除,则顶级类别将保留。
我可以通过以下方式单独删除每个类别:
[HttpPost]
public ActionResult Delete (int id) {
Category cat = db.Categories.Find(id);
db.Categories.Remove(cat)
return View("Index");
}
最佳答案
这应该有效
[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 的名称不同。我想你已经明白了。
关于mysql - 删除匹配 id 的多行 - MVC Asp.Net,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35657288/