I'm trying to organize grouped data in my Controller to use in my View.

I have the following solution in place but I'm receiving the following error:

"There is already an open DataReader associated with this Command which must be closed first."

Given 2 sets of related data: A set of questions and the categories they belong to, represented by the following classes


I would like to group the questions by their category, connected by a foreign key


Here's some example data:


category1 { Id = 1, Name = "Info about you" }
category2 { Id = 2, Name = "Info about your pet" }


question1 { categoryId = 1, Text = "What's your name?" }
question2 { categoryId = 1, Text = "What's your age?" }
question3 { categoryId = 2, Text = "What kind of pet do you have?"
question4 { categoryId = 2, Text = "What color is your pet?"

And the desired HTML output would be something like

Info about you

  • What's your name?
  • What's your age?

Info about your pet

  • What kind of pet do you have?
  • What color is your pet?

So my thought is to put info the category name and the associated questions into a ViewModel like the one below:

public class CategoriesWithQuestions() {
    public string Name { get; set; }
    public IEnumerable<Question> Questions { get; set; }

And then in my controller I would put the data into the ViewModel using a query:

public ActionResult MyAction() {

    var categoriesWithQuestions =
            .Select(category => new CategoriesWithQuestions()
                Name = category.Name,
                Questions = db.Questions().Where(Queryable => q.CategoryId == category.Id)

    return View(categoriesWithQuestions);

And use the ViewModel in the view, by looping it and accessing the category's name property and the associated questions, both accessors in the ViewModel class:

@model IEnumerable<App.ViewModels.CategoriesWithQuestions>


@foreach (var category in Model)
    @foreach (App.Models.Question Question question in category.Questions)

The Name comes in fine but the error happens when trying to access the Questions in the view.

Open to ideas in fixing my current solution or alternative (better) solutions.

Related posts

Recent Viewed