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