Code First Entity Framework: How to control varchar/nvarchar length in SQL Server
Posted: 5/12/2016 9:15:43 PM
By:
Times Read: 2,389
0 Dislikes: 0
Topic: Programming: .NET Framework

When using the code first option for Entity Framework, in order to control the length of varchar and nvarchar fields on the actual generated database, you can use one of the two approaches:

-- Example 1

Use the ColumnAttribute in order to specific datatype (varchar or nvarchar), followed by the StringLength attribute to control the length of the text (1 to 4000 are the allowed lengths.)

[Column(TypeName = "VARCHAR")] 

[StringLength(250)] public string SomeStringOfCharacters { get; set; }

Example 2: Using the Fluent API: (This is the best way, learn this syntax if you don't already know it.)

modelBuilder.Entity() .Property(e => e.SomeStringOfCharacters ).HasColumnType("VARCHAR").HasMaxLength(250);
Rating: (You must be logged in to vote)