简体   繁体   中英

Entity Framework error: There is already an open DataReader associated with this Command

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

In this code there is only 1 database connection, so when you do this

foreach (var cat in db.BookCategories.Include("Books").Where(c => c.Id == CategoryId))

It uses the connection to start reading the 'Books'. It starts reading them, then reads one at a time.

You get that error message if you try to do another DB operation inside the loop. The reason is that the connection is still in the middle of reading the Books, or in other words, the reader is still open.

If you do this:

...... => c.Id == CategoryId).ToList())

Then it forces all the Books to be read into the list, and closes the reader, so now you can do something else with the connection.

Turns out i just had to add.ToList() at the end of the cat variable

foreach (var cat in db.BookCategories.Include("Books").Where(c => c.Id == CategoryId).ToList())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM