LINQ inserts 'ESCAPE N'~' in query

后端 未结 3 1365
谎友^
谎友^ 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

提交回复
热议问题