首页 > 解决方案 > 实体框架字符串长度验证

问题描述

我需要保存一个长度大于 2000 个字符的字符串,但实体框架验证“挂起”了 2000 年的字符串大小并返回错误消息:

Value 字段必须是字符串或数组类型,最大长度为“2000”。

在数据库中,字段是VARCHAR (8000)并且在实体中定义 MaxLength 为 8000

模型

public class TermoUso : BaseEntity
{
    public Guid TermoUsoKeyId { get; set; }
    public virtual TermoUsoKey TermoUsoKey { get; set; }

    [Required]
    [MaxLength(8000)]
    public string Texto { get; set; }
}

数据上下文

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
        modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();

        modelBuilder.Properties<string>()
            .Configure(c => c.HasColumnType("varchar"));

        modelBuilder.Properties<string>()
            .Configure(c => c.HasMaxLength(8000));

        modelBuilder.Properties<DateTime>()
            .Configure(c => c.HasColumnType("datetime2"));
    }

标签: c#entity-framework

解决方案


尝试使用“字符串长度”:

public class TermoUso : BaseEntity
{
    public Guid TermoUsoKeyId { get; set; }
    public virtual TermoUsoKey TermoUsoKey { get; set; }

    [Required]
    [StringLength(8000)]
    public string Texto { get; set; }
}

StringLength 是一个数据注释,将用于验证用户输入。

来自 MSDN:指定数据字段中允许的最小和最大字符长度

MaxLength 用于实体框架在创建数据库时确定字符串值字段的大小。

来自 MSDN:指定属性中允许的数组或字符串数​​据的最大长度。


推荐阅读