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.

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

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);