Maximum length not applicable in migration

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

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

Why is this done only if I change the value with a null value?

+5
source share
2 answers

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 due to the fact that the StringLength attribute has a minimum length that is not supported by SQL, so the MaxLength attribute is better suited for this use case.

To be clear, attributes do not affect themselves. They may contain logic and information, but should be used by reflection from another part of the code during the normal execution model. This is with the exception of some attributes that the compiler gets special meaning, for example, the Conditional attribute.

EDIT

The author found that this is a known issue for cases where the toolbox has been updated with RC2 => RTM.

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

+4
source

Fortunately, there is no such problem in EF :) I tested your script and it works fine.

For this you need to use the [MaxLength(100)] attribute. Here is the document: MaxLength Data Annotations

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

First, I created a property similar to this:

  public string Title { get; set; } 

After migration:

enter image description here

After that, I changed it as follows:

  [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); 

Version of tested tools:

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

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


All Articles