title: How to perform an update using ObjectContext
body: <p>I am using EF4 in my ASP.NET MVC 2 web application. I am attempting to save data to a database. It is fairly straightforward to <em>add</em> new data to a database. I'm doing it something like this:</p>
  
  <pre><code>PeopleEntities entities = ObjectContextFactory.GetPeopleEntities();
  entities.People.AddObject(person); // The Person object created from user input.
  entities.SaveChanges();
  </code></pre>
  
  <p>However, this has the unfortunate side-effect of always saving a new object to my database. I do need this functionality (of course), but I also want the option to update an existing item in the database (or, save as new if the item does not yet exist in the database).</p>
  
  <p>I tried replacing the second line above with something like this:</p>
  
  <pre><code>entities.People.ApplyCurrentValues(person);
  </code></pre>
  
  <p>but I am receiving this InvalidOperationException:</p>
  
  <blockquote>
    <p>An object with a key that matches the
    key of the supplied object could not
    be found in the ObjectStateManager.
    Verify that the key values of the
    supplied object match the key values
    of the object to which changes must be
    applied.</p>
  </blockquote>
  
  <p>This case happens whether I try to add a new person, or if I am trying to edit a person. What can I do to correct this issue?</p>
  
  <p><strong>Update to Question:</strong></p>
  
  <p>I tried the answers provided below, but when I went to debug the <code>Single</code> statement, I found that the ID of the Person I was saving was always 0 - even if I had retrieved it from the database. So, I wanted to post what I am doing to retrieve the web application in the first place. Maybe this will help a bit.</p>
  
  <p>When I navigate to a page displaying a Person's information, the address is:</p>
  
  <p><a href="http://localhost/Person/Index/1" rel="nofollow">http://localhost/Person/Index/1</a></p>
  
  <p>where 1 is the ID of the Person in the database. I retrieve the Person through a repository method that contains the following line (entities is a member variable of the repository class):</p>
  
  <pre><code>public Person GetPerson(int id)
  {
      return entities.People.FirstOrDefault(p =&gt; p.PersonID == id);
  }
  </code></pre>
  
  <p>This method is called from my project's controller. That looks like this:</p>
  
  <pre><code>public ActionResult Index(int id)
  {
      var entities = ObjectContextFactory.GetScenarioDBEntities();
      Person person = new PersonRepository(entities).GetPerson(id);
      return View("Index", person);
  }
  </code></pre>
  
  <p>Now that I am looking at that, I wonder if it's wrong to instantiate a local entities object every time I want to retrieve a new Person. (Going to research that now.) In any case, when I do, ultimately go to save over the previous Person, I find that the PersonID value is always == 0.</p>