Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nhibernate.Linq: Restricting query results with Where(Expression<Predicate<T>>)

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.

Here's what I tried:

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

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?

like image 246
Sebastian Edelmeier Avatar asked Mar 28 '12 10:03

Sebastian Edelmeier


1 Answers

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.

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);
like image 194
Daniel Hilgarth Avatar answered Oct 20 '22 05:10

Daniel Hilgarth