title: MVC4 C# Populating data in a viewmodel from database
body: <p>I have a viewmodel which needs data from two models person and address:</p>
  
  <p>Models:</p>
  
  <pre><code>public class Person
  {
     public int Id { get; set; }
     public string Name { get; set; }
     public int Age { get; set; }
     public int Gender { get; set; }
  }
  
  public class Address
  {
     public int Id { get; set; }
     public string Street { get; set; }
     public int Zip { get; set; }
     public int PersonId {get; set; }
  }
  </code></pre>
  
  <p>The Viewmodel is as such</p>
  
  <pre><code>public class PersonAddViewModel
  {
      public int Id { get; set; }
      public string Name { get; set; }
      public string Street { get; set; }
  }
  </code></pre>
  
  <p>I have tried several ways to get data into the viewmodel and pass it to the view.  There will be multiple records returned to display.  </p>
  
  <p>My latest method is populating the view model as such:</p>
  
  <pre><code>private AppContexts db = new AppContexts();
  public ActionResult ListPeople()
  {
      var model = new PersonAddViewModel();
      var people = db.Persons;
      foreach(Person p in people)
      {
          Address address = db.Addresses.SingleOrDefault(a =&gt; a.PersonId == p.Id)
          model.Id = p.Id;
          model.Name = p.Name;
          model.Street = address.Street;
      }
      return View(model.ToList());
  }
  </code></pre>
  
  <p>I get an error on the Address address = db... line of "EntityCommandExecutionException was unhandled by user code.  </p>
  
  <p>How can you populate a view model with multiple records and pass to a view?  </p>
  
  <p>Final Solution:</p>
  
  <pre><code>private AppContexts db = new AppContexts();
  private AppContexts dbt = new AppContexts();
  public ActionResult ListPeople()
  {
      List&lt;PersonAddViewModel&gt; list = new List&lt;PersonAddViewModel&gt;();
      var people = db.Persons;
      foreach(Person p in people)
      {
          PersonAddViewModel model = new PersonAddViewModel();
          Address address = dbt.Addresses.SingleOrDefault(a =&gt; a.PersonId == p.Id)
          model.Id = p.Id;
          model.Name = p.Name;
          model.Street = address.Street;
      }
      return View(list);
  }
  </code></pre>