title: How do I edit an entity using the Entity Framework Code First approach?
body: <p>I have been tearing my hair out over this for days and before I go completely bald it's time to ask all the people smarter than me how to do this.</p>
  
  <p>I am using Entity Framework 4 with the Code First CTP 5 and MVC 3.</p>
  
  <p>The exception message right now is "An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key."</p>
  
  <p>First up here is the controller the edit form is posted to:</p>
  
  <pre><code>public ActionResult Save(ClientEntity postedClient)
      {
          try
          {
              if (ModelState.IsValid)
              {
                  Base.clientInterface.Save(postedClient);
                  return RedirectToAction("Index");
              }
          }
          catch (Exception)
          {
  
              throw;
          }
  
          SetupManageData(null, postedClient);
          return View("Manage");
  
      }
  </code></pre>
  
  <p>The Save method on the client interface is this:</p>
  
  <pre><code>public void Save(ClientEntity theClient)
      {
          SetContext();
  
  
          if (theClient.clientId == 0)
              this.pContext.Clients.Add(theClient);
          else
          {
              ClientEntity existingClient = GetSingle(theClient.clientId); // Get the existing entity from the data store.
  
              // PseudoCode: Merge existingClient and theClient - Can this be done without using ObjectStateManager?               
              // PseudoCode: Attach merged entity to context so that SaveChanges will update it in the database - is this correct?
          }
  
          this.pContext.SaveChanges();
  
      }
  
      private void SetContext()
      {
          if (this.pContext == null)
              this.pContext = new PersistanceContext();           
      }
  </code></pre>
  
  <p>Persistance context is the DBContext and looks like this:</p>
  
  <pre><code>public class PersistanceContext : DbContext
  {
      public DbSet&lt;ClientEntity&gt; Clients { get; set; }
  }
  </code></pre>