Entity framework 实体框架验证混淆-最大字符串长度为';128';
我面临一个令人困惑的问题,在我的编辑或创建操作结果方法中,EF4将抛出一个DbEntityValidationException,其内部消息声明: 字段正文必须是字符串或字符串 最大长度为的数组类型 “128” 所讨论的模型如下所示:Entity framework 实体框架验证混淆-最大字符串长度为';128';,entity-framework,asp.net-mvc-3,entity-framework-4.1,Entity Framework,Asp.net Mvc 3,Entity Framework 4.1,我面临一个令人困惑的问题,在我的编辑或创建操作结果方法中,EF4将抛出一个DbEntityValidationException,其内部消息声明: 字段正文必须是字符串或字符串 最大长度为的数组类型 “128” 所讨论的模型如下所示: [Table("tblArticles")] public class Article { [Key] public int ID { get; set; } [Required(ErrorMessage="Title must be in
[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; }
}
[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();
}
我在代码或数据库中看不到任何可能导致此问题的内容,因此我还应该在哪里查找?代码中字符串字段的默认长度为128。如果您正在使用EF验证,它将引发异常。您可以使用以下方法扩展大小:
[StringLength(Int32.MaxValue)]
public string Body { get; set; }
这篇文章在某种程度上变得很受欢迎,所以我添加了第二种方法,这种方法也很有效:
[MaxLength]
public string Body { get; set; }
StringLengthAttribute
来自System.ComponentModel.DataAnnotations程序集,MaxLengthAttribute
来自EntityFramework程序集(EF 4.1)。如果使用模型优先的方法得到此错误,检查EF模型:可能只是您正在更新的实体上的属性设置了Max Length
属性。可能是您使用的
Property(m => m.Body ).IsRequired().HasMaxLength(128);
在OnModelCreating中的dbcontext类上。
因此,根据您的长度进行更改对我来说,
[MaxLength]
不起作用。我在上下文中添加了以下语句
modelBuilder.Entity<YourModel>().Property(e => e.YourColumn).HasMaxLength(4000);
modelBuilder.Entity().Property(e=>e.YourColumn).HasMaxLength(4000);
我没有尝试过超过“4000”限制,但我认为可以进一步扩展。您不必像编译器显示的错误那样保留它128。Magic。这就是问题所在。谢谢。这为我解决了问题,但在我们的案例中,这是一些部署上的问题,而不是其他部署上的问题。结果表明部署了与EF 4.1 dll稍有不同的版本;
modelBuilder.Entity<YourModel>().Property(e => e.YourColumn).HasMaxLength(4000);