C# C:如何将参数化值传递给System.Data.Entity.SqlSquery
我将直接在数据库上执行SQL查询。 我已使用以下方法定义与数据库的连接:C# C:如何将参数化值传递给System.Data.Entity.SqlSquery,c#,sql,entity-framework,dbcontext,parameterized,C#,Sql,Entity Framework,Dbcontext,Parameterized,我将直接在数据库上执行SQL查询。 我已使用以下方法定义与数据库的连接: System.Data.Entity.DbContext rawDbContext = new DbContext(connectionString); 我不想直接向查询字符串插入参数以避免SQL注入,因此我想通过以下方式为我的SQL查询设置参数化值: string sqlCommandString = "IF EXISTS(select* from @MappingTableName where " +
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();
运行此查询导致excpetion必须声明表变量\@MappingTableName\
如何修复此问题?检查此问题
数据库对象表、存储过程或任何其他对象
无法作为参数传递。仅列或列的实际值
变量可以是参数。您需要构建SQL语句
在这种情况下是动态的
这基本上意味着您必须提供和/或构建表名,这可能会造成危害
如何降低风险。声明一组可能的表名并进行精确匹配
然后使用文本连接构建查询。这是不能用参数来完成的,因为您不能期望可能的值,但可以用表来完成,因为它们只有这么多。请小心在名称列表中使用Equals而不是Contains。不能使用参数表示表名,也不能使用字段name@Steve你知道这是什么原因吗?此外,您知道如何检查将在DB上执行的已编译查询吗?@VSB如果您使用Microsoft SQL Server或其他RDBMS的类似工具,则可以使用SQL事件探查器检查将在DB上执行的查询。例如,检查这有一个例子,如何通过tvp