12

I would like to use code first to generate my SQL Server 2014 database. The table columns get generated as nvarchar(MAX) but I want the strings to get generated as varchar(50).

Things I tried in my model:

    [MaxLength(50)]
    public string Name { get; set; }


    [Required]
    [Column(TypeName = "varchar(50)")]
    public string Name { get; set; }


    [Required]
    [MaxLength(50)]
    [Column(TypeName = "varchar(50)")]
    public string FName { get; set; }

This gets generated in the migration as:

Name = table.Column<string>(maxLength: 50, nullable: false)

When using the "dotnet ef database update" the the columns get created as nvarchar(MAX).

I'm using references:

Microsoft.VisualStudio.Web.CodeGeneration.Tools Version="2.0.2" Microsoft.EntityFrameworkCore.Tools.DotNet Version="2.0.1"

3 Answers 3

10

It is working now with [Column(TypeName = "varchar(50)")].

I think when I deleted the database tables and deleted the migration from the migrations table using SSMS, it was not actually deleting the tables so it appeared that they were getting created the same way as before with the nvarchar(MAX) when I refreshed the tables folder in SSMS.

So [Column(TypeName = "varchar(50)")] works fine.

9

Had the same issue but I'm using Fluent API for configuration. So, if you'd be willing to use Fluent to configure your model then:

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder
            .Entity<MyEntity>()
            .Property(x => x.Name)
            .HasMaxLength(50)
            .IsUnicode(false);
    }

As EF now knows you don't need Unicode it'll use VARCHAR instead of NVCHAR. This combined with HasMaxLength will result in your desired VARCHAR(50).

2

While this is not for the requested version, starting with EF Core 6, there is a dedicated option for specifying VARCHAR vs NVARCHAR as a column type with the [Unicode(false)] decoration.

Then you can separate out the length and column type definitions:

    [Unicode(false)]
    [MaxLength(50)]
    public string Name { get; set; }

A value of true is the default and will define NVARCHAR in SQL while false will set it to VARCHAR. This setting will properly apply the correct column names for any supported database or ignore it for database types that do not use it.

see: https://learn.microsoft.com/en-us/ef/core/modeling/entity-properties?tabs=data-annotations%2Cwithout-nrt#unicode

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.