title: How can I replace an entity by another entity with the same key in an Entity Framework DB first approach?
body: <p>I am programming an MVC 4 webapplication using EF 5 Database first. I have some apparently trivial issues for which I cannot find a proper solution. These issues are with the object state manager. </p>
  
  <p>In the simplest scenario, everything works fine: I read entities from the database using Find, put them in a view, wait for a response, reconstitute the entity, write it back using Attach, EntityState.Modified and SaveChanges. Problems occur if, while processing a request, I get the entity from the database once more.</p>
  
  <p>I do this if:<br>
  1. I want to check some values of the original entity for some reason.<br>
  2. Some of my values are not to be modified, because they identify the entity. I put these in my view for reference only, using DisplayFor. Of course, the reconstituted model does not have these values. I get the original entity from the database and in the controller use TryUpdateModel to merge it with the model from the view.</p>
  
  <p>When calling Attach, I get an exception "An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.".</p>
  
  <p>If I use <code>Context.Entry(t).CurrentValues.SetValues(t);</code> instead of <code>DbSet.Attach(t);</code>, I get the following exception:</p>
  
  <p><code>Member 'CurrentValues' cannot be called for the entity of type 'Price' because the entity does not exist in the context. To add an entity to the context call the Add or Attach method of DbSet&lt;Price&gt;.</code></p>
  
  <p>As I understand it, there are two instances of an entity with the specific key. I would like to make the one I want to save, replace the one present, if at all. I would like this to be automatic, that is, without me having to tell if another one is present already that has to be replaced.</p>
  
  <p>Is there a way to achieve this?</p>