【问题标题】:Delete categories recursively raises datareader exception递归删除类别会引发数据读取器异常
【发布时间】: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


【解决方案1】:

您正在为childrenCategories 语句打开DataReader

除了异常之外,这意味着您执行了两次查询 - 一次获取计数,然后再次获取数据。

这应该可以解决问题:

var childrenCategories = _db.Categories
  .Where(x => x.RootCategory.ID == id)
  .ToList()
;

这将执行 SQL 语句并将所有记录具体化为 List
所以,你的数据在内存中,DataReader 就完成了。

【讨论】:

    【解决方案2】:

    我相信您的问题是您试图在 foreach 循环期间更改排序规则,这是无法完成的。

    尝试创建要删除的项目列表,然后将它们全部删除

    _db.Remove(itemsToRemove).
    

    这对你有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-08
      • 2014-02-14
      • 1970-01-01
      • 2016-10-13
      • 2016-05-27
      • 1970-01-01
      • 2014-08-31
      相关资源
      最近更新 更多