Frage

So in SQL I can write a query like this:

SELECT
  A,
  B,
  C
FROM
  myTABLE
WHERE
  (@X is NULL OR A = @X) AND
  (@Y is NULL OR B = @Y) AND
  (@Z is NULL OR C = @Z)

in order create a single query that returns all entries if no filtering parameters are specified, or a subset if any of them are specified. But how would I go about doing this using Nhibernate's QueryOver? I'm not even fully sure how to do an OR with QueryOvery at all...

War es hilfreich?

Lösung

In order to subjectively query (based on the parameter), the accepted method would be to build the where clause in pieces as such:

var qry = session.QueryOver<obj>(); 
if (!String.IsNullOrEmpty(A)) { qry.Where(x => x.a == A); } 
if (!String.IsNullOrEmpty(B)) { qry.Where(x => x.b == B); } 
if (!String.IsNullOrEmpty(C)) { qry.Where(x => x.c == C); } 
List<obj> data = qry.List<obj>().ToList();

So that the final result is the exact query to run for a given set of parameters, rather the generalized SQL query specified in the original post.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top