c# - 实体框架字符串长度验证
问题描述
我需要保存一个长度大于 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"));
}
解决方案
尝试使用“字符串长度”:
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:指定属性中允许的数组或字符串数据的最大长度。
推荐阅读
- html - 如何将伪元素设置为段落的标题?
- reactjs - React Router:如何在不替换任何内容的情况下正确附加到路由/url?
- c# - 将匿名任务添加到此列表的语法是什么?
- reactjs - 即使状态存在,React-Redux 页面刷新也会重定向到登录
- javascript - 从帖子摘录字段将所有帖子图像 URL 更改为新 URL
- javascript - 'scales' 选项似乎破坏了 Chart.js 图表
- sqlite - 当我尝试在 SQLITE DB 中保存数据时出现错误“数据库已锁定”
- xamarin - 如何更改 Android 的 Xamarin.Forms Frame 默认选定边框?
- r - R 新手,尽管安装了 lubridate,但无法使用 floor_date 命令
- laravel - 在 Laravel 8 中创建包含作业、事件、侦听器、队列的结构