Im having some issues with a code here. I have this method that checks if there are currently any books connected to a category, if there aren't - you should be able to remove it. And this works when i check with an category with no books and category with books connected to it.
using(var db = new DatabaseContext())
{
foreach (var cat in db.BookCategories.Include("Books").Where(c => c.Id == CategoryId)) {
if(cat.Books.Count != 0)
{
Console.WriteLine("Category cannot be deleted, because there are still books connected to it");
} else
{
Console.WriteLine("Category can be deleted, because there are no books connected to it");
}
}
}
But when i add the attach,remove and savechanges under the else statement i get this error "System.InvalidOperationException: 'There is already an open DataReader associated with this Connection which must be closed first."
db.attach(cat);
db.remove(cat);
db.savechanges();
What do i need to do to get pass this? Thank you