Nhibernate ICriteria和在查询中使用Lambda表达式 [英] Nhibernate ICriteria and Using Lambda Expressions in queries
问题描述
我是NHibernate的新手,我有些困惑.
hi i am new in NHibernate and i am a little confused.
假设我们有一个 product 表. 假设 product 表具有2列price1和price2.
Suppose we have a product table. Let the product table have 2 columns price1 and price2.
然后我可以通过HQL查询映射的产品实体,如下所示:
then i may query mapped product entities via HQL as follows:
string queryString = @"from product p
where p.price1 = p.price2 + 100 ";
IList result = session.CreateQuery(queryString).List();
如何通过ICriteria API实现这一目标.
How can i achieve that via ICriteria API.
我知道这很荒谬,但我正在尝试……
i know it's absurd but i am trying sth like that:
session.CreateCriteria(typeof(product))
.Add(Expression.Eq("price1", "price2" + 100))
.List()
或更恰当的说(使用lambda扩展名):
or more appropriately sth like that (using lambda extensions):
session.CreateCriteria(typeof(product))
.Add<product>(p => p.price1 == (p.price2 + 100))
.List()
事实上,我从googlecode下载了lambda扩展项目,并对其进行了扩展以可回避地处理Binary和Unary表达式,以实现诸如以下的表达式:
in fact i downloaded lambda extensions project from googlecode and i extended it to recusively process Binary and Unary expressions to implement expresssions like:
session.CreateCriteria(typeof(product))
.Add<product>(p =>
(!(p.price1 > 29007) && (p.price1 > 19009))
|| (p.price2 == 29009));
我目前正在像上面那样处理查询,但是由于我无法返回适当的限制条件来获取所需的条件,所以arithmethic子句让我很烦.
i am currently processing queries like above but the arithmethic clauses are annoying me since i can't return the appropriate Restriction to obtain the Criterion i need.
mpffh我已经厌倦了试图以一种全面的方式来解释它.我希望它能奏效.感谢您的帮助.
mpffh i m tired of trying to explain it in a comprehensive way. i hope it worked. Any help is appreciated.
推荐答案
您可以尝试以下方法:
ISQLFunction sqlAdd = new VarArgsSQLFunction("(", "+", ")");
var products = session
.CreateCriteria<product>()
.Add(
Expression.EqProperty(
"price1",
Projections.SqlFunction(
sqlAdd,
// TODO: replace this with appropriate type
NHibernateUtil.Double,
Projections.Property("price2"),
Projections.Constant(100)
)
)
)
.List<product>();
这篇关于Nhibernate ICriteria和在查询中使用Lambda表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!