title: What is the best way to dynamically add to a where clause in a nhibernate query in C#?
body: <p>I have a some C# code that is querying a database using nhibernate that looks like this:</p>
  
  <pre><code>      public void Query()
        {
  
          IEnumerable&lt;Project&gt; list = session.Query&lt;Project&gt;()
              .Where(p =&gt; !p.IsDeleted)
              .FetchMany(r =&gt; r.UnfilteredProjectApplications)
              .ThenFetch(r =&gt; r.Application)
              .ToList()
        }
  </code></pre>
  
  <p>I now have a number of user driver filters so, based on the parameters passed in, i want to add to the where clause.  So something like this:</p>
  
  <pre><code>       public void Query(string name)
        {
  
           if (!String.IsNullOrEmpty(name)
            {
              IEnumerable&lt;Project&gt; list = session.Query&lt;Project&gt;()
               .Where(p =&gt; !p.IsDeleted &amp;&amp; p.Name == name)
              .FetchMany(r =&gt; r.UnfilteredProjectApplications)
              .ThenFetch(r =&gt; r.Application)
              .ToList()
            }
        }
        else
        {
          IEnumerable&lt;Project&gt; list = session.Query&lt;Project&gt;()
              .Where(p =&gt; !p.IsDeleted)
              .FetchMany(r =&gt; r.UnfilteredProjectApplications)
              .ThenFetch(r =&gt; r.Application)
              .ToList()
        }
  </code></pre>
  
  <p>the user can select one or many filters.  As you can imagine, this code above would get ridiculously complicated given the large number of combinations.  Is there an elegant way to append a where clause here with additional blocks of logic.  Some might be simple such as</p>
  
  <pre><code>         p.Name == name
  </code></pre>
  
  <p>but others might be more complicated like:</p>
  
  <pre><code>         p.ProjectApplications.Select(r =&gt; r.Application).Any(s =&gt; applicationIds.Contains(s.Id)))
  </code></pre>
  
  <p>and as I said, there may be zero or many different filters . .</p>
  
  <h2>UPDATE:</h2>
  
  <p>i have seen in other cases, people suggesting building up the where clause like </p>
  
  <pre><code>query = query.where (r=&gt;r.name = "XYZ");
  query = query.where (r=&gt;r.Age &gt; 10);
  query = query.where (r=&gt;r.Gender = "Male");
  </code></pre>
  
  <p>but that does NOT seem to work with nhibernate so what started was a generic lambda question is now a specific question to nhibernate</p>