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\"."

我该如何解决这个问题?

勾选这个from Microsoft forums

Database objects (tables, stored procedures or any other objects) cannot be passed as parameters. Only actual values for columns or variables can be parameters. You need to build your SQL statement dynamically in this case

这基本上意味着您必须提供 and/or 构建 table 名称,因为这可能会受到损害。

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

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