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

I have an Entity Framework CodeFirst model that I am creating from an existing database and I want to decorate some char and varchar differently with DataAnnotations.

The difference between char and varchar is that char has a fixed length and varchar has a variable length.

For Varchar, I use [Maxlength (length)]. Is this the right way for char, or is there a better way to determine if the string property in the class is displayed as char in the database?

+4
source share
1 answer

With a quick 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();

Using annotations, you can specify the type:

[Column(TypeName = "char")]
[StringLength(2)]
public string MyCharField { get; set; }
+10

Source: https://habr.com/ru/post/1607194/


All Articles