2

Where the error in the following code? There is already an open DataReader associated with this Command the which must be closed first.

"An error Occurred while executing the command definition. See the inner exception for details."

var cat = from c in db.Question select c;
foreach (Questions question in cat) {
    Console.WriteLine("{0}", question.tittle);
    Console.WriteLine("{0}", question.deskripsi);
    Console.WriteLine("{0}", question.id_question);
    **foreach (Categories p in question.Categories)**
    {
        Console.WriteLine("{0}", p.id_kategori);
        Console.WriteLine("{0}", p.nama_kategori);
    }
}
puretppc
  • 3,232
  • 8
  • 38
  • 65
user3113811
  • 21
  • 1
  • 2

1 Answers1

8

You probably didn't enable multiple active result sets (MARS) in your config file. Here are some details of why and how, but it always entails adding an entry

"MultipleActiveResultSets=True"

to the connection string.

However, apart from activating MARS, it's better to eager load the Categories:

from c in db.Question.Include(q => q.Categories) select c

because in your code each iteration of the foreach will execute a query to lazy load the categories (also known as n + 1 problem).

Gert Arnold
  • 105,341
  • 31
  • 202
  • 291