8

I have an Entity Framework CodeFirst model that I'm creating from existing Database and I want to decorate some char and varchar in different way using DataAnnotations.

Difference between char and varchar is that the Char has fixed length and varchar have variable length.

For Varchar I'm using [Maxlength(length)] For char is this the correct way or there is a better way to define that the string property in the class is mapped as a char in the Database?

JuanDYB
  • 590
  • 3
  • 9
  • 23

1 Answers1

23

With the fluent api you can use IsFixedLength():

//Set StudentName column size to 50 and change datatype to nchar 
//IsFixedLength() change datatype from nvarchar to nchar
  modelBuilder.Entity<Student>()
                    .Property(p => p.StudentName)
                    .HasMaxLength(50).IsFixedLength();

With annotations, you can dictate the type:

[Column(TypeName = "char")]
[StringLength(2)]
public string MyCharField { get; set; }
Steve Greene
  • 12,029
  • 1
  • 33
  • 54
  • 3
    `[StringLength]` is incorrect here. Should be `[MaxLength]` and this is a server-side validation. Refer to this post: https://stackoverflow.com/a/5717297/459102 and – Aaron Hudon Apr 09 '18 at 03:37
  • 1
    @AaronHudon Those annotations will create a fixed length CHAR(2) field in the database OP was asking for. It has the added benefit of client side validation. See the comment by Matt Johnson in your link. I can also attest it works for us. – Steve Greene Apr 09 '18 at 19:49
  • @AaronHudon @SteveGreene What matters is that you have `[Column(TypeName = "char")]` or `[Column(TypeName = "binary")]`. Without explicitly being specified, EF will default to a variable length type. If the type is specified to a fixed length type, then it will use either `MaxLength()` **or** `StringLength()` as the fixed length. So you both are sort of right. – binki Jul 06 '18 at 16:59