Entity Framework Code First MaxLength and FixedLegth (char vs varchar)

10,673

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; }
Share:
10,673
JuanDYB
Author by

JuanDYB

Updated on July 28, 2022

Comments

  • JuanDYB
    JuanDYB almost 2 years

    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?

  • Aaron Hudon
    Aaron Hudon about 6 years
    [StringLength] is incorrect here. Should be [MaxLength] and this is a server-side validation. Refer to this post: stackoverflow.com/a/5717297/459102 and
  • Steve Greene
    Steve Greene about 6 years
    @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.
  • binki
    binki almost 6 years
    @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.