These functions give access to specialty functions (SqlClient) in SQL. For example 'like' or 'between'. And they also give a nicer common abstraction layer for them. Not to be confused with stored procedure(s) "functions" which is the topic of this other question.
My question that I can't seem to find a full answer for is. Are they safe to use, or am I opening the system to a SQL injection attack? I always use bound variables when writing regular SqlCommands.
But in moving to Entity Framework. There is less control over the SQL statements. I don't mind it, but I can't help worrying when I concatenate a string coming from a browser and pass it to a function.
Here is an example:
var QueryResult = EFContext.Table.Where(x =>
SqlFunctions.PatIndex("%" + Potentially_unsafe_search_keyword + "%",
x.Column) > 0);
I did some tests and traced the actual SQL sent to the server. Single quotes are escaped out automatically. So clearly there is some protection there. There is some sanitization taking place. Insert statements do use bind variables. Should I be content with the single quote replacement? Is there something else going on behind the scenes?
Every Constant, variable, parameter in Linq is passed as command parameter in IDbCommand, which in turn is escaped by underlying driver.
Unless there is a bug, all EF queries and SQL helper functions are safe against SQL injection attacks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With