6

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)

4
  • 3
    As long as your nvarchar column is less than 4000 characters (2 bytes each) - SQL Server will use the nvarchar(n) type. The upper limit is 4000 characters - if you specify a length greater than that, there's no alternative but to use nvarchar(max) (which supports up to 1 billion characters)
    – marc_s
    Aug 27, 2015 at 13:21
  • @marc_s That seems ridiculous (I know it's not your fault; I'm just responding to your comment). There's a HUGE amount of space between 4000 and 2^31 - 1. Why can't I specify 8192 or something? I'm wondering if there's a technical reason for it, or if they just decided, "if you need more than 4000 (which is itself arbitrary), then max will just have to do".
    – Ari Roth
    Jul 11, 2017 at 20:21
  • 2
    @AriRoth: the physical storage in SQL Server is organized in pages which are 8K (8192 bytes). Since nvarchar always uses 2 bytes per character, and each page has a few header bytes, you basically get 8000 bytes (or 4000 nvarchar characters) on a single page - at most. Therefore, the "normal" nvarchar(n) is limited to a max. of 4000 chars (the non-Unicode varchar(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
    – marc_s
    Jul 11, 2017 at 20:26
  • @marc_s Oh yeah, I forgot about the 8k page size. It just seems weird to me that nvarchar basically says "You can limit the field size to 8k, but after that you're just going to have to use max". I mean, this seems like a solvable problem, and I imagine there are plenty of cases where you'd want to limit the field size to more than 4000 characters and less than max. But I'm not a DB admin or anything, so maybe it's not as solvable as it seems it would be to me. :)
    – Ari Roth
    Jul 11, 2017 at 23:10

1 Answer 1

7

I think it's SQL Server limits. msdn says

Variable-length Unicode string data. n defines the string length and can be a value from 1 through 4,000.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.