43
[HttpPost]
public ActionResult Edit(Movie movie)
{
    if (ModelState.IsValid)
    {
        db.Entry(movie).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(movie);
}

This action receives a movie model and updates it in the database.
But I can't figure out how.
The movie object isn't attached to the db, so how does entity framework know which row in the db should be updaed?

I am sure that the Entry method has something to do with it, but I don't really know what this method does. I read that it provies information but I cannot understand how by just changing the State of an entry it becomes attached and tracked by the DBContext.

Idan Yadgar
  • 974
  • 1
  • 6
  • 16

1 Answers1

40

It just attaches the entity to the dataContext. Otherwise you will have to search for the entity using the primary key and then edit the value and save it.

If you have an entity that you know already exists in the database but to which changes may have been made then you can tell the context to attach the entity and set its state to Modified. http://msdn.microsoft.com/en-US/data/jj592676

Community
  • 1
  • 1
Parv Sharma
  • 12,581
  • 4
  • 48
  • 80
  • 3
    But for that you have the [Attach](http://msdn.microsoft.com/en-us/library/system.data.entity.dbset.attach(v=vs.103).aspx) method. – Idan Yadgar Feb 23 '13 at 21:26
  • 2
    So this method knows which of the properties of the entity class are keys and can then internally formulate a search to get the entity by its key(s) and attach it. Right? If so, that's awesome. – Luke Puplett Jan 12 '15 at 12:29
  • 4
    @Idan [here](http://stackoverflow.com/questions/30987806/dbset-attachentity-vs-dbcontext-entryentity-state-entitystate-modified)'s the difference. – Shimmy Weitzhandler May 03 '17 at 11:30