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.
Entity Framework Core provides the DbSet. FromSql() method to execute raw SQL queries for the underlying database and get the results as entity objects.
Entity Framework Core allows you to drop down to SQL queries when working with a relational database.
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.
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).
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
Have you tried using the MaxLength attribute? This article gives a decent summary of how the various data annotation attributes are interpreted by EF.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With