title: Is is possible to check if an object is already attached to a data context in Entity Framework?
body: <p>I am getting the following error when trying to attach an object that is already attached to a given context via <code>context.AttachTo(...)</code>:</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>Is there a way of achieving something along the lines of:</p>
  
  <p><code>context.IsAttachedTo(...)</code></p>
  
  <p>Cheers!</p>
  
  <p><b>Edit:</b></p>
  
  <p>The extension method Jason outlined is close, but it doesn't work for my situation.</p>
  
  <p>I am trying to do some work using the method outlined in the answer to another question:</p>
  
  <p><a href="https://stackoverflow.com/questions/1601350/how-do-i-delete-one-or-more-rows-from-my-table-using-linq-to-entities-without-r">How do I delete one or more rows from my table using Linq to Entities *without* retrieving the rows first?</a></p>
  
  <p>My code looks a bit like this:</p>
  
  <pre><code>var user = new User() { Id = 1 };
  context.AttachTo("Users", user);
  comment.User = user;
  context.SaveChanges();
  </code></pre>
  
  <p>This works fine, except when I do something else for that user where I use the same method and try to attach a dummy <code>User</code> object. This fails because I have previously attached that dummy user object. How can I check for this?</p>