I have an action method to handle the HTTP-POST as follows.
[HttpPost]
public ActionResult Edit(Movie model)
{
var movie = db.Movies.FirstOrDefault(x => x.Id == model.Id);
if (movie == null)
{
TempData["MESSAGE"] = "No movie with id = " + id + ".";
return RedirectToAction("Index", "Home");
}
if (!ModelState.IsValid)
return View(model);
// what method do I have to invoke here
// to update the movie object based on the model parameter?
db.SaveChanges();
return RedirectToAction("Index");
}
Question: How to update movie based on model ?
Edit 1
Based on @lukled’s solution, here is the final and working code:
[HttpPost]
public ActionResult Edit(Movie model)
{
var movie = db.Movies.FirstOrDefault(x => x.Id == model.Id);
if (movie == null)
{
TempData["MESSAGE"] = string.Format("There is no Movie with id = {0}.", movie.Id);
return RedirectToAction("Index", "Home");
}
if (!ModelState.IsValid)
return View(model);
var entry = db.Entry(movie);
entry.CurrentValues.SetValues(model);
db.SaveChanges();
return RedirectToAction("Index");
}
Try this:
You can also just copy values from model to movie:
OK. You are using Code First, so it will be probably:
But I am not sure about it, because I don’t have Code First installed. Taken from:
http://blogs.msdn.com/b/adonet/archive/2011/01/30/using-dbcontext-in-ef-feature-ctp5-part-5-working-with-property-values.aspx