3

I'm having troubles trying to execute a SQL query with repeated parameters using entity framework.

The query is a keyword search, that looks in different tables, therefore using the same parameter many times. I'm using LIKE statements (yes, I know I should be using FULLTEXTSEARCH, but I don't have time for that right now).

I've tried all the syntax explained here: How to use DbContext.Database.SqlQuery<TElement>(sql, params) with stored procedure? EF Code First CTP5 and none of them make the query work (I get zero returned rows).

I even tried building a string array in runtime, with length equal to the number of times the parameter repeats in the query, and then populating all the elements of the array with the keyword search term. Then I passed that as the object[] parameters. Didn't work either.

The only thing that works is to make a search&replace that is obviously a bad idea because the parameter comes from a text input, and I'll be vulnerable to SQL injection attacks.

The working code (vulnerable to SQL injection attacks, but the query returns rows):

//not the real query, but just for you to have an idea
string query =
    "SELECT Field1, " +
    "       Field2 " +
    "FROM   Table1 " +
    "WHERE  UPPER(Field1) LIKE '%{0}%' " +
    "OR     UPPER(Field2) LIKE '%{0}%'";

//keywordSearchTerms is NOT sanitized
query = query.Replace("{0}", keywordSearchTerms.ToUpper());

List<ProjectViewModel> list = null;
using (var context = new MyContext())
{
    list = context.Database.SqlQuery<ProjectViewModel>(query, new object[] { }).ToList();
}
return list;

I'm using ASP.NET MVC 4, .NET 4.5, SQL Server 2008 and Entity Framework 5.

Any thoughts on how to make the SQLQuery<> method populate all the occurrences of the parameter in the query string? Thank you very much for your time.

3 Answers 3

6

Try this:

string query =
    @"SELECT Field1,
          Field2 FROM Table1
      WHERE UPPER(Field1) LIKE '%' + @searchTerm + '%'
      OR UPPER(Field2) LIKE '%' + @searchTerm + '%'";
 
context
    .SqlQuery<ProjectViewModel>(query, new SqlParameter("@searchTerm", searchTerm))
    .ToList();
Sign up to request clarification or add additional context in comments.

Comments

1

You can use parameters in your query. Something like this

string query =
 "SELECT Field1, " +
 "       Field2 " +
 "FROM   Table1 " +
 "WHERE  UPPER(Field1) LIKE @searchTerm" +
 "OR     UPPER(Field2) LIKE @searchTerm";

        string search= string.Format("%{0}%", keywordSearchTerms);

        context.SqlQuery<ProjectViewModel>(query, new SqlParameter("@searchTerm", search)).ToList();

1 Comment

I tried this. It throws a SqlException: Must declare the scalar variable "@searchTerm". Thanks for the suggestion.
-2

how about try this

string query =
string.Format("SELECT Field1, Field2 FROM   Table1 WHERE  UPPER(Field1) LIKE '%{0}%' 
OR     UPPER(Field2) LIKE '%{0}%'",keywordSearchTerms.ToUpper());

context. Database.SqlQuery< ProjectViewModel >(query)

5 Comments

I also tried this. In fact, I think it was one of my first attemps. It doesn't throw an exception, but the query returns zero results. Thanks.
Did you try to use the query in SQL Management Studio?
what's your keywordSearchTerms? is it a single word? or multiple words?
The query works. When I use search&replace on the query string, the method gives back results for certain searches I have prepared for testing. It also works on SQL Management studio. So is not the query that is wrong. What I think the problem is that the SqlQuery<T>(query, params) method does not substitute the parameter placeholders in the query string with the sanitized value. Finally I don't think is relevant the value of the keywordSearchTerms. The LIKE operator works with strings, regardless of single or multiple words, as far as I know. Thanks for your time.
Since you're using string.Format to do the parameter replacement instead of SqlParameter, isn't this method susceptible to SQL injection?

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.