Why does the first / EF code use "nvarchar (4000)" for strings in the original SQL command?

Essentially, I have a table with zip codes. The zipcode field is defined as "char (5)". I use the code first, so I put these attributes in my ZipCode property:

[Key, Column( Order = 0, TypeName = "nchar"), StringLength(5)] public string ZipCode { get; set; } 

Now, if I ask about this in EF:

 var zc = db.ZipCodes.FirstOrDefault(zip => zip.ZipCode == "12345"); 

Generated SQL uses nvarchar (4000) to enter parameters. A? Is it because "12345" is technically a string of unknown length? Should EF be smart enough to just use the proper "nchar (5)" when querying this table?

I ask because the nvarchar (4000) request takes half a second, while the request with the correct scope is much faster (and less read).

Any help / advice would be appreciated.

+6
source share
2 answers

This is the use of automatic parameterization. The following article explains the general concept, as well as why nvarchar (4000) is used.

http://msdn.microsoft.com/en-us/magazine/ee236412.aspx

+2
source

Have you tried to use the MaxLength attribute? This article provides a worthy summary of how the various attributes of data annotation are interpreted by EF.

+1
source

Source: https://habr.com/ru/post/891747/


All Articles