I have very basic category model ID, RootCategoryID, Name and if I have category that has many childrens it won’t delete so I need to do this recursively but when I do so I get error.
I know that there is a work-around if I add MultipleActiveResultSets=true in connection string but AFAIK this can be solved from within code and it is not a good idea to use this parameter. Is this true?
Error
There is already an open DataReader associated with this Command which
must be closed first.
Code
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);
}
You’re leaving the
DataReaderopen for thechildrenCategoriesstatement.Apart from the exception, it means you’re executing the query twice – once to get the count and then again to get the data.
This should fix the problems:
This executes the SQL statement and materializes all the records into a
List.So, you have your data in memory, and the
DataReaderis complete.