title: EF and normalized code-first database duplicate primary key
body: <p>I have a base class that has a virtual property. The id column for the base class is auto generated upon insertion, while the class that is virtual has an Id, retrieved from another data source (still guaranteed unique). When inserting a base entity into the database twice, I get a "primary key violation exception" on the property - meaning the database is trying to reinsert the same entity twice. </p>
  
  <p>Is there a way to tell EF to insert <strong>or update</strong> the virtual property entity, as I would like to keep the property entries at a minimum, and they don't change once created?</p>
  
  <p>Example:</p>
  
  <pre><code>public class Parent {
      [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
      [Key]
      public Guid Id {get;set;}
  
      public virtual Child Child {get; set;} 
  }
  
  public class Child {
      [Key]
      public Guid Id {get;set;} 
  }
  
  void Insert(){
      var c1 = new Child(){Id = Guid.NewGuid()};
      var c2 = new Child(){Id = c1.Id};
      var p1 = new Parent(){ Child = c1 };
      var p2 = new Parent(){ Child = c2 };
      db.Entries.Add(p1);
      db.SaveChanges();
      db.Entries.Add(p2); //Throws exception because of this
      db.SaveChanges(); 
  }
  </code></pre>
  
  <p>Note that this is an example, these could be object from two different functions, just with the same Child Id.</p>
  
  <p>Update: I'd like to say I know I could create a new Parent, get any Child with the correct Id from the DB and assign that to Parent.Child, but there are quite a few properties in Parent, and quite a few parents created - the process takes about 2.5 seconds for four parent objects. Way too long.</p>
  
  <p>Update 2: I'll define the actual question here. Is there a way, without explicitly calling </p>
  
  <p><code>c2 = db.Entries.FirstOrDefault(e=&gt;e.Child.Id == c2.Id)?.Child</code> </p>
  
  <p>to have EF figure out I want the p2.Child pointing at c1 (when c1 and c2 have the same PK of course) instead of trying to reinsert c2? Remember, the Parent inserts will happen from non related function executions.</p>