Question

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)\r\n at NHibernate.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+'%'

Was it helpful?

Solution 2

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>();

OTHER TIPS

s.CreateCriteria<Client>().Add(
      Restrictions.InsensitiveLike( "LastName", "something", MatchMode.Anywhere))

For Case-Insensitive %Like% Search

 Criteria criteria = session.createCriteria(Any.class);
 criteria.add(Restrictions.ilike(propertyName, value, MatchMode.ANYWHERE);
 criteria.list();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top