title: Assigning UserId to Foreign Key = null
body: <p>I'm using Entity Framework 5 and MVC 4, with .NET 4.5 using Code First migrations. I have foreign keys between two entities in a 1 to zero-or-1 relationship. When I try to create the record for Jogger everything blows up. I get error messages that are either:</p>
  
  <ul>
  <li>Foreign Key is a null reference</li>
  <li>dbo.Jogger does not exist</li>
  <li>Unhandled exception ... no metadata.</li>
  </ul>
  
  <p>When I run the EF Viewer the navigation relationships are perfect. No Fluent API code is used at the moment.</p>
  
  <p><strong>User Class</strong> </p>
  
  <pre><code>     [Key]
      [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
      public int UserId { get; set; }
      public string UserName { get; set; }
  
      // Other properties
  
      public int? JoggerId { get; set; }
      public virtual Jogger Jogger { get; set; }
  </code></pre>
  
  <p><strong>Jogger Class</strong></p>
  
  <pre><code>    [ForeignKey("UserId")]
      public int JoggerId { get; set; }
  
      public virtual UserProfile UserId { get; set; }
  </code></pre>
  
  <p>When the JoggerController is generated it produces this code for the Get and Post Methods:</p>
  
  <pre><code>// GET: /Jogger/Create
  
      public ActionResult Create()
      {
          ViewBag.JoggerId = new SelectList(db.UserProfiles, "UserId", "UserName");
          return View();
      }
  
      //
      // POST: /Jogger/Create
  
      [HttpPost]
      [ValidateAntiForgeryToken]
      public ActionResult Create(Jogger jogger)
      {
  
  
  
          if (ModelState.IsValid)
          {
              db.Jogger.Add(jogger);
              db.SaveChanges();
              return RedirectToAction("Index");
          }
  
          ViewBag.JoggerId = new SelectList(db.UserProfiles, "UserId", "UserName", jogger.JoggerId);
          return View(jogger);
      }
  </code></pre>
  
  <p>In the Jogger/Create view there are no fields for JoggerId or UserId according to the generated code. </p>
  
  <p>Typically it fails on the (ModelState.IsValid) portion of code where the Output shows JoggerId = 0 and UserId = null. </p>
  
  <p>I have not seen this behaviour on the Contoso University tutorial on asp.net's website and I have looked at the MSDN Learn EF site as well. I can't seem to solve this problem. Your advice is appreciated. </p>