When I examine the sql query the linq spits out, I noticed that it places a ESCAPE N\'~\' when doing a LIKE command. How do I get rid of this? It seems like the query take
Apparently,
var SearchPhrase = "xyz";
var result = (from I in db.myTabl
where i.col1.contains(SearchPhrase)
select I).toList();
will add ESCAPE N'~' in the underlying query.
However using a constant filter like the following, doesn't produce escape characters in the underlying query
var result = (from I in db.myTabl
where i.col1.contains("xyz")
select I).toList();
Which means, variable filters are escaped, while constants are not.
So, in this case, we need a variable to be used as a constant filter.
Using the following, shouldn't add any escape characters:
var SearchPhrase = "xyz";
var result = (from I in db.myTabl
where SqlMethods.Like(i.col1, string.Format("%{0}%", SearchPhrase))
select I).toList();
but this works only with LINQ to SQL.
The other alternative is to embed the variable value as a constant, which is done using the following as explained in the SO article
If you use LINQ 2 Entities, use SqlQuery to remove the "~" character.
Just append the value to compare like an ordinary sql query.
For example:
var resultList = context.TableName.SqlQuery(
"SELECT * FROM TableName WHERE field LIKE '%" + fieldValue+ "%' ").ToList();
Linq to Sql use '`' as it's default escape character when doing like comparisons. It will only cause a problem if your string actually contains ~ characters.
Use SqlMethods.Like to override this.