Search code examples
sql-serverentity-frameworkef-code-first

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


Solution

  • 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