5

I'm using the following c# code:

public IList<T> GetAllByExpression(Expression<Func<T, bool>> expression, int startIndex, int count, Func<T, DateTime> dateTimeSelector)
{
    using (ISession session = NHibernateHelper.GetSession())
    {
        return session.Query<T>()
            .Where(expression)
            .OrderBy(dateTimeSelector)
            .Skip(startIndex - 1)
            .Take(count)
            .ToList();
    }
}

update: even the follwoing code throws the same exception:

public IList<T> GetAllByExpression(Expression<Func<T, bool>> expression, int startIndex, int count, Expression<Func<T, DateTime>> dateTimeSelector)
{
    using (ISession session = NHibernateHelper.GetSession())
    {
        return session.Query<T>()
            .Where(expression)
            //.OrderBy(dateTimeSelector)
            //.Skip(startIndex - 1)
            //.Take(count)
            .ToList();
    }
}

And get Nh error:

Unable to cast object of type 'NHibernate.Hql.Ast.HqlCast' to type 'NHibernate.Hql.Ast.HqlBooleanExpression'.

what am I doing wrong?

Elad Benda2
  • 13,852
  • 29
  • 82
  • 157

2 Answers2

6

The problem was that I wrote short condition in the expression: as ((a == null)? true : a > b) NH casting fails on that (?)

Elad Benda2
  • 13,852
  • 29
  • 82
  • 157
  • Can confirm this is the problem. Had the same issue and rewriting the expression solved the issue. Thanks for sharing! – Ales Potocnik Hahonina Jan 08 '13 at 15:51
  • For a good example of how to rewrite the code to avoid this error, you can view the answer here: http://stackoverflow.com/questions/9774598/conditional-operator-in-linq-expression-causes-nhibernate-exception – humbads Apr 14 '14 at 14:30
1

Most probably you miss Expression<> over your datetime dateTimeSelector predicate.

Wiktor Zychla
  • 47,367
  • 6
  • 74
  • 106
  • tried to comment all: .OrderBy(dateTimeSelector) .Skip(startIndex - 1) .Take(count), and it didn't help – Elad Benda2 Dec 03 '11 at 15:18
  • how your example call looks like? – Wiktor Zychla Dec 03 '11 at 15:42
  • The problem was that I wrote short condition in the expression: as ((a == null)? true : a > b) NH casting fails on that (?) – Elad Benda2 Dec 03 '11 at 15:53
  • Probably. Try something trivial like `a > b` and it should work. When it fails at specific conditions (like yours) it means that there's no obvious translation of the expression to SQL (hibernate linq is not able to handle it). – Wiktor Zychla Dec 03 '11 at 16:13