Nhibernate.Linq:用Where(Expression <Predicate <T >>)限制查询结果

Seb*_*ier 5 c# nhibernate linq-to-nhibernate

我使用NHibernate查询我的数据库.现在我需要使用谓词来限制所选择的数据.到目前为止,我发现(Google驱动开发的最佳状态)使用Expressions和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;
}
Run Code Online (Sandbox Code Playgroud)

这导致无法将类型为'NHibernate.Hql.Ast.HqlCast'的对象强制转换为'NHibernate.Hql.Ast.HqlBooleanExpression'.只需快速检查它的位置:将方法体的第一行更改为

Expression<Func<Order, bool>> restriction = x => x.Id!=1;
Run Code Online (Sandbox Code Playgroud)

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

如何在表达式中执行我的Predicate?

Dan*_*rth 6

你不能 - 至少不容易.NHibernate(作为EF和LINQ to SQL)解释表达式并将其转换为SQL.NHibernate根本不知道如何将谓词转换为SQL.

实现它的一种方法是用以下方法替换Predicate<T>自身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;
}
Run Code Online (Sandbox Code Playgroud)

重要提示:
调用此方法的代码仍然与以前一样:

var orders = GetAll(x => x.Id != 1);
Run Code Online (Sandbox Code Playgroud)