NHibernate Criteria - how to filter by combination of properties

I needed to filter a list of results using a combination of two properties. A simple SQL statement would look like this:

SELECT TOP 10 *
FROM Person
WHERE FirstName + ' ' + LastName LIKE '%' + @Term + '%'

The ICriteria at NHibernate that I used was:

ICriteria criteria = Session.CreateCriteria(typeof(Person));
criteria.Add(Expression.Sql(
    "FirstName + ' ' + LastName LIKE ?",
    "%" + term + "%",
    NHibernateUtil.String));
criteria.SetMaxResults(10);

It works great, but I'm not sure if this is the perfect solution, since I'm still learning the NHibernate API. What are the recommended alternatives?

  • Is there anything besides Expression.Sqlthat will perform the same operation? I tried Expression.Like, but could not figure out how to combine the first and last name.
  • Should I map the FullName property to the formula "FirstName +" and "LastName" in the mapping class?
  • Should I create a FullName property for reading only for a domain object, and then map it to a column?
+3
2

:


Session.CreateCriteria<Person>()
       .Add(Restrictions.Like(
            Projections.SqlFunction("concat",
                                    NHibernateUtil.String,
                                    Projections.Property("FirstName"),
                                    Projections.Constant(" "),
                                    Projections.Property("LastName")),
            term,
            MatchMode.Anywhere))
+13

, : , , "foo bar" "bar foo"... :

ICriteria criteria = Session.CreateCriteria(typeof(Person));
criteria.Add(Expression.Like("FirstName",term, MatchMode.Anywhere) || Expression.Like("LastName",term, MatchMode.Anywhere));
criteria.SetMaxResults(10);
0

All Articles