Skip to content
Advertisement

C#: How to pass parmeterize values to System.Data.Entity.SqlSquery

I’m going to execute SQL query directly on database. I’ve define connection to my database using:

I don’t want to insert parameters directly to query string to avoid SQL Injection so I want to set parametrized values for my SQL query this way:

Running this query leads to excpetion "Must declare the table variable "@MappingTableName"."

How can I fix this?

Advertisement

Answer

Check this from Microsoft forums

Database objects (tables, stored procedures or any other objects) cannot be passed as parameters. Only actual values for columns or variables can be parameters. You need to build your SQL statement dynamically in this case

Which basically means that you have to provide and/or build the table name, under the danger that this can be compromised.

How to mitigate the risk. Declare a set of probable table name and do an exact match.

Then build your query with text concatenation. This is something that can’t be done with parameters cause you can’t expect the possible values, but can be done with tables because they are only so many. Be carefull to use Equals instead of Contains in your list of names.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement