How do I escape a LIKE clause using NHibernate Criteria?

Posted by Jon Seigel on Stack Overflow See other posts from Stack Overflow or by Jon Seigel
Published on 2010-03-22T14:33:04Z Indexed on 2010/03/22 16:41 UTC
Read the original article Hit count: 489

Filed under:
|
|
|

The code we're using is straight-forward in this part of the search query:

myCriteria.Add(
    Expression.InsensitiveLike("Code", itemCode, MatchMode.Anywhere));

and this works fine in a production environment.

The issue is that one of our clients has item codes that contain % symbols which this query needs to match. The resulting SQL output from this code is similar to:

SELECT ... FROM ItemCodes WHERE ... AND Code LIKE '%ItemWith%Symbol%'

which clearly explains why they're getting some odd results in item searches.

Is there a way to enable escaping using the programmatic Criteria methods?


Addendum:

We're using a slightly old version of NHibernate, 2.1.0.4000 (current as of writing is 2.1.2.4853), but I checked the release notes, and there was no mention of a fix for this. I didn't find any open issue in their bugtracker either.

We're using SQL Server, so I can escape the special characters (%, _, [, and ^) in code really easily, but the point of us using NHibernate was to make our application database-engine-independent as much as possible.

Neither Restrictions.InsensitiveLike() nor HqlQueryUtil.GetLikeExpr() escape their inputs, and removing the MatchMode parameter makes no difference as far as escaping goes.

© Stack Overflow or respective owner

Related posts about .NET

Related posts about nhibernate