I have specified a text field's MaxLength
as 4096 with EF fluent api in order to limit its length:
this.Property(p => p.MyText).HasMaxLength(4096).IsRequired();
But for some reason in SQL Server, the column becomes nvarchar (max)
.
Just for test if I specify 2048 to make sure that SQL Server gets updated
this.Property(p => p.MyText).HasMaxLength(2048).IsRequired();
And this way it is works.
So my queston why EF sets sql nvarchar (max)
when MaxLength(4096)
nvarchar
column is less than 4000 characters (2 bytes each) - SQL Server will use thenvarchar(n)
type. The upper limit is 4000 characters - if you specify a length greater than that, there's no alternative but to usenvarchar(max)
(which supports up to 1 billion characters)nvarchar
always uses 2 bytes per character, and each page has a few header bytes, you basically get 8000 bytes (or 4000nvarchar
characters) on a single page - at most. Therefore, the "normal"nvarchar(n)
is limited to a max. of 4000 chars (the non-Unicodevarchar(n)
is limited to 8000 chars). If you need more, then you get a total of 2 GB of storage through pretty elaborate (and complicated) structures of using 8K pages to store all that data