title: How to update foreign key in EF 6 - Code First
body: <p>I'm trying to update a foreign key in EF6 (Code First) in an ASP.Net MVC manner.</p>
  
  <p>Let me explain : </p>
  
  <p><strong>My entities</strong></p>
  
  <pre><code>public class Person
  {
      public int Id { get; set; }
      public string Name { get; set; }
      public virtual Country Country { get; set; }
  }
  
  public class Country
  {
      public int Id { get; set; }
      public string Name { get; set; }
  }
  </code></pre>
  
  <p><strong>My database</strong></p>
  
  <p>Table Countries with 2 records : </p>
  
  <ol>
  <li>Id = 1, Name = France </li>
  <li>Id = 2, Name = Canada</li>
  </ol>
  
  <p>Table People with 1 record :</p>
  
  <ol>
  <li>Id = 1, Name = Nicolas, Country_Id = 1</li>
  </ol>
  
  <p><strong>My code</strong></p>
  
  <pre><code>  // In a MVC application, these class has been retrieved via EF in a previous page. So now, we've lost all "proxy" informations
    var p = new Person() { Id = 1, Name = "Nicolas" };
  
    // Change country
    p.Country = new Country() { Id = 2, Name = "Canada" };
  
    // Persist all in DB
    using (var db = new TestDbContext())
    {                
        db.Persons.Attach(p); // Reattach to EF context
        db.Entry&lt;Person&gt;(p).State = EntityState.Modified; // Flag modified state
        db.SaveChanges(); // Generate only modification on field "name"
    }
  </code></pre>
  
  <p><strong>My issue</strong></p>
  
  <p>When the previous code is executed, the generated SQL never include the country_Id field from the person table.</p>
  
  <p><strong>My "not" issue</strong></p>
  
  <p>I know that it works perfectly when doing all these lines of codes in one EF context but in my case, I will have the data coming from my ASP.Net MVC page.
  I would also like to avoid to retrieve the existing data and modify each field one by one</p>