实体框架验证混淆 - 最大字符串长度为'128'

时间:2011-03-24 04:01:50

标签: entity-framework asp.net-mvc-3 entity-framework-4.1

我遇到了一个令人困惑的问题,在我的编辑或创建操作结果方法中,EF4将抛出一个DbEntityValidationException,内部消息说明:

  

字段Body必须是字符串或   数组类型,最大长度为   '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类型,因此没有明显的限制。我想发布的数据是:

<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>

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");
}

最后,实际执行grunt工作的方法是:

public void Update(T Entity)
{
    dbset.Attach(Entity);
    db.Entry(Entity).State = System.Data.EntityState.Modified;
    db.Commit();
}

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

5 个答案:

答案 0 :(得分:68)

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

答案 1 :(得分:2)

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

答案 2 :(得分:1)

可能你用过了

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

在OnModelCreating上的dbcontext类中。 所以根据你的长度改变

答案 3 :(得分:0)

对我来说,[MaxLength]无效。我在上下文中添加了以下语句。

modelBuilder.Entity<YourModel>().Property(e => e.YourColumn).HasMaxLength(4000);

我没有尝试超过“ 4000 ”的限制,但我认为可以进一步扩展。您不必将其保留为 128 (编译器显示的错误)。

答案 4 :(得分:-2)

  1. 打开实体模型图。
  2. 单击提供例外的列。
  3. 增加最大长度。
相关问题