我面临一个令人困惑的问题,其中在我的编辑或创建操作结果方法,EF4将抛出一个DbEntityValidationException与内部消息说:
The field Body must be a string or
array type with a maximum length of
‘128’.
有问题的模型如下:
[Table("tblArticles")] public class Article { [Key] public int ID { get; set; } [required(ErrorMessage="Title must be included")] public string Title { get; set; } [AllowHtml] public string Body { get; set; } [required(ErrorMessage="Start Date must be specified")] [Display(Name="Start Date")] [DisplayFormat(DataFormatString="dd-mm-yyyy")] public DateTime? StartDate { get; set; } [required(ErrorMessage = "End Date must be specified")] [Display(Name = "End Date")] public DateTime? EndDate { get; set; } public int Priority { get; set; } public bool Archived { get; set; } public virtual ICollection<ArticleImage> Images { get; set; } }
实际数据库中的“Body”字段是Text类型,因此没有明显的限制。我试图发布的数据是:
06001
Edit方法的示例如下所示:
[HttpPost] public ActionResult Edit(Article article) { if (ModelState.IsValid) { try { articleRepository.Update(article); } catch (DbEntityValidationException dbevEx) { ErrorSignal.FromCurrentContext().Raise(dbevEx); ModelState.AddModelError("FORM",dbevEx); return View("Edit",article); } // Other exception handling happens... } return RedirectToAction("Index"); }
最后,实际上做咕噜工作的方法是:
public void Update(T Entity) { dbset.Attach(Entity); db.Entry(Entity).State = System.Data.EntityState.Modified; db.Commit(); }