如何根据传递给Edit action方法的域模型参数更新域模型对象?

时间:2011-02-17 03:19:21

标签: c# asp.net-mvc entity-framework asp.net-mvc-3

我有一个动作方法来处理HTTP-POST,如下所示。

    [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");
    }

问题:如何根据movie更新model

修改1

基于@ lukled的解决方案,这是最终的和有效的代码:

    [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");
    }

3 个答案:

答案 0 :(得分:1)

[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");
}

答案 1 :(得分:1)

试试这个:

db.Movies.ApplyCurrentValues(model);
db.SaveChanges();

您也可以只将模型中的值复制到电影中:

movie.Title = model.Title;
movie.Director = model.Director;
db.SaveChanges();

行。您正在使用Code First,因此可能会:

var entry = context.Entry(movie);
entry.CurrentValues.SetValues(model);
db.SaveChanges();

但我不确定,因为我没有安装Code First。摘自:

http://blogs.msdn.com/b/adonet/archive/2011/01/30/using-dbcontext-in-ef-feature-ctp5-part-5-working-with-property-values.aspx

答案 2 :(得分:1)

你试过吗

TryUpdateModel(movie)