title: Why does EF say an object with the same key already exists when it's "Detached"?
body: <p>In my repository update method, I first attach existing objects that may need to be added to the updated entity's collections before doing anything else, so that EF realizes that I want to associate the entity with another existing entity, and not create a new one.  So in this example, I'm doing it with user groups:</p>
  
  <pre><code>UserGroup basicGroup = repoGroup.GetGroupByName("BasicGroup");
  List&lt;UserGroup&gt; updatedGroups = new List&lt;UserGroup&gt; { basicGroup };
  foreach (var user in usersToUpdate) {
      repoUser.UpdateUser(user.userId, updatedGroups);
  }
  
  [...]
  
  public bool UpdateUser(int updatedUserId, List&lt;UserGroup&gt; updatedGroups) {
      using (var context = new MyDbContext()) {
          if (updatedGroups != null) {
              // Attach groups to context before add so that EF creates a new
              // relationship between entity and new items in groups collection,
              // instead of creating a new entity for each new item.
              foreach (UserGroup group in updatedGroups) {
  
                  var testEntry = context.Entry(group);
  
                  context.UserGroups.Attach(group);
              }
          }
  
          var userToUpdate = context.Users.First(usr =&gt; usr.id == updatedUserId);
          userToUpdate.UserGroups.Clear();
          foreach (var group in updatedGroups) {
              userToUpdate.UserGroups.Add(group);
          }
  
          context.SaveChanges();
          return true;
      }
  }
  </code></pre>
  
  <p>So my code cycles through several users and tries to associate a new set of groups with them.  I realize the mistake I'm making here is that my <code>.Attach</code> is potentially trying to attach the same entity to the object context twice - in this case, <code>basicGroup</code>.  So I thought I could test to see whether the object had already been attached and only attach it if it hadn't.</p>
  
  <p>So look at the testEntry line.  There, I try and get the <code>group</code> entity's <code>Entry</code> status.  I do indeed get a <code>DbEntityEntry</code> instance, but it always says that the <code>EntityState</code> is <code>Detached</code> (in every loop iteration).  Now, when I run my code, it's OK in the first iteration of the foreach loop, but in the second iteration, I get the exception:</p>
  
  <blockquote>
    <p>An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.</p>
  </blockquote>
  
  <p>I don't understand this; if the object already exists in the ObjectStateManager, why does my <code>DbEntityEntry</code> say its state is <code>Detached</code>?  Surely it should remember that its state is <code>Unchanged</code>.</p>