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

Category
Question

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

categoryId

Here's some example data:

Categories

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

Questions

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 =
        db.Categories()
            .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)
{
    <h3>@category.Name</h3>
    <ul>
    @foreach (App.Models.Question Question question in category.Questions)
    {
        <li>@question.Text</li>
    }
    </ul>
}

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