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

只愿长相守 提交于 2019-12-01 19:13:01

问题


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?


回答1:


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; }


来源:https://stackoverflow.com/questions/32554420/entity-framework-code-first-maxlength-and-fixedlegth-char-vs-varchar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!