我有下面的類日期時間錯誤時將更改保存到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