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?
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
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 :
After that I have changed it like this :
[MaxLength(500)]
public string Title { get; set; }
After migration :
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" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With