我将直接在数据库上执行SQL查询。我已经使用:
定义了到数据库的连接System.Data.Entity.DbContext rawDbContext = new DbContext(connectionString);
我不想直接在查询字符串中插入参数以避免SQL注入,所以我想以这种方式为我的SQL查询设置参数化的值:
string sqlCommandString =
"IF EXISTS(select* from @MappingTableName where " + Environment.NewLine +
"BranchID= @PrimaryKeyID and " + Environment.NewLine +
"BranchNo = @BranchNo and " + Environment.NewLine +
"TableName = @TableName and " + Environment.NewLine +
"BranchSchema = @SchemaNameInBranch and " + Environment.NewLine +
"TableID = @TableID) " + Environment.NewLine +
" select 1" + Environment.NewLine +
"ELSE " + Environment.NewLine +
"select 0 " + Environment.NewLine;
SqlParameter parameterMappingTableName = new SqlParameter("@MappingTableName", vipMappingTableName);
SqlParameter parameterSchemaNameInBranch = new SqlParameter("@SchemaNameInBranch", schemaName);
SqlParameter parameterPrimaryKeyInBranch = new SqlParameter("@PrimaryKeyID", primaryNodeId);
SqlParameter parameterBranchNo = new SqlParameter("@BranchNo", branchNo);
SqlParameter parameterTableId = new SqlParameter("@TableID", tableId);
SqlParameter parameterTableName = new SqlParameter("@TableName", tableName);
DbRawSqlQuery<int> result = rawDbContext.Database.SqlQuery<int>(sqlCommandString,
new[] {
parameterMappingTableName,
parameterSchemaNameInBranch,
parameterPrimaryKeyInBranch,
parameterBranchNo,
parameterTableId,
parameterTableName
});
int finalResult = result.Single();
运行此查询会导致出现"Must declare the table variable \"@MappingTableName\"."
我该如何解决?
数据库对象(表,存储过程或任何其他对象)不能作为参数传递。仅列或列的实际值变量可以是参数。您需要构建您的SQL语句在这种情况下动态]
这基本上意味着您必须提供和/或构建表名,以免损害它的危险。
如何降低风险。声明一组可能的表名称并进行完全匹配。
然后使用文本串联构建查询。这是无法用参数完成的,因为您无法期望可能的值,但是可以使用表来完成,因为它们太多了。请谨慎使用名称列表中的Equals
而不是Contains
。