在MVC中仅更新对象的某些字段的最佳方法是什么?

Unw*_*und 5 c# asp.net-mvc entity-framework-6 asp.net-mvc-5

我正在尝试更新新闻帖子.该帖子有一个名为Created的日期字段,该字段在最初创建记录时填充.我在更新时不包含这个,因此在使用下面的方法时,这是null并抛出错误.

我正在使用MVC 5和Entity Framework 6

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Title,Summary,Content")] Post post) {
    if (ModelState.IsValid) {
        db.Entry(post).State = EntityState.Modified;
        db.SaveChanges();

        return RedirectToAction("Index");
    }
    return View(post);
}
Run Code Online (Sandbox Code Playgroud)

这种方法确实有效,但看起来有点笨重.

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Title,Summary,Content")] Post post) {
    if (ModelState.IsValid) {
        var newsPost = db.Posts.Find(post.Id);
        if (newsPost == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); }
        newsPost.Title = post.Title;
        newsPost.Summary = post.Summary;
        newsPost.Content = post.Content;
        db.Entry(newsPost).State = EntityState.Modified;
        db.SaveChanges();

        return RedirectToAction("Index");
    }
    return View(post);
}
Run Code Online (Sandbox Code Playgroud)

这样做的最佳实践方法是什么?

谢谢!

Sho*_*hoe 7

EF还有一个简单的内置"AutoMapper",可以使用标量值.

public class PostViewModel()
{
     public string Id {get;set;}
     public string Title {get;set;}
     public string Summary {get;set;}
     public string Content {get;set;}
}

public ActionResult Edit(PostViewModel viewModel)
{
    if (ModelState.IsValid) {
        var newsPost = db.Posts.Find(post.Id);
        ...
        db.Entry(newsPost).CurrentValues.SetValues(viewModel);
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这真的是唯一这样做的方式......对数据库的额外调用让我感到畏缩...... (2认同)