How do I escape a '@' in a Dapper query?

和自甴很熟 提交于 2019-12-10 13:46:00

问题


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();

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

(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.)


回答1:


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.



来源:https://stackoverflow.com/questions/24897030/how-do-i-escape-a-in-a-dapper-query

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