Minarja
Minarja

Reputation: 23

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?

Upvotes: 2

Views: 1416

Answers (2)

Radim K&#246;hler
Radim K&#246;hler

Reputation: 123901

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

Upvotes: 1

xanatos
xanatos

Reputation: 111950

As written by Radim, you are using a parameter inside the QueryOver. The problem is that newExam is probably null when you execute the query.

Upvotes: 0

Related Questions