Is it possible to pass in the table name as a parameter to a Dapper Query command? I'm not looking for a SQL table defined function or a SQL table variable. I want to define the table name within C# and pass it to Dapper. Here's my code, that when executed, returns an error of Must declare the table variable "@TableName"
var foo = conn.Query("SELECT * FROM @TableName WHERE Id = @Id", new { TableName = "MyTable", Id = 123 });
Parameter values can be passed to commands as anonymous types: var parameters = new { UserName = username, Password = password }; var sql = "select * from users where username = @UserName and password = @Password"; var result = connection.
Parameter. Dynamic parameters are special types of parameters. Dynamic parameter value is recalculated each time you assess the parameter; i.e., this parameter acts as a function.
It's Prevent SQL Injection from external user input by avoiding raw-SQL query string building. Dapper provides methods to build parameterized queries as well as passing sanitized parameters to stored procedures. Dapper has provided multiple methods to Query or execute the store procedures and SQL queries.
Dapper's(SqlMapper) Query method over the Connection factory runs the SQL query, then maps the database result to Employee class and returns as a list of employees. Note : Only matching class and table properties are mapped to list of employee, they are case sensitive.
SQL does not support parameterized table names, and dapper is a very very thin wrapper over SQL - so: no.
You could, however, use string.format:
string sql = string.Format("... from [{0}] ...", table name);
Note that even with the [/] this has an inherent SQL injection risk.
You could check to see if the table exists first to protect from Sql injection:
string tableNameExistsCheck = "SELECT count(1) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = @tableName";
if (c.QuerySingle<int>(tableNameExistsCheck, new { tableName }) == 1)
{
string sql = string.Format("... from [{0}] ...", tableName);
var result = c.Query(sql);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With