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几乎相同)
- 使用适当的基于实体的条件:
- If you always work with the full name, it's probably best to have a single property
- Create a query-only property for that purpose (see http://ayende.com/Blog/archive/2009/06/10/nhibernate-ndash-query-only-properties.aspx)
- Do the query in HQL, which is better suited for free-form queries (it will probably be almost the same as your SQL)
- Use a proper entity-based Criteria:
Session.CreateCriteria<Person>()
.Add(Restrictions.Like(
Projections.SqlFunction("concat",
NHibernateUtil.String,
Projections.Property("FirstName"),
Projections.Constant(" "),
Projections.Property("LastName")),
term,
MatchMode.Anywhere))
这篇关于NHibernate标准 - 如何过滤属性的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文