Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity framework SqlQuery execute query with repeated parameter

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.

like image 243
Juan Paredes Avatar asked Jan 18 '26 05:01

Juan Paredes


2 Answers

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();
like image 181
serefbilge Avatar answered Jan 19 '26 18:01

serefbilge


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();
like image 30
Jurica Smircic Avatar answered Jan 19 '26 18:01

Jurica Smircic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!