NHibernate 标准 - 如何过滤属性组合 [英] NHibernate Criteria - How to filter on combination of properties
本文介绍了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 triedExpression.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:
- 如果您总是使用全名,最好只有一个属性
- 为此目的创建一个仅查询属性(参见 http://ayende.com/Blog/archive/2009/06/10/nhibernate-ndash-query-only-properties.aspx)
- 在 HQL 中执行查询,它更适合自由格式查询(它可能与您的 SQL 几乎相同)
- 使用适当的基于实体的标准:
Session.CreateCriteria<Person>()
.Add(Restrictions.Like(
Projections.SqlFunction("concat",
NHibernateUtil.String,
Projections.Property("FirstName"),
Projections.Constant(" "),
Projections.Property("LastName")),
term,
MatchMode.Anywhere))
这篇关于NHibernate 标准 - 如何过滤属性组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文