Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass Table Name as Parameter to Dapper

Tags:

dapper

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 });
like image 1000
bigmac Avatar asked Jul 29 '14 14:07

bigmac


People also ask

How do you pass parameters in dapper?

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.

What is Dynamicparameters?

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.

How does dapper prevent SQL injection?

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.

Is Dapper case sensitive?

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.


2 Answers

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.

like image 62
Marc Gravell Avatar answered Sep 20 '22 14:09

Marc Gravell


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);                    
}
like image 25
user841657 Avatar answered Sep 20 '22 14:09

user841657