title: MVC Models, Entity Framework and binding dropdowns best practice
body: <p>Extremely basic question about best practice in MVC when binding drop down lists.</p>
  
  <p>This inst a real world example but a basic example that explains my question:</p>
  
  <p>Take the following model</p>
  
  <pre><code>public class Person
  {
      public int ID { get; set; }     
      public string Name { get; set; }
      public virtual Car Car { get; set; }
  }
  
  public class Car
  {
      public int ID {get;set;}
      public string Make {get; set;{}
      public string Model {get; set;}
  }
  </code></pre>
  
  <p>Then assume that these get flattened into a view model: </p>
  
  <pre><code>public class IndexViewModel
  {
      public int PersonID;
      public string Name;
      public int SelectedCarID;
      public SelectList&lt;Cars&gt; Cars;
  }
  </code></pre>
  
  <p>In my constructor I have an index method:</p>
  
  <pre><code>[HttpGet]
  public ActionResult Index()
  {
      var person = _ctx.People.FirstOrDefault(x=&gt;x.ID == 1);
  
      var vm = new IndexViewModel(){
          Name = person.Name,
          SelectedCarID = person.Car.ID,
      };
  
      return View(vm);
  }
  </code></pre>
  
  <p>Now, Assume that the person that is returned from the context has NO car record when the page first loads.
  The view has a line : </p>
  
  <pre><code>@Html.DropDownListFor(m=&gt;m.SelectedCarID, Model.Cars)
  </code></pre>
  
  <p>When the form is submitted it is picked up by the action :</p>
  
  <pre><code>[HttpPost]
  public ActionResult Index(IndexViewModel model)
  {
      var person = _ctx.People.FirstOrDefault(x=&gt;x.ID == model.PersonID);
  
      var car = _ctx.Cars.FirstOrDefault(x=&gt;x.ID == model.SelectedCarID);
  
      person.Name = model.name;
      person.Car = car;
  
      _ctx.SaveChanges();
  }
  </code></pre>
  
  <p>Now that is the way I have done it for ages, I started using EF back when LINQ to SQL was taking off and I have always created my models like that as I was under the imperssion that it was the recommended way.
  After a discussion with another developer today I am not sure if this is stil the best way? It has always irked me that I need to do a lookup against the database to get the Car record out just so that I can update the record.</p>
  
  <p>My questions are: </p>
  
  <ol>
  <li>What is the best way to achive what I have described above? </li>
  <li>Is the above correct? </li>
  <li>Is there a better way to update the car entity against the person without doing a lookup (Preferably without including the foreign keys in the model)?</li>
  <li>Is it better to just include the FKs in the model (Its not the way Ive been doing it bit it seems more sensible)?</li>
  <li>Is there a way to bind the drop down to the car object (The guy I spoke to seemed to suggest you could but my knowlege of MVC/asp.net and furious googling seems to indicate that you cant)?</li>
  </ol>