Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Essentially I have a table with zip codes in it. The zipcode field is defined as 'char(5)'. I'm using code first, so I've put these attributes on my ZipCode property:

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

Now if I query against this in EF:

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

The generated SQL uses nvarchar(4000) to inject the parameters. Huh? Is it because "12345" is technically a string of unknown length? Shouldn't EF be smart enough to just use the proper "nchar(5)" when querying that table?

I ask because the nvarchar(4000) query takes half a second whereas the properly-scoped query is much faster (and less reads).

Any assistance/advice would be appreciated.

like image 939
Nicholas Head Avatar asked Jun 30 '11 17:06

Nicholas Head


People also ask

Which of the following executes a raw SQL query in the database using EF core?

Entity Framework Core provides the DbSet. FromSql() method to execute raw SQL queries for the underlying database and get the results as entity objects.

What is EF code in SQL?

Entity Framework Core allows you to drop down to SQL queries when working with a relational database.

What's the difference between Nvarchar and varchar?

The key difference between varchar and nvarchar is the way they are stored, varchar is stored as regular 8-bit data(1 byte per character) and nvarchar stores data at 2 bytes per character. Due to this reason, nvarchar can hold upto 4000 characters and it takes double the space as SQL varchar.

What is the max length of Nvarchar in SQL?

nvarchar [ ( n | max ) ] n defines the string size in byte-pairs, and can be a value from 1 through 4,000. max indicates that the maximum storage size is 2^30-1 characters (2 GB).


2 Answers

This is to take advantage of auto parameterization. The following article explains the general concept as well as why specifically nvarchar(4000) is used.

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

like image 158
Robert Horvick Avatar answered Oct 11 '22 21:10

Robert Horvick


Have you tried using the MaxLength attribute? This article gives a decent summary of how the various data annotation attributes are interpreted by EF.

like image 44
Bobby D Avatar answered Oct 11 '22 21:10

Bobby D