问题描述
本质上我有一个表格,其中包含邮政编码。邮政编码字段定义为char(5)。我正在使用代码,所以我把这些属性放在我的ZipCode属性上:
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; }
现在,如果我在EF中查询这个:
Now if I query against this in EF:
var zc = db.ZipCodes.FirstOrDefault(zip => zip.ZipCode == "12345");
生成的SQL使用nvarchar(4000)注入参数。咦?是因为12345在技术上是长度不明的字符串?请问EF是否足够聪明才能在查询该表时使用正确的nchar(5)?
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?
我问,因为nvarchar(4000)查询需要一半第二,而正确范围的查询要快得多(读取更少)。
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.
推荐答案
这是利用自动参数化。以下文章解释了一般概念以及为什么特别使用nvarchar(4000)。
This is to take advantage of auto parameterization. The following article explains the general concept as well as why specifically nvarchar(4000) is used.
这篇关于为什么代码第一/ EF在原始SQL命令中的字符串使用'nvarchar(4000)'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!