如何在Dapper查询中转义“ @”? [英] How do I escape a '@' in a Dapper query?

查看:200
本文介绍了如何在Dapper查询中转义“ @”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个查询,查询中的符号应为( @ )。如何用Dapper查询表达这一点?

I've got a query that should contain a literal at sign (@). How do I express this with a Dapper query?

var num = cnx.Query<int>("declare @foo int = 2; select @foo").Single();

我尝试使用文字作为解决方法:

I've tried using literals as a workaround:

var num = cnx.Query<int>(
    "declare {=at}foo int = 2; select {=at}foo", new { at = "@" }
).Single();

但这会引发 NotSupportedException ,因为字符串文字不支持...

But this throws a NotSupportedException since string literals aren't supported...

(请注意,在我的真实代码中,我确实想替换其他@parameters并为我自动转义,因此,我宁愿尽可能使用Dapper,而不仅仅是使用原始的 SqlCommand 。)

(Note that in my real code, I've got other @parameters that I actually do want replaced and auto-escaped for me, so I'd rather stick with Dapper if possible instead of just using a raw SqlCommand.)

推荐答案

哦。我想到了。如果您的 @param 实际上没有绑定任何内容,则会将其原样传递给基础 SqlCommand ,直接将其传递给数据库。

Oh. I figured it out. If you have a @param that isn't actually bound to anything, it's passed as-is to the underlying SqlCommand, which passes it straight to the DB.

换句话说,您无需执行任何特殊操作即可使其工作。我的第一个示例应该运行良好。愚蠢的我。

In other words, you don't need to do anything special to get this to work. My first example should run fine. Silly me.

这篇关于如何在Dapper查询中转义“ @”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆