2

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. Yes, I had to resort to my own SQL injector.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.