NHibernate Expression.Like Criteria on Two Fields

2019-06-28 05:28发布

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!

2条回答
叛逆
2楼-- · 2019-06-28 06:06

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.

查看更多
对你真心纯属浪费
3楼-- · 2019-06-28 06:24
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();
查看更多
登录 后发表回答