title: Entity Framework - Updating relationship by changing foreign key
body: <p>I have the two following models and DbContext:   </p>
  
  <pre><code>    public class TestDbContext : DbContext
      {
          public IDbSet&lt;Person&gt; People { get; set; }
          public IDbSet&lt;Car&gt; Cars { get; set; }
      }
  
      public class Person
      {
          public Person()
          {
              ID = Guid.NewGuid();
          }
  
          public Guid ID { get; set; }
          public string Name { get; set; }
          public virtual List&lt;Car&gt; Cars { get; set; }
      }
  
      public class Car
      {
          public Car()
          {
             ID = Guid.NewGuid();
          }
  
          public Guid ID { get; set; }
          public string Name { get; set; }
          public virtual Person Owner { get; set; }
      }
  </code></pre>
  
  <p>I then declare a list of people and a list of cars, setting the owner of the first car to the first person in the list:</p>
  
  <pre><code>List&lt;Person&gt; People = new List&lt;Person&gt;()
          {
              new Person() {Name = "bill", ID = new Guid("6F39CC2B-1A09-4E27-B803-1304AFDB23E3")},
              new Person() {Name = "ben", ID = new Guid("3EAE0303-39D9-4FD9-AF39-EC6DC73F630B")}
          };
  
          List&lt;Car&gt; Cars = new List&lt;Car&gt;() { new Car() { Name = "Ford", Owner = People[0], ID = new Guid("625FAB6B-1D56-4F57-8C98-F9346F1BBBE4") } };   
  </code></pre>
  
  <p>I save this off to the database using the following code and this works fine.</p>
  
  <pre><code>using (TestDbContext context = new TestDbContext())
          {
              foreach (Person person in People)
              {
                  if (!(context.People.Any(p =&gt; p.ID == person.ID)))
                      context.People.Add(person);
                  else
                  {
                      context.People.Attach(person);
                      context.Entry&lt;Person&gt;(person).State = System.Data.EntityState.Modified;
                  }
              }
              foreach (Car caar in Cars)
              {
                  if (!(context.Cars.Any(c =&gt; c.ID == caar.ID)))
                      context.Cars.Add(caar);
                  else
                  {
                      context.Cars.Attach(caar);
                      context.Entry&lt;Car&gt;(caar).State = System.Data.EntityState.Modified;
                  }
              }
              context.SaveChanges();
          }
  </code></pre>
  
  <p>If I then change the owner of the car to the second person and run the code again, the Car owner property doesn't get updated.   </p>
  
  <pre><code>Cars[0].Owner = People[1];
  </code></pre>
  
  <p>Any ideas to what I'm doing wrong? Thanks for any help. </p>