Home > Mobile >  How to specify max length string if I have a default already set?
How to specify max length string if I have a default already set?

Time:12-03

Normally I can specify .HasMaxLength(null) and this will result in a string column of maximum length (nvarchar(MAX)).

I think in fact this is actually the default, and if you don't specify a length then you get nvarchar(MAX).

However, it is possible to set a default using code like this:

DbModelBuilder.Properties<string>().Configure(config => config.HasMaxLength(50));

This will result in all string columns by default having nvarchar(50) (a max length of 50).

But then, this seems to prevent .HasMaxLength(null) from working, and I can no longer choose maximum length. I tried also saying .HasMaxLength(null).HasColumnType("nvarchar(MAX)") and this worked for generating the right column at the database level, but then I found that EF is still throwing an exception when my length exceeds 50 characters.

Is there a way around this, or will I have to go through and manually set most string columns back to .HasMaxLength(50) and forget about having a default length that is different from nvarchar(MAX)?

CodePudding user response:

I found that the solution here is to use the .IsMaxLength() method.

.IsMaxLength() is I guess the default, and says "use the maximum length" (nvarchar(MAX)).

.HasMaxLength(null) does not say to use the maximum length, it says to use the default length, and the default default length is the maximum length (the result of calling .IsMaxLength() which is nvarchar(MAX)).

  • Related