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

徘徊边缘 提交于 2019-12-18 05:56:31

问题


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.


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/6538746/why-does-code-first-ef-use-nvarchar4000-for-strings-in-the-raw-sql-command

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!