Search code examples
c#nhibernatequeryover

NHibernate QueryOver NullReferenceException


I have following QueryOver which throws NullReferenceException when newExam.ActiveTo is null (ActiveTo type is DateTime?)

Exam examAlias = null;
examsInSameTime = session.QueryOver(() => examAlias)
                            .Where(() => examAlias.ActiveTo == null && newExam.ActiveTo == null)
                            .Future<Exam>();

When I rewrote query to this HQL everything works fine

var query = "from Exam exam where exam.ActiveTo is null and :newExamActiveTo is null)";
examsInSameTime = session.CreateQuery(query)                
            .SetParameter("newExamActiveTo", newExam.ActiveTo).List<Exam>();

Why QueryOver throws exception and HQL not?


Solution

  • I would say, that solution here should be surprisingly simple and elegant (but only if I do read your issue correctly).

    The point is - check your params in C#, do not send that into DB side:

    Exam examAlias = null;
    var query = session.QueryOver(() => examAlias);
    
    //here we will check what needed
    if(newExam.ActiveTo == null)
    {
        query.Where(() => examAlias.ActiveTo == null)
    }
    
    // we can repeat that many times and build WHERE clause as required
    ...
    
    // finally the query
    examsInSameTime = query.Future<Exam>();
    

    So, the trick here is:

    • check the search params on application side
    • if needed, convert them into SQL WHERE statement
    • send on DB side only restrictions which are required