【发布时间】:2013-01-14 20:15:37
【问题描述】:
我有非常基本的类别模型ID, RootCategoryID, Name,如果我的类别有很多孩子,它不会删除,所以我需要递归地执行此操作,但这样做时会出错。
我知道如果我在连接字符串中添加MultipleActiveResultSets=true 可以解决此问题,但AFAIK 这可以从代码中解决,使用此参数不是一个好主意。这是真的吗?
错误
已经有一个打开的 DataReader 与此命令关联 必须先关闭。
代码
public ActionResult Delete(int id)
{
this.DeleteRecursive(id);
_db.SaveChanges();
return RedirectToAction("index", "category");
}
private void DeleteRecursive(int id)
{
// Selecting current category
var currentCategory = _db.Categories.Where(x => x.ID == id).Single(); // this line
var childrenCategories = _db.Categories.Where(x => x.RootCategory.ID == id);
// Check if category has children
if (childrenCategories.Count() > 0)
{
// Loop through children and apply same function recrusively
foreach (var c in childrenCategories)
{
this.DeleteRecursive(c.ID);
}
}
// Category has no children left, delete it
_db.Categories.Remove(currentCategory);
}
【问题讨论】:
-
在这种情况下,递归 CTE 比 LINQ 更合适。
标签: c# asp.net-mvc linq entity-framework asp.net-mvc-4