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