Question

I'm trying to fix a problem in an ASP.NET application which uses DataContext.ExecuteQuery to execute sql statement. The query has this part:

LEFT OUTER JOIN dbo.Contacts ON dbo.Accounts.SalesRepId = dbo.Contacts.ContactId WHERE " + string.Join(" AND ", whereClauses) + @"

where "whereClauses" is a List of strings. This way, a search functionality is implemented into the query. Problem appears when an open search is run for a string like "O'Donnel" which obviously run query into an error. I have been asked to fix this problem. My approach was to substitute the where statement with "{0}" in the query and then pass it as a parameter in ExecuteQuery method. What I achieved is:

LEFT OUTER JOIN dbo.Contacts ON dbo.Accounts.SalesRepId = dbo.Contacts.ContactId {0}

var where = "WHERE 1=1";
_db.ExecuteQuery<AccountModel>(query, where)

but it doesn't work? When I substitute the whole where part with just a parameter for it everything is fine:

LEFT OUTER JOIN dbo.Contacts ON dbo.Accounts.SalesRepId = dbo.Contacts.ContactId WHERE 1={0}

var where = "1";
_db.ExecuteQuery<AccountModel>(query, where)

My question - is it then possible to inject the whole where statement dynamically into DataContext.ExecuteQuery method, or can I pass specific parameters only using this method?

Was it helpful?

Solution

Here's the help page for the ExecuteQuery method.

You can't pass the whole where clause as a parameter because a query like select * from myTable @param isn't valid SQL, whereas select * from myTable where myField = @param is valid SQL.

So, in answer to your specific question - no, you can't do this by passing parameters to ExecuteQuery.

However, why not build up the query in code before you pass it to ExecuteQuery?

e.g.

var query = "select * from myTable where 1=1" + string.Join(" AND ", whereClauses);
var result = _db.ExecuteQuery<AccountModel>(query);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top