我使用EF 4执行字符串查询:
string query = "SELECT * FROM Table WHERE ....";
[+ build WHERE clausule based on the user's input values]
db.ExecuteStoreQuery<TAble>(query).ToList();
我想知道如何在taht WHERE clausule中阻止来自SQL注入的查询。有什么想法吗?
答案 0 :(得分:5)
您需要使用参数化查询:
// Build where clause
var filters = new StringBuilder();
var parameters = new List<object>();
if (!string.IsNullOrEmpty(name))
{
if (filters.Length > 0)
filters.Append(" AND ");
filters.Append("name = @name");
var param = new SqlParameter("@name", SqlDbType.NVarChar);
param.Value = name;
parameters.Add(param);
}
...
// Build query
string query = "SELECT * FROM Table";
if (filters.Length > 0)
query = query + " WHERE " + filters;
// Execute
db.ExecuteStoreQuery<TAble>(query, parameters.ToArray()).ToList();
答案 1 :(得分:1)
您将以与构建SqlCommand
时相同的方式阻止它。您将使查询参数化,您将过去的参数集合作为ExecuteStoreQuery
方法的第二个参数(如果您只传递值,EF将为您创建参数,但您必须按照查询中的正确顺序传递它们)