title: Looping through list of entities in a ViewModel
body: <p>One of my entities <code>Create</code> page needs to have a list of other entities, in this case the <code>Timetable</code> create view needs a list of <code>Station</code> entities. To achieve this I created my own ViewModel:</p>
  
  <pre><code>public class TimetablesCreateViewModel
  {
      public Timetable Timetable { get; set; }
      public IEnumerable&lt;Station&gt; Stations { get; set; }
  }
  </code></pre>
  
  <p>I then changed my <code>Create</code> methods in the <code>TimetablesController</code> class to be this:</p>
  
  <pre><code>public ActionResult Create()
  {
      TimetablesCreateViewModel model = new TimetablesCreateViewModel
      {
          Timetable = new Timetable(),
          Stations = db.Stations.ToList()
      };
  
      return View();
  }
  </code></pre>
  
  <p>I then modified my <code>Create.cshtml</code> page to use <code>@model MyApp.ViewModels.TimetablesCreateViewModel</code>, and I'm attempting to loop through <code>Station</code>s like this:</p>
  
  <pre><code>@foreach (var s in Model.Stations)
  {
      &lt;p&gt;@s.Name&lt;/p&gt;
  }
  </code></pre>
  
  <p>When I load the <code>/Timetables/Create</code> page, I get a <code>NullReferenceException</code>:</p>
  
  <blockquote>
    <p>An exception of type 'System.NullReferenceException' occurred in
    App_Web_lqnuresu.dll but was not handled in user code</p>
    
    <p>Additional information: Object reference not set to an instance of an
    object.</p>
  </blockquote>
  
  <p>The only thing I thought would be causing this is if no stations were populated into <code>Model.Stations</code>, but that's not the case, it's successfully retrieving all the stations in the database.</p>