RSlaughter
RSlaughter

Reputation: 1201

NHibernate Expression.Like Criteria on Two Fields

I have an Nhibernate object that has the properties Firstname and Surname, and I'd like to be able to query on both fields (Firstname + " " + Surname); e.g. If the search term is "John Doe", this will be matched when John and Doe are in seperate fields.

How can I achieve that? Thanks!

Upvotes: 5

Views: 3139

Answers (2)

RSlaughter
RSlaughter

Reputation: 1201

So I ended up going with:

.Add(Restrictions.Like(Projections.SqlFunction("concat",
        NHibernateUtil.String,
        Projections.Property("Firstname"),
        Projections.Constant(" "),
        Projections.Property("Surname")),
    searchString, MatchMode.Anywhere))

Which seems to work as I need it to.

Upvotes: 5

psousa
psousa

Reputation: 6726

string firstName = "John";
string lastName = "Doe";

for example, using LINQ:

Session.Query<User>()
       .Where(u => u.FirstName == firstName || u.Surname == lastName)
       .ToList();

you could do it with QueryOver, which looks almost the same:

Session.QueryOver<User>()
       .Where(u => u.FirstName == firstName || u.Surname == lastName)
       .List();

UPDATE: I missed the point of the question.

what about this:

var name = "John Doe";
Session.Query<User>()
       .Where(u => name.Contains(u.FirstName) || name.Contains(u.Surname))
       .ToList();

Upvotes: 0

Related Questions