title: Why am I getting an InvalidOperationException when trying to re-attach an object
body: <p>I had a bit of a struggle trying to understand why my code was crashing (which I got to work).</p>
  
  <p>When you look at both the original method and the working one, the placement of one line is different</p>
  
  <pre><code>ctx.Inventories.Attach(this);
  </code></pre>
  
  <p>I'm puzzled when the original method doesn't work but the second one does. 
  Can anyone provide some insight?</p>
  
  <p>Here's the exception that I get.</p>
  
  <p>System.InvalidOperationException : An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.</p>
  
  <p>This is my original method</p>
  
  <pre><code>  public void RemoveDependency(int depId)
      {
          bool returnValue = false;
  
          if (this.Id != 0 &amp;&amp; depId &gt; 0)
          {
              using (ApsEntities ctx = new ApsEntities())
              {
                  var query2 = from d in ctx.Dependencies
                               where d.Id == depId
                               select d;
  
                  Dependency found = query2.FirstOrDefault();
  
                  if (found != null)
                  {
                  **ctx.Inventories.Attach(this);**
                      ctx.ObjectStateManager.ChangeObjectState(this, EntityState.Modified);
                      this.Dependencies.Remove(found);
  
                     ctx.SaveChanges();
                  }
              }
          }
  
          return returnValue;
      }
  </code></pre>
  
  <p>Here is my working method</p>
  
  <pre><code>public void RemoveDependency(int depId)
  {
      bool returnValue = false;
  
      if (this.Id != 0 &amp;&amp; depId &gt; 0)
      {
          using (ApsEntities ctx = new ApsEntities())
          {
              **ctx.Inventories.Attach(this);**
  
              var query2 = from d in ctx.Dependencies
                           where d.Id == depId
                           select d;
  
              Dependency found = query2.FirstOrDefault();
  
              if (found != null)
              {
                  ctx.ObjectStateManager.ChangeObjectState(this, EntityState.Modified);
                  this.Dependencies.Remove(found);
  
                 ctx.SaveChanges();
              }
          }
      }
  
      return returnValue;
  }
  </code></pre>