Sean
Sean

Reputation: 15174

Force Entity Framework 6 (EF6) to use nvarchar(MAX)

I thought this would be easy, but...

How do you force EF6 to use nvarchar(MAX)?

I've tried:

[Column(TypeName = "nvarchar(MAX)")]

and

[Column(TypeName = "nvarchar")]
[MaxLength()]

and

modelBuilder.Entity<Date>().Property(o => o.test).HasColumnType("nvarchar(MAX)");

I'm using EF6.2.0 and SQL2014 Express

Upvotes: 9

Views: 26461

Answers (3)

Steve Ford
Steve Ford

Reputation: 7763

If you do not specify a length then EF Code First defaults to nvarchar(max), so if you specify a Name column:

public string Name { get; set; }

you will get an nvarchar(max) column.

If you need to specify a length, say 100 chars then you would specify the column in code:

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

If you need to specify varchar rather than nvarchar you would use this:

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

see Code First Conventions, Code First Data Annotations and Column Annotations

Upvotes: 20

Ogglas
Ogglas

Reputation: 70184

This is what worked for me in Entity Framework Core 5<

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

Generates the following migration:

migrationBuilder.AlterColumn<string>(
    name: "ImageBase64",
    table: "Medias",
    type: "nvarchar(MAX)",
    maxLength: 2147483647,
    nullable: true,
    oldClrType: typeof(string),
    oldType: "nvarchar(450)",
    oldMaxLength: 450,
    oldNullable: true);

MaxLength needed since we modify OnModelCreating to avoid nvarchar(MAX) for all string columns.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    foreach (var property in modelBuilder.Model.GetEntityTypes()
        .SelectMany(t => t.GetProperties())
        .Where(p => p.ClrType == typeof(string)))
    {
        if (property.GetMaxLength() == null)
            property.SetMaxLength(450);
    }

Upvotes: 4

Rao khurram adeel
Rao khurram adeel

Reputation: 626

Instead of typing it everywhere you can also set it by default to your required length. Override the function OnModelCreating in you dbcontext class

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    foreach (var property in modelBuilder.Model.GetEntityTypes()
        .SelectMany(t => t.GetProperties()).Where(p => p.ClrType == typeof(string)))
    {
        if (property.GetMaxLength() == null)
        {
            property.SetMaxLength(256);
        }

        if (string.IsNullOrEmpty(property.GetColumnType()))
        {
            property.SetColumnType("varchar");
        }
    }
}

Upvotes: 1

Related Questions