Nhibernate.Linq:限制与在查询结果(表达式来;谓语< T>>) [英] Nhibernate.Linq: Restricting query results with Where(Expression<Predicate<T>>)

查看:302
本文介绍了Nhibernate.Linq:限制与在查询结果(表达式来;谓语< T>>)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用NHibernate查询我的数据库。现在我需要限制使用谓词选择中的数据。到目前为止,我发现(谷歌在其最好的驱动开发),这样的事情是可能使用表达式和NHibernate.Linq

I query my Database using NHibernate. Now I need to restrict the data being selected using a Predicate. So far I found out (Google driven development at its best) that something like this is possible using Expressions and NHibernate.Linq.

下面是我的尝试:

public IList<Bestellung> GetAll(Predicate<Order> predicate)
{
    Expression<Func<Order, bool>> restriction = x => predicate(x);
    ISession session = SessionService.GetSession();
    IList<Order> bestellungen = session.Query<Order>()
                        .Where(restriction).ToList();
    return bestellungen;
}

这导致的无法投类型的对象'NHibernate.Hql .Ast.HqlCast为键入'NHibernate.Hql.Ast.HqlBooleanExpression。检查只是一个匆匆它吮吸:方法体的第一行更改为

This results in Unable to cast object of type 'NHibernate.Hql.Ast.HqlCast' to type 'NHibernate.Hql.Ast.HqlBooleanExpression'. Just a quickie to check where it sucks: Change the first line of the method body to

Expression<Func<Order, bool>> restriction = x => x.Id!=1;



与令人惊叹的结果是一切正常。

with the stunning result that everything works fine.

我怎样才能让我的谓语表达式执行

How can I get my Predicate executed in the expression?

推荐答案

您不能 - ?的至少不容易的。 NHibernate的(如EF和LINQ to SQL)解释的表达,将其转换为SQL。 。NHibernate的根本不知道怎么翻译的谓词到SQL

You can't - at least not easily. NHibernate (as EF and LINQ to SQL) interpret the expression and convert it to SQL. NHibernate simply doesn't know how to translate your predicate to SQL.

要实现这将是更换一种方式谓词< T> 本身与表达式来; Func键< T,BOOL>>

One way to achieve it would be to replace the Predicate<T> itself with an Expression<Func<T, bool>>:

public IList<Bestellung> GetAll(Expression<Func<Order, bool>> restriction)
{
    ISession session = SessionService.GetSession();
    IList<Order> bestellungen = session.Query<Order>()
                        .Where(restriction).ToList();
    return bestellungen;
}



重要提示:结果
你的代码调用此方法会看起来还是和以前一样:

Important:
Your code that calls this method would still look the same as before:

var orders = GetAll(x => x.Id != 1);

这篇关于Nhibernate.Linq:限制与在查询结果(表达式来;谓语&LT; T&GT;&GT;)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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