DataAnnotation for fixedLength in Entity Framework Core on .NET 6

Viewed 248

I'm using .NET 6 and EF Core with code-first approach.

public class MyObj 
{
    [MaxLength(7)]
    public string MyField { get; set; }
}

With [MaxLength(7)] I can create a migration with the maxLength parameter:

table.Column<string>(type: "TEXT", maxLength: 7, nullable: false)

I also want to say to EF Core that MyField is made up of at least 7 characters => fixed length.

Some questions:

  1. Is there a DataAnnotation attribute for fixedLength like [MaxLength(7)] for max length?
  2. How does knowing that a string has a fixed length affect the database?

Edit:

@Steve in a comment under this question propose [Column(TypeName="Char(7)")] that produce

table.Column<string>(type: "Char(7)", nullable: false),

In this case with "Char(7)" I'm directly use a SQL keyword, right?

So, in my case it works, but as I saw there, EF Core can also work with NoSQL database; will "Char(7)" be a problem in that case?

2 Answers

use StringLength

  [StringLength(7, ErrorMessage = "The MyField value cannot exceed 7 characters. ")]
  public string MyField { get; set; }

maybe you can use both MinLengh attribute and MaxLengh Attribute to achieve the result you're after

MinLength

Related