实体框架字符串长度验证

时间:2018-07-25 15:05:13

标签: c# entity-framework

我需要保存长度大于2000个字符的字符串,但是Entity Framework验证在2000年将字符串大小“挂起”并返回错误消息:

  

值字段必须是最大长度为的字符串或数组类型   '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; }
}

DataContext

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

1 个答案:

答案 0 :(得分:1)

尝试使用“ StringLength”:

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:指定属性中允许的最大数组或字符串数​​据长度。