EF SqlQuery参数错误

时间:2015-07-04 18:11:25

标签: c# sql parameters

使用

string sql = @"
SELECT TOP 50 *
FROM Log 
ORDER BY Date desc";
return context.Database.SqlQuery<Log>(sql).ToList();

工作,但当我试图插入像

这样的参数时
string sql = @"
SELECT TOP @top *
FROM Log 
ORDER BY @order";

List<object> parameters = new List<object>();
parameters.Add(new SqlParameter("top", top)); //top is int with value 50
parameters.Add(new SqlParameter("order", order)); //order is string with value Date desc

return context.Database.SqlQuery<Log>(sql, parameters.ToArray()).ToList();

我得到了

  

“附加信息:'@ top'附近的语法不正确。”。

哪里错了?

1 个答案:

答案 0 :(得分:3)

按以下方式重新排列您的查询

string sql = @"
SELECT TOP (@top) *
FROM Log 
ORDER BY @order";

修改

string sql = @"
SELECT TOP @top *
FROM Log 
ORDER BY ";

sql += order;

List<object> parameters = new List<object>();
parameters.Add(new SqlParameter("top", top)); //top is int with value 50

return context.Database.SqlQuery<Log>(sql, parameters.ToArray()).ToList();