C # safely build SQL string to execute using Entity Framework

I am executing some SQL using EF with the command .SqlQuery(string sql) .

I want my sql string to be completely sanitized, so the logical approach was to use a SqlCommand object with parameters to create it.

However, I do not want to execute it with SqlCommand, I just want SqlCommand to spit out a string that I can connect to my EF .SqlQuery(...) call.

Is there a way to do this, or another way to ensure my .SqlQuery won't lead to an injection?

+6
source share
2 answers

Does EF support this out of the box?

You should be able to call SqlQuery with parameters, so it will take care of SQL injection, etc., just like SqlCommand does:

 var tests = context.Database.SqlQuery<Test>( @"SELECT Id, Name FROM tests where Name={0}", "TestName"); 

or..

 var tests = context.Database.SqlQuery<Test>( @"SELECT Id, Name FROM tests where Name=@name ", new SqlParameter("@name", "TestName")); 
+12
source

Get the CommandText property for SqlCommand.

 string query = cmd.CommandText; foreach (SqlParameter p in cmd.Parameters) { query = query.Replace(p.ParameterName, p.Value.ToString()); } 
0
source

Source: https://habr.com/ru/post/950276/


All Articles