Search code examples
nhibernatecreatecriteria

nhibernate CreateCriteria wildcard Like when


In SQL I can write

SELECT blah FROM Clients
Where @p1 Like '%'+lastname+'%'

How do I represent this with CreateCriteria in Nhibernate?

I've tried

s.CreateCriteria<Client>.Add(Restrictions.Where<Client>(c => "something".Contains(c.LastName))

but get an error

System.Exception: Unrecognised method call: 
  System.String:Boolean Contains(System.String)
  at Hibernate.Impl.ExpressionProcessor.ProcessCustomMethodCall(
         MethodCallExpression methodCallExpression)

I've also tried

s.CreateCriteria<Client>.Add(Restrictions.Where<Client>(c => "something".IndexOf(c.LastName) != -1))

but get

variable 'c' of type 'TrinityFinance.Data.Entities.Client' referenced 
from scope '', but it is not defined

Note the order is important here.

@p1 Like '%'+lastname+'%'

is not the same as

lastname Like '%'+@p1+'%'


Solution

  • Thanks to a friend I've solved my issue.

    var searchCriteria = GetSession().CreateCriteria<Client>(); searchCriteria.Add(Expression.Sql(string.Format("'{0}' like '%' + {1} + '%'", p.ClientInputText,p.DbField)));

    var results = searchCriteria.List<Client>();