Dapper是否支持like运算符? [英] Does Dapper support the like operator?
问题描述
使用Dapper-dot-net ...
Using Dapper-dot-net...
以下在数据对象中不会产生任何结果:
The following yields no results in the data object:
var data = conn.Query(@"
select top 25
Term as Label,
Type,
ID
from SearchTerms
WHERE Term like '%@T%'",
new { T = (string)term });
但是,当我只使用常规字符串格式,如:
However, when I just use a regular String Format like:
string QueryString = String.Format("select top 25 Term as Label, Type, ID from SearchTerms WHERE Term like '%{0}%'", term);
var data = conn.Query(QueryString);
我在集合中得到了25行。 Dapper是否无法正确解析参数 @T
的结尾?
I get 25 rows back in the collection. Is Dapper not correctly parsing the end of the parameter @T
?
推荐答案
尝试:
term = "whateverterm";
var encodeForLike = term => term.Replace("[", "[[]").Replace("%", "[%]");
string term = "%" + encodeForLike(term) + "%";
var data = conn.Query(@"
select top 25
Term as Label,
Type,
ID
from SearchTerms
WHERE Term like @term",
new { term });
类似运算符没有什么特别的,您永远不要将参数放在字符串文字中,它们将无法工作,而是将它们解释为字符串。
There is nothing special about like operators, you never want your params inside string literals, they will not work, instead they will be interpreted as a string.
注意
强烈建议您不要在第二个代码段中使用代码编码的示例,除了这是sql注入的巨大问题之外,它还可能导致dapper泄漏。
The hard-coded example in your second snippet is strongly discouraged, besides being a huge problem with sql injection, it can cause dapper to leak.
凹腔
任何喜欢
以通配符开头的匹配项不可SARGable,这意味着它很慢,需要进行索引扫描。
Any like
match that is leading with a wildcard is not SARGable, which means it is slow and will require an index scan.
这篇关于Dapper是否支持like运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!