0

I have the following Edit method:

[HttpPost]
public ActionResult Edit(Movie movie)
{
    try
    {
        _db.ApplyCurrentValues("Movies1",movie);
        _db.SaveChanges();
        return RedirectToAction("Index"); 
     }
     catch
     {
         return View();
     }
 }

I get the error below when I run it:

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.

A couple points:

  • I did not get the error the first time I did an update, only subsequent updates.
  • Movies1 is the the name of the EntitySet when I view the edmx designer. Is this what it shold be or should it be the name of the table (Movie)?
  • I have seen things regarding Attach, but I am confused as to what exactly that is.
0

1 Answer 1

2

Inorder to apply current values an entity with that given key should be present in ObjectStateManager. The documentation for the ApplyCurrentValues states

Copies the scalar values from the supplied object into the object in the ObjectContext that has the same key.

You can attach the entity and apply current values.

    _db.Movies.Attach(movie);
    _db.ObjectStateManager.ChangeState(movie, EntityState.Modified);
    _db.SaveChanges();
Sign up to request clarification or add additional context in comments.

2 Comments

I think reloading from DB instead of calling Attach would be a better example. Your code snippet removes the exception, but is somehow an empty operation because you are updating an entity with itself = No changed properties = No UPDATE to DB.
@Slauma Yes. Thanks for noticing the issue. Updated answer to change the state of the object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.