title: IDbSetExtensions.AddOrUpdate and relationships
body: <p>IDbSetExtensions.AddOrUpdate is meant to help write code that works the same whether the database is empty or populated.  But linking objects needs different code.  When the database is empty, objects don't have IDs yet and you link them by assigning the navigational property.  When the objects already exist, however, navigational properties don't work and you need to set the foreign keys directly.  <del>Navigational properties do work for proxies in both cases, at the cost of forfeiting POCOs.</del> Edit: Actually, proxies don't work when both entities are old.</p>
  
  <p>This sample crashes in the second SaveChanges call, when EF tries to set CountryID to 0:</p>
  
  <pre><code>public class Country
  {
      public virtual int ID { get; set; }
      public virtual string Name { get; set; }
  }
  
  public class Person
  {
      public virtual int ID { get; set; }
      public virtual string Name { get; set; }
  
      public virtual int CountryID { get; set; }
      public virtual Country Country { get; set; }
  }
  
  public class Context : DbContext
  {
      public DbSet&lt;Person&gt; Person { get; set; }
      public DbSet&lt;Country&gt; Country { get; set; }
  }
  
  class Program
  {
      static void Foo()
      {
          using (var db = new Context())
          {
              //var c = new Country();
              var c = db.Country.Create();
              c.Name = "usa";
              db.Country.AddOrUpdate(x =&gt; x.Name, c);
  
              //var p = new Person();
              var p = db.Person.Create();
              p.Name = "billg";
              p.Country = c;
              db.Person.AddOrUpdate(x =&gt; x.Name, p);
  
              db.SaveChanges();
          }
      }
      static void Main()
      {
          Database.SetInitializer&lt;Context&gt;(new DropCreateDatabaseAlways&lt;Context&gt;());
          Foo();
          Foo();
      }
  }
  </code></pre>
  
  <p>How is AddOrUpdate used?</p>