1

I need to save a string with a length larger than 2000 characters, but the Entity Framework validation "hangs" the string size in 2000 and returns me error message:

The Value field must be a string or array type with maximum length of '2000'.

In the database the field is VARCHAR (8000) and in the entity is defined MaxLength of 8000

Model

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"));
    }
9
  • 1
    Could you provide more code? The Model that you're using. Commented Jul 25, 2018 at 15:09
  • Have you tried applying the max length attribute to the data objects property? Commented Jul 25, 2018 at 15:10
  • 2
    Is it possible that you created EF model when your DB field size was 2000, then increased column size without updating EF model? Commented Jul 25, 2018 at 15:18
  • from the beginning the entity is with MaxLength defined in 8000, I am using code first Commented Jul 25, 2018 at 15:25
  • Could you provide more code? Commented Jul 25, 2018 at 15:30

1 Answer 1

1

Try using '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 is a data annotation that will be used for validation of user input.

From MSDN: Specifies the minimum and maximum length of characters that are allowed in a data field

MaxLength is used for the Entity Framework to decide how large to make a string value field when it creates the database.

From MSDN: Specifies the maximum length of array or string data allowed in a property.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.