Entity Framework Validation confusion - maximum string length of '128'

元气小坏坏 提交于 2019-11-27 11:47:54

Default length of string field in code first is 128. If you are using EF validation it will throw exception. You can extend the size by using:

[StringLength(Int32.MaxValue)]
public string Body { get; set; }

This post became somehow popular so I'm adding second approach which also works:

[MaxLength]
public string Body { get; set; }

StringLengthAttribute is from System.ComponentModel.DataAnnotations assembly and MaxLengthAttribute is from EntityFramework assembly (EF 4.1).

Marty

If you get this error using a Model First approach, check the EF Model: it may be simply that a property on the Entity you're updating has the Max Length attribute set.

May be you have used

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

On your dbcontext class in OnModelCreating. So change as per your length

For me, [MaxLength] didn't work. I have added below statement to the context.

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

I have not tried exceeding "4000" limit but I think it can be extended further. You don't have to keep it 128 as the error showed by compiler.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!