Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
986 views
in Technique[技术] by (71.8m points)

entity framework - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...