I am trying to create an MVC Razor Webpage on C# an in order to display some content I am trying to get some data from a SQL Table.
I am trying to create a SQL command that I can add parameters to in order to prevent SQL Injection attacks.
string cmdClientAccess = "SELECT * FROM @Table WHERE [User] = '@User'";
int i = 0;
foreach (var client in Clients) {
using (SqlConnection sConnection = new SqlConnection(SqlConnectionString))
{
SqlCommand sUserAccess = new SqlCommand(cmdClientAccess);
sUserAccess.Parameters.AddWithValue("@Table", ClientUserTables[i]);
sUserAccess.Parameters.AddWithValue("@User", AccessingUser);
sConnection.Open();
using (SqlDataReader SDReader = sUserAccess.ExecuteReader())
{
while (SDReader.Read())
{
if (SDReader["Requirement2"].ToString() != "")
{
List1.Add(client);
}
if (SDReader["Requirement2"].ToString() == "Yes")
{
List2.Add(client);
}
}
}
sConnection.Close();
}
i++;
}
The problem is that as soon as the program reaches this line:
using (SqlDataReader SDReader = sUserAccess.ExecuteReader())
Visual Studio gives the following message:
System.InvalidOperationException: 'ExecuteReader: Connection property has not been initialized.'