LINQ inserts 'ESCAPE N'~' in query

后端 未结 3 1364
谎友^
谎友^ 2021-01-05 10:33

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

相关标签:
3条回答
  • 2021-01-05 11:07

    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

    0 讨论(0)
  • 2021-01-05 11:12

    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();
    
    0 讨论(0)
  • 2021-01-05 11:18

    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.

    0 讨论(0)
提交回复
热议问题