title: Attaching an entity of type 'X' failed because another entity of the same type
body: <p>I've stumbled upon a strange bug in my code. Which was working before, but now works sometimes.</p>
  
  <p>I am using EF6 to Edit an entity with some relations.
  To not edit the relations I 'Attach' them (see example code).</p>
  
  <pre><code>public void EditA(A ThisIsA, B ThisIsB)
      {
          using (var Context = new LDZ_DEVEntities())
          {
              Context.As.Attach(ThisIsA);
  
              var b = Context.Bs.FirstOrDefault(x =&gt; x.BId == ThisIsB.BId);
              //var b = Context.Bs.Find(ThisIsB.BId);
  
              if (b != null)
                  Context.Bs.Attach(b);
              else
                  b = ThisIsB;
  
              if (b.C != null)
                  Context.Cs.Attach(b.C);
  
              ThisIsA.Bs.Add(b);
  
              Context.SaveChanges();
  
          }
      }
  </code></pre>
  
  <p>I've edited the names to keep it simple.</p>
  
  <p>The following line</p>
  
  <pre><code>Context.Cs.Attach(b.C);
  </code></pre>
  
  <p>throws this error:</p>
  
  <blockquote>
    <p>Attaching an entity of type 'C' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.</p>
  </blockquote>
  
  <p>This line was introduced because all the C entities are static entities. I never want a C to be created. If I remove this line, every time when I will add a B to A; a C is created. Which is not desirable.</p>
  
  <p>Extra info:<br>
  A has a list of B's<br>
  B has one C<br></p>
  
  <p>This EditA() Method is being called at multiple places in my software. This error only appears when the method is called in a loop (import). There are no problems while working on the first record. But I’m getting the error in the records after the first one.</p>
  
  <p>I've read this questions plus answers but they weren't working for me:</p>
  
  <ol>
  <li><p><a href="https://stackoverflow.com/questions/23201907/asp-net-mvc-attaching-an-entity-of-type-modelname-failed-because-another-ent">ASP.NET MVC - Attaching an entity of type &#39;MODELNAME&#39; failed because another entity of the same type already has the same primary key value</a></p></li>
  <li><p><a href="https://stackoverflow.com/questions/26879968/attaching-an-entity-of-type-failed-because-another-entity-of-the-same-type-alrea">Attaching an entity of type failed because another entity of the same type already has the same primary key value</a></p></li>
  </ol>