How to update the domain model object based on the domain model parameter passed to Edit action method?
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 wit开发者_JS百科h 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:
db.Movies.ApplyCurrentValues(model);
db.SaveChanges();
You can also just copy values from model to movie:
movie.Title = model.Title;
movie.Director = model.Director;
db.SaveChanges();
OK. You are using Code First, so it will be probably:
var entry = context.Entry(movie);
entry.CurrentValues.SetValues(model);
db.SaveChanges();
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
[HttpPost]
public ActionResult Edit(Movie movie)
{
if (movie == null)
{
TempData["MESSAGE"] = "No movie with id = " + id + ".";
return RedirectToAction("Index", "Home");
}
if (!ModelState.IsValid)
return View(movie);
// what method do I have to invoke here
// to update the movie object based on the model parameter?
db.Movie.AddObject(movie);
db.ObjectStateManager.ChangeObjectState(movie, System.Data.EntityState.Modified);
db.SaveChanges();
return RedirectToAction("Index");
}
Have you tried
TryUpdateModel(movie)
精彩评论