繁体   English   中英

使用ObjectContext.ExecuteStoreQuery在SQL查询中参数化“ ORDER BY” <T> ()

[英]Parameterizing 'ORDER BY ' in SQL query with ObjectContext.ExecuteStoreQuery<T>()

我的问题在这个问题之上:

实体框架与原始字符串查询-SQL注入预防

在这种情况下,如何通过命令参数化限制和顺序?

非常感谢。

更新:

我尝试了这段代码,但它不起作用:

var filters = new StringBuilder();
var parameters = new List<object>();


decimal numRealPrice = 25.00m;
filters.Append("RealPrice = @RealPrice");
var paramRealPrice = new SqlParameter("@RealPrice", SqlDbType.Decimal);
paramRealPrice.Value = numRealPrice;
parameters.Add(paramRealPrice);


var paramSort = new SqlParameter("@field", SqlDbType.NVarChar);
paramSort.Value = "Id";
parameters.Add(paramSort);


string sqlStatement = "SELECT * FROM gift WHERE ";

sqlStatement = sqlStatement + filters + " ORDER BY @field DESC";

生成的SQL是:

exec sp_executesql N'SELECT * FROM gift WHERE RealPrice = @RealPrice ORDER BY @Id DESC',
N'@RealPrice decimal(4,2), @Id varchar(2)',
@RealPrice=25.00,
@Id='id'

go

错误消息是:

由ORDER BY数字1标识的SELECT项包含一个变量,作为表示列位置的表达式的一部分。 仅当通过引用列名的表达式进行排序时才允许使用变量。

您不能参数化ORDER BY子句。 因为您已经在C#中构造/组成查询,所以最有效的方法是简单地将该参数列入白名单并直接添加该子句:

string orderByField = "Id"; // or whatever

// whitelist the field
switch(orderByField) {
    case "Id":
    case "Name":
    ...
        break; // these are OK
    default:
        throw new InvalidOperationException("Illegal order clause: " + orderByField);
}

sqlStatement = sqlStatement + filters + " ORDER BY " + orderByField + " DESC";

它以与该问题答案完全相同的方式显示,但是您需要更改SQL以在其中包含用于OrderBy子句的case语句。

 SELECT * FROM gift 
    ORDER BY 
    CASE @dir 
        WHEN 'desc' THEN  
        CASE @col 
            WHEN 'id' THEN id
            END 
        END 
        DESC, 
    CASE @dir 
        WHEN 'asc' THEN              
        CASE @field 
            WHEN 'id' THEN id 
            END 
        END 

然后将参数插入为

var param = new SqlParameter("@field", SqlDbType.NVarChar);
param.Value = name;
parameters.Add(param);

然后再在这里确定方向

var param = new SqlParameter("@dir", SqlDbType.NVarChar);
param.Value = 'desc'; // or 'asc'
parameters.Add(param);

暂无
暂无

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

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