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

dapper sql-server tsql

Question

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

Accepted Answer

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.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why