NHibernate 标准 - 如何过滤属性组合 [英] NHibernate Criteria - How to filter on combination of properties

查看:21
本文介绍了NHibernate 标准 - 如何过滤属性组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用两个属性的组合来过滤结果列表.一个简单的 SQL 语句看起来像这样:

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

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

我最终使用的 NHibernate 中的 ICriteria 是:

The ICriteria in NHibernate that I ended up using was:

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

它运行良好,但我不确定它是否是理想的解决方案,因为我仍在学习 NHibernate 的 Criteria API.有哪些推荐的替代方案?

It works perfectly, but I'm not sure if it is the ideal solution since I'm still learning about NHibernate's Criteria API. What are the recommended alternatives?

  • 除了 Expression.Sql 之外还有什么东西可以执行相同的操作吗?我尝试了 Expression.Like,但不知道如何组合名字和姓氏.
  • 我是否应该将 FullName 属性映射到映射类中的公式FirstName + ' ' + LastName"?
  • 是否应该在域对象上创建只读的 FullName 属性,然后将其映射到列?
  • Is there something besides Expression.Sql that would perform the same operation? I tried Expression.Like but couldn't figure out how to combine the first and last names.
  • Should I map a FullName property to the formula "FirstName + ' ' + LastName" in the mapping class?
  • Should I create a read only FullName property on the domain object then map it to a column?

推荐答案

您可以执行以下操作之一:

You can do one of the following:

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

这篇关于NHibernate 标准 - 如何过滤属性组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆