繁体   English   中英

C#:如何将参数化值传递给 System.Data.Entity.SqlSquery

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

我将直接在数据库上执行 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\\"."

我怎样才能解决这个问题?

从 Microsoft 论坛查看此内容

数据库对象(表、存储过程或任何其他对象)不能作为参数传递。 只有列或变量的实际值可以是参数。 在这种情况下,您需要动态构建 SQL 语句

这基本上意味着您必须提供和/或构建表名,否则可能会受到损害。

如何降低风险。 声明一组可能的表名并进行精确匹配。

然后使用文本连接构建您的查询。 这是使用参数无法完成的事情,因为您无法期望可能的值,但可以使用表来完成,因为它们只有这么多。 请小心在您的名称列表中使用Equals而不是Contains

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM