问题
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+'%'
回答1:
s.CreateCriteria<Client>().Add(
Restrictions.InsensitiveLike( "LastName", "something", MatchMode.Anywhere))
回答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>();
回答3:
For Case-Insensitive %Like% Search
Criteria criteria = session.createCriteria(Any.class);
criteria.add(Restrictions.ilike(propertyName, value, MatchMode.ANYWHERE);
criteria.list();
来源:https://stackoverflow.com/questions/8728796/nhibernate-createcriteria-wildcard-like-when