我正在尝试更新新闻帖子.该帖子有一个名为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)
这样做的最佳实践方法是什么?
谢谢!