efcore icon indicating copy to clipboard operation
efcore copied to clipboard

How can I override a MaxLength convention with an attribute?

Open kbaley opened this issue 3 years ago • 0 comments

Ask a question

I've define a convention in ConfigureConventions where all strings are to have a max length of 256. I'd like to override this for some properties, for example by setting the type to nvarchar(max) and setting [MaxLength(int.MaxValue)]. This correctly sets the column type but the maxLength is still 256.

If I set the max length in OnModelCreating, it works fine but I was wondering if there was a way to do it with the data annotations.

Include your code

DB Context

protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) {
    base.ConfigureConventions(configurationBuilder);

    configurationBuilder.Properties<string>()
        .HaveMaxLength(256);
}

Domain object

public class MyObject {
	// ...
    [Column(TypeName = "nvarchar(MAX)")]
    [MaxLength(int.MaxValue)]
    public string Notes { get; set; }
}

(Note: I also tried [StringLength(int.MaxValue)]

Resulting migration code:

    // ...
   Notes = table.Column<string>(type: "nvarchar(MAX)", maxLength: 256, nullable: false),
    // ...

Include provider and version information

EF Core version: 6.0.5 Database provider: Microsoft.EntityFrameworkCore.SqlServer 6.0.5 Target framework: .NET 6.0 Operating system: MacOS 12.3.1 IDE: VS Code 1.70.0

kbaley avatar Aug 10 '22 21:08 kbaley