我一直在使用以下代码执行我的SQL查询,看起来像这样
SELECT abc.... FROM .... (many joins).. WHERE userid =" + userId + " AND UserState = " +userState ...; (Other parameters)
下面是我运行查询并返回数据表的方式
using (var context = new DbContext())
{
DataTable dt= new DataTable();
var conn = context.Database.Connection;
var connectionState = conn.State;
try
{
if (connectionState != ConnectionState.Open)
conn.Open();
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = buildveryLongQuery(userId,userState);
cmd.CommandType = CommandType.Text;
using (var reader = cmd.ExecuteReader())
{
if (reader.HasRows)
dt.Load(reader);
}
}
}
上面的方法工作正常,但提供了SQL注入。我该如何参数化它?
我尝试了以下方法:
已更改查询以使用@userId
IDbDataParameter personParam = cmd.CreateParameter();
personParam.DbType = DbType.Int32;
personParam.ParameterName = "@userId";
personParam.Value = userId;
但是我遇到了错误
必须声明标量变量\“ @ userId \