Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create varchar using Entity Framework Core 2 Code First

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"

like image 517
forwheeler Avatar asked Feb 01 '18 22:02

forwheeler


2 Answers

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.

like image 56
forwheeler Avatar answered Sep 25 '22 01:09

forwheeler


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).

like image 43
Martin Avatar answered Sep 26 '22 01:09

Martin