33

我遇到了一个令人困惑的问题,在我的 Edit 或 Create 操作结果方法中,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; }
}

实际数据库中的“正文”字段是文本类型,因此没有明显的限制。我要发布的数据是这样的:

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

最后,实际完成繁重工作的方法是:

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

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

4

4 回答 4

73

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

于 2011-03-24T08:18:28.293 回答
2

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

于 2012-09-07T13:43:13.107 回答
1

可能你用过

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

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

于 2017-01-22T11:55:02.700 回答
0

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

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

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

于 2019-02-07T12:35:34.587 回答