0

I need to know the correct way to handle SQL Injection when using the FromSQL command.

At runtime, I need to dynamically create a where statement. So I am using FromSql to create the SQL command. Now I know that using use string interpolation is the way to go. However, I need to step through a list of "Where Parameters" to generate the command. Simple enough to do;

foreach (var x in wp)
{
    if (!string.IsNullOrEmpty(results))
        results = $"{results} and {x.Field} = {x.Value}";
    if (string.IsNullOrEmpty(results))
       results = $"where {x.Field} = {x.Value}";
}

Problem is that this return a simple string and would not be string interpolation. How can I do this correctly?

2 Answers 2

1

Entityframework will parameterize your queries if you put it in the following format:

db.something.FromSql("SELECT * FROM yourTable WHERE AuthorId = {0}", id)

Is x.Field a form field that has a fixed number of possibilities? i.e. title, firstname etc. If so then something like the following:

        var sqlstring = new StringBuilder();
        var sqlp = new List<SqlParameter>();

        var i = 0;
        foreach (var x in wp)
        {
            var param = "@param" + i.ToString();
            if (i!=0)
            {
                sqlstring.Append($" AND {x.Field} = " + param);
                sqlp.Add(new SqlParameter(param, x.Value));
            }
            if (i==0)
            {
                sqlstring.Append($"WHERE {x.Field} = " + " @param" + i.ToString());
                sqlp.Add(new SqlParameter(param, x.Value));
            }
            i++;
        }

You'd then need to do something like this:

db.something.FromSql(sqlstring.ToString(), sqlp.ToArray())

Might be a better/cleaner way but that should work.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I basically came up with your solution just without the StringBuilder. The problem was that the IDE actually gave a SQL injection warning. Your solution does not
1

My solution to this problem is a VS extension, QueryFirst. QueryFirst generates a C# wrapper for sql that lives in a .sql file. As such, parameters are the only way to get data into your query and SQL injection is near impossible. There are numerous other advantages: you edit your sql in a real environment, it's constantly validated against your db, and using your query in your code is very simple.

1 Comment

I have moved from this problem but that looks exactly like what I wanted. Hope I can circle back and use this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.