使用 Dapper 在 SQL 语句中参数化 LIKE 子句
我想使用 Dapper 执行以下查询,它当前不会返回预期结果(我认为它必须将 @pName 参数视为单引号内的文字文本?):
var q = "SELECT * FROM Users WHERE Name LIKE '@pName%'";
@pName 是我为其分配值的参数执行查询。
如果我只是构建这样的 SQL,事情就可以了:
var q = "SELECT * FROM Users WHERE Name LIKE '" + name + "%'";
.. 但如果可能的话,我更愿意使用参数。
我正在使用以下代码执行查询:
o = _cn.Query<User>(q, new { pName = new DbString { Value = name, IsFixedLength = false, Length = 25, IsAnsi = true } }).ToList();
How do I get about this using Dapper?
I want to perform the following query using Dapper, which currently doesn't return expected results (I think it must be treating the @pName param as literal text within the single quotes?):
var q = "SELECT * FROM Users WHERE Name LIKE '@pName%'";
@pName is the param I assign a value to upon executing the query.
Things work if I just build the SQL like:
var q = "SELECT * FROM Users WHERE Name LIKE '" + name + "%'";
.. but I would prefer to use a param if possible.
I am executing the query using the following code:
o = _cn.Query<User>(q, new { pName = new DbString { Value = name, IsFixedLength = false, Length = 25, IsAnsi = true } }).ToList();
How do I got about this using Dapper?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想在这里添加另一个可能的解决方案:
通配符位于字符串 var 本身内部,然后我们在 SQL 中引用该 var。适用于您想要的任何通配符模式。
I would like to add here another possible solution:
The wildcard is inside the string var itself, and then we reference that var in the SQL. Applies to any wildcard pattern you want.