title: Exception:The object cannot be attached because it is already in the object context
body: <p>I am trying to update records in a loop using Entity Framework like this:</p>
  
  <pre><code>var data = userDetails.users.Where(x =&gt; x.IsAnonymous == true);
  
  foreach(var item in data)  
  {
      var updatedData = db.Users.FirstOrDefault(x =&gt; x.UserId == item.UserId);
      updatedData.IsAnonymous = true;
      db.Users.Attach(updatedData);
      db.ObjectStateManager.ChangeObjectState(updatedData, EntityState.Modified);
      db.SaveChanges();     
  }
  </code></pre>
  
  <p>While attach (<code>db.Users.Attach(updatedData);</code>) I got exception </p>
  
  <blockquote>
    <p>The object cannot be attached because it is already in the object context. An object can only be reattached when it is in an unchanged state</p>
  </blockquote>
  
  <p>How can I resolve this error?</p>