2011-03-24 92 views
29

我面对一个令人困惑的问题,即在我的编辑或创建行动结果的方法,EF4将抛出DbEntityValidationException与内部消息,说明最大字符串长度:实体框架验证混乱 - 的“128”

字段主体必须是字符串或 阵列类型,最大长度为 '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; } 
} 

在实际的数据库中的“身体”字段类型文本的,所以没有明显的限制存在。我想要发布的数据是这样的:

<p> 
This is an example to confirm that new articles are looking right.</p> 
<p> 
<img alt="" src="http://www.google.co.nz/logos/2011/houdini11-sr.jpg" 
style="width: 160px; height: 56px; float: left;" /></p> 

编辑方法的一个例子是这样的:

[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(); 
} 

我看不到在代码或数据库中可能导致问题的任何东西,所以我应该在哪里看?

回答

60

代码中字符串字段的默认长度为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)。

+0

魔法。这是问题所在。谢谢。 – 2011-03-24 19:50:06

+0

这解决了我的问题,但在我们的情况下,这是一些部署问题,而不是其他问题。结果发现部署了一个稍微不同的EF 4.1 dll版本。 – tpower 2011-09-13 16:07:36

+0

太棒了!你做了我的一天。 – 2013-01-06 17:34:10

2

如果您使用模型优先方法得到此错误,请检查EF模型:可能只是您正在更新的实体上的属性已设置了Max Length属性。

0

可能是你使用

Property(m => m.Body).IsRequired().HasMaxLength(128); 

论OnModelCreating你的DbContext类。 因此根据你的长度改变