Given a table of contents that will contain:
Categories, Sections, Topics,
I have created the following 3 models:
public class Category
{
public int id { get; set; }
public string name { get; set; }
public ICollection<Section> Sections { get; set; }
}
public class Section
{
public int id { get; set; }
public string name { get; set; }
public int CategoryId { get; set; }
public ICollection<Topic> Topics { get; set; }
}
public class Topic
{
public int id { get; set; }
public string name { get; set; }
public int SectionId { get; set; }
}
In SQL Mgmt Studio, I have created the one-to-many relationships between the 3 tables. My Controller ActionResult looks like this:
public ActionResult Index()
{
return View(_db.Categories.ToList());
}
Then my View:
@model IEnumerable<Models.Category>
<h2>Table of Contents</h2>
<ul>
@foreach (var item in Model)
{
<li>@Html.DisplayFor(model => item.name)
@if (item.Sections != null)
{
<ul>
@foreach (var sec in item.Sections)
{
<li>@Html.DisplayFor(model => sec.name)
@if (sec.Topics != null)
{
<ul>
@foreach (var topic in sec.Topics)
{
<li>@Html.DisplayFor(model => topic.name)</li>
}
</ul>
}
</li>
}
</ul>
}
</li>
}
</ul>
I only get the data from the Category table. So it correctly grabs the category data and builds the outer list, but it is not populating the related Sections and Topics in the model. What am I doing wrong?
Attempted to implement an answer per David Clough's suggestion in the comments below. After referencing System.Data.Entity in my Controller, the lambda expression version was able to compile and run, but it produces an error in the foreach loop trying to access the model. The error in the InnerException is: "Invalid column name 'Section_id'.\r\nInvalid column name 'Category_id'.\r\nInvalid column name 'Section_id'."
Here is the change I made to the Controller:
public ActionResult Index()
{
var TOC = _db.Categories.Include(c => c.Sections.Select(s => s.Topics));
return View(TOC);
}