在Entity Framework中使原始SQL安全

时间:2016-04-29 15:43:05

标签: entity-framework entity-framework-6 sql-injection

var retval = db.TestTable.SqlQuery("SELECT * FROM dbo.TestTable WHERE " + aColumn + " = '" + passedInValue + "'");

// normally when using parameters I would do something like this:
var valueParam = SqlParameter("aValue", passedInValues);
var retval = db.TestTable.SqlQuery("SELECT * FROM dbo.TestTable WHERE Column1 = @aValue", valueParam);
// NOTE: I would not do this at all. I know to use LINQ. But for this question, I'm concentrating on the issue of passing variables to a raw sql string.

但由于列和值都是“参数”:

var retval = db.TestTable.SqlQuery("SELECT * FROM dbo.TestTable WHERE " + aColumn + " = '" + passedInValue + "'");

,是否可以防止sql注入?

2 个答案:

答案 0 :(得分:1)

首先:whilelist aColumn:这必须通过字符串连接添加,但您知道数据库中有哪些列(或者您可以使用模式视图进行检查)。

第二:在实体框架中 - 如您所示 - 您可以在查询中使用值的参数。但是,您可以传递值并使用SqlParameter@p0,...而不是创建@p1个实例。

答案 1 :(得分:0)

防止SQL注入的正确方法是使用SqlParameterSqlQuery<T>

var parameter = new SqlParameter("@title", value);
var result = context.Database.SqlQuery<Book>("SELECT * FROM Books WHERE Title LIKE @title", parameter);

http://ignoringthevoices.blogspot.ru/2013/07/sql-injection-with-entity-framework-5.html