0

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?

4

1 に答える 1

0

メソッドヘルプ ページは次のExecuteQueryとおりです。

のようなクエリは有効な SQL ではありませんが、有効な SQL であるため、where 句全体をパラメーターとして渡すことできません。select * from myTable @paramselect * from myTable where myField = @param

したがって、特定の質問への回答として-いいえ、パラメーターをに渡すことでこれを行うことはできませんExecuteQuery

ただし、クエリを に渡す前に、コードでクエリを作成してみませんExecuteQueryか?

例えば

var query = "select * from myTable where 1=1" + string.Join(" AND ", whereClauses);
var result = _db.ExecuteQuery<AccountModel>(query);
于 2014-02-12T09:27:40.683 に答える