NHibernate Expression.Like Criteria on Two Fields

2019-06-28 05:27发布

问题:

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!

回答1:

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.



回答2:

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