title: An object with a temporary EntityKey value cannot be attached to an object context
body: <p>I am using a disconnected Entity Framework 4 Object Context and thanks to some awesome help previously, I've moved forward.</p>
  
  <p>Now, I have more problems. It seems EF seems to create unnecessary barriers when performing simple CRUD. In this case parent-child relations.</p>
  
  <p>In my situation, I have an existing VatCode which has VatRates. I load this in, display it and allow the user to add more VatRates. So we end up with:</p>
  
  <blockquote>
    <p>VatCode --- VatRate (existing)<br />
             +- VatRate (added by user)</p>
  </blockquote>
  
  <p>Saving this using the following code:</p>
  
  <pre><code>using (SopEntities sopEntities = EntitiesFactory.Create()) {
     VatRepository vatRepository = new VatRepository(sopEntities);
  
     foreach (VatRate vatRate in Item.VatRates) {
        if (vatRate.EntityKey == null || vatRate.EntityKey.IsTemporary) {
           sopEntities.VatRates.Attach(vatRate); 
           sopEntities.ObjectStateManager.ChangeObjectState(
              vatRate,
              System.Data.EntityState.Added
           );
        } else {
           sopEntities.VatRates.Attach(vatRate); // exception here
           sopEntities.ObjectStateManager.ChangeObjectState(
              vatRate,
              System.Data.EntityState.Modified
           );
        }
     }
  
     if (IsNew) {
        sopEntities.VatCodes.AddObject(Item);
     } else {
        sopEntities.VatCodes.Attach(Item);
        sopEntities.ObjectStateManager.ChangeObjectState(Item,System.Data.EntityState.Modified);
     }
     vatRepository.SaveChanges();
  }
  </code></pre>
  
  <p>However, when I save I get the exception:</p>
  
  <blockquote>
    <p>An object with a temporary EntityKey value cannot be attached to an
    object context</p>
  </blockquote>
  
  <p>I have attached a screenshot below:</p>
  
  <p><img src="https://i.stack.imgur.com/nJQDH.png" alt="screenshot"></p>
  
  <p>I am manually attaching/adding VatRates within the collection myself to try and identify which object is at issue. However, this does not help. THe exception shown is on the <em>genuine</em> existing VatRate within the VatCode, which <em>already has</em> an Entity Key. Could it be that the EF is stepping up the object graph into the VatCode and back down into the other VatRate which hasn't been set-up yet - because I haven't yet got to it?</p>
  
  <p>Basically, how can I save the VatCode and the VatRates contained within it within a disconnected scenario? </p>