title: Fluent NHibernate dynamic DTO query
body: <p>I'm trying to write a dynamic query using Fluent NHibernate and struggling to work out how to apply the dynamic where criteria.</p>
  
  <p>This is for an ASP.NET MVC5 project, where I wish to display a table of DTOs in a view, with the ability for the user to apply a filter on any of the rows. The filter must be passed to the database for performance reasons.</p>
  
  <p>Say I have the following class definitions:</p>
  
  <pre><code>// Entity in database
  public class EntityA
  {
      public int Id {get; set;}
      public string Name {get; set;}
      public IEnumerable&lt;EntityB&gt; Children {get; set;}
  }
  
  // Entity in database
  public class EntityB
  {
      public int Id {get; set;}
      public string Name {get; set;}
      public EntityA Parent {get; set;}
  }
  
  // DTO that is displayed in view / filter criteria is based on
  public class Dto
  {
      public int Id {get; set;}
      public string AName {get; set;}
      public string BName {get; set;}
  }
  </code></pre>
  
  <p>I am receiving the user's filter criteria in an <code>IEnumerable&lt;FilterProperty&gt;</code>, which looks like:</p>
  
  <pre><code>public class FilterProperty
  {
      public string Name {get; set;}
      public dynamic Value {get; set;}
  }
  </code></pre>
  
  <p>My NHibernate query is as follows:</p>
  
  <pre><code>EntityA aliasA = null;
  EntityB aliasB = null;
  Dto aliasDto = null;
  
  var query = QueryOver.Of(() =&gt; aliasB)
      .JoinAlias(() =&gt; aliasA.Parent, () =&gt; aliasA)
      .SelectList(l =&gt; l
          .Select(() =&gt; aliasB.Id).WithAlias(() =&gt; aliasDto.Id)
          .Select(() =&gt; aliasA.Name).WithAlias(() =&gt; aliasDto.AName)
          .Select(() =&gt; aliasB.Name).WithAlias(() =&gt; aliasDto.BName)
      )
      .TransformUsing(Transformers.AliasToBean&lt;Dto&gt;());
  </code></pre>
  
  <p><strong>Where I'm stumped is how do I translate the flat list of filters against the DTO, into expression trees against the entity objects that I can pass to the <code>.Where()</code> NHibernate method?</strong></p>
  
  <p>Is it possible to apply a restriction criteria post transformation?</p>