title: Nested foreach loop in ASP.NET MVC Core NullReferenceException
body: <p>I'm trying to add a navigation sidebar in a simple web app that has two primary models, and I'm running into a peculiar error when I try to use a nested loop to render data in the sidebar.</p>
  
  <p>My app has two models like Category and Thing in the example below:</p>
  
  <pre><code>public class Category
  {
      public int ID { get; set; }
      public string Name { get; set; }
      public virtual ICollection&lt;Thing&gt; Things { get; set; }
  }
  
  public class Thing
  {
      public int ID { get; set; }
      public string Title { get; set; }
      public string Description { get; set; }
      public int CategoryID { get; set; }
      public virtual Category Category { get; set; }
  }
  </code></pre>
  
  <p>I want to add a sidebar that contains a list of all my Categories. I created a ViewComponent that I'm referencing in _Layout.cshtml like so:</p>
  
  <pre><code>// SidebarViewComponent.cs
  public class SidebarViewComponent : ViewComponent
  {
      private readonly MyContext db;
  
      public SidebarViewComponent(MyContext context)
      {
          db = context;
      }
  
      public async Task&lt;IViewComponentResult&gt; InvokeAsync()
      {
          var categories = await GetCategoriesAsync();
          return View(categories);
      }
  
      private Task&lt;List&lt;Category&gt;&gt; GetCategoriesAsync()
      {
          return db.Category.ToListAsync();
      }
  }
  
  // View file for SidebarViewComponent
  @model IEnumerable&lt;MyApp.Models.Category&gt;
  &lt;div id="sidebar"&gt;
      @foreach (var category in Model)
      {
          &lt;div class="header"&gt;@category.Name&lt;/div&gt;
              @foreach (var thing in @category.Things)
              {
                  &lt;div&gt;@thing.Title&lt;/div&gt;
              }
          &lt;/div&gt;
      }
  &lt;/div&gt;
  
  // _Layout.cshtml
  &lt;!DOCTYPE html&gt;
  &lt;html&gt;
  &lt;head&gt;
      &lt;meta charset="utf-8" /&gt;
      &lt;title&gt;@ViewData["Title"]&lt;/title&gt;
  
      &lt;!-- Stylesheets --&gt;
      &lt;link rel="stylesheet" href="~/css/site.css"&gt;
  &lt;/head&gt;
  &lt;body&gt;
      @await Component.InvokeAsync("Sidebar")
      @RenderBody()
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>When I access a page that's rendered by my ThingController, this works perfectly. But on my home page or any page handled by CategoryController, I get the error "NullReferenceException: Object reference not set to an instance of an object." at the line <code>@foreach (var thing in @category.Things)</code>.</p>
  
  <p>How can I get this sidebar to work on every page?</p>