我有下面的类日期时间错误时将更改保存到DB
public class News
{
[Key]
public int NewsId { get; set; }
[Required(ErrorMessage = "The article title is required.")]
[MaxLength(50)]
public string Title { get; set; }
[Required(ErrorMessage = "The article text is required.")]
[UIHint("MultilineText")]
[MaxLength(500)]
public string Article { get; set; }
[Display(Name = "Days to Expire")]
public int DaysToExpire { get; set; }
public DateTime ArticleDate { get; set; }
}
和生成的CRUD视图页面。下面是从控制器的代码编辑:
[HttpPost]
public ActionResult Edit(News news)
{
if (ModelState.IsValid)
{
db.Entry(news).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(news);
}
当我尝试编辑记录,我收到以下错误:
The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.
我改变了方法
[HttpPost]
public ActionResult Edit(News news)
{
if (ModelState.IsValid)
{
var prevDate = db.NewsArticles.First(a => a.NewsId == news.NewsId).ArticleDate;
news.ArticleDate = prevDate;
db.Entry(news).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(news);
}
到尝试将ArticleDate属性设置为已有值,但收到以下错误:
The statement has been terminated.
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
我发现这是question这是相同的错误(有趣的是,他们也在使用文章),它提到错误是由于ApplyPropertyChanges被使用。
要添加,在Edit.cshtml中,ArticleDate不作为可编辑字段存在。
帮助表示赞赏。
谢谢。
谢谢你了。这样一个简单的修复。 – Erik 2012-08-14 21:35:03