How to insert an SQL literal as a query parameter in Dapper?

c# dapper

Question

I want to insert part of SQL statement as a parameter instead of concatenation to have it neat:

connection.Query(@"
    SELECT @Fields
    FROM Table
    WHERE ID = @Id
    ", new { Fields = "A, B", Id = 1});

I tried wrapping the parameter string in a custom class and mapping the class using Dapper

public class SqlString
{
    public readonly string Value;

    public SqlString(string sql)
    {
        Value = sql;
    }

    public override string ToString()
    {
        return Value;
    }
}

...

Dapper.SqlMapper.AddTypeMap(typeof(SqlString), System.Data.DbType.Object);

but to no avail.

Accepted Answer

You can't parameterize field names in T-SQL.

You will have to generate the dynamic SQL with your dynamic field names before you pass the sql string into the Connection.Query() method.



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