Max length not applied in migration

c# entity-framework-core sql-server

Question

I am using efcore.sqlserver 1.0.1 with preview2 tools - I have a string property which in sql server is created as an nvchar(max) field. When I add a data annotation stringlength(100) to the property and add a new migration the migration does not alter the column at all.

However if I add a Required and StringLength annotation then the generated migration alters the column and shows ( .. maxLength: 100, nullable: false )

Why does it only do this if I change the nullable value?

1
6
11/2/2016 8:07:59 PM

Accepted Answer

I believe you need to use MaxLengthAttribute instead of StringLengthAttribute.

https://docs.efproject.net/en/latest/modeling/max-length.html#data-annotations

This is probably because the StringLength attribute has an option for minimum length, which is not supported natively by SQL, and therefore the MaxLength attribute is a better fit for this use case.

Just to be clear, attributes have no effect in and of themselves. They can contain logic and information, but must be utilized via reflection from another piece of code during the normal execution model. This is with the exception of certain attributes which are given special meaning by the compiler, such as the Conditional attribute.

EDIT

The author found that this is a known issue for cases when the tool set has been upgraded from RC2 => RTM.

https://github.com/aspnet/Announcements/issues/195

6
11/2/2016 11:00:37 PM

Popular Answer

Fortunately there is no such issue on the EF core :) I have tested your scenario and it is working fine.

You have to use [MaxLength(100)] attribute for that.Here is the doc : MaxLength Data Annotations

Test case : I used MaxLength as 500 for my test.

Firstly I have created a property like this :

 public string Title { get; set; }

After migration :

enter image description here

After that I have changed it like this :

 [MaxLength(500)]
 public string Title { get; set; }

After migration :

enter image description here

Generated Script :

  migrationBuilder.AlterColumn<string>(
                name: "Title",
                table: "Posts",
                maxLength: 500,
                nullable: true);

Tested Tools version :

 <package id="Microsoft.EntityFrameworkCore.Tools"
 version="1.0.0-preview2-final" targetFramework="net461"
 developmentDependency="true" />


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow