0

How do I add optional where clauses with QueryOver?

TL;DR

I am trying to implement a search form for an application and use QueryOver.
Some of the search parameters are optional.

          var query =
            myDatabase.QueryOver(() => customerAlias)
                .JoinAlias(() => customerAlias.Projects, () => projectAlias)
                .Where(() => projectAlias.IsClosed >= 1)
                ... possibly add more stuff
LosManos
  • 7,195
  • 6
  • 56
  • 107

1 Answers1

4

QueryOver is deferred in execution as for usual Linq statements. It will only execute when you force it to by calling a finalising method such as .List<T>().

var query =
    myDatabase.QueryOver(() => customerAlias)
        .JoinAlias(() => customerAlias.Projects, () => projectAlias)
        .Where(() => projectAlias.IsClosed >= 1);

if (myCondition) {
    query = query.Where(...);
}

var result = query.List<T>(); //Or however else you want to make it execute.

You should still be able to access the in-line aliases too this way.

starlight54
  • 1,051
  • 1
  • 14
  • 20
  • But what if I have 2 conditions? `query = query.AddWhere(...)` ? – LosManos Oct 10 '16 at 07:51
  • 1
    There is probably no efficiency cost to doing `query.Where(condition1).Where(condition2)` versus `query.Where(condition1 && condition2)`, of course there is in normal LINQ, but I suspect Nhibernate would generate the same SQL query from both of these. But you can do this also: http://stackoverflow.com/questions/22944722/what-is-the-best-way-to-dynamically-add-to-a-where-clause-in-a-nhibernate-query#22948137 Although you won't get your in-line aliases then. – starlight54 Oct 10 '16 at 13:53
  • To those who didn't understand my original comment (i.e. me) my comment was about `query.Where(...);query.Where(...)` where I thought the second `Where` call would overwrite the first one but it turns out they concatenate instead; so the Answer is correct. – LosManos Oct 16 '16 at 11:28
  • 1
    I traced the query and found that there is no 'where' on the 'where' in the outputed sql but instead an appended 'and'. – LosManos Oct 17 '16 at 06:45