Search code examples
nhibernatenhibernate-criteria

NHibernate default child collection and criteria strategies


In the domain model, there are a number of entities that have a Status enum with values of either Active or Deleted.

I'm looking for documentation and advice on recommended approaches on how to handle:

  1. When fetching a collection of entities that have a Status enum, to exclude those with the value set to Deleted by default (overridable on a case by case basis)

  2. When fetching a child collection of entities, by default to exclude those with the value set to Deleted by default.

In summary, I effectively want to keep all data relating to entities with a Status enum property, but to exclude those that have a value of Deleted for status by default.

Any pointers in the right direction much appreciated.


Solution

  • You can use a feature in nhibernate called a filter.

    Example:

      <class name="Post"  table="Posts">
         <id name="Id">
            <generator class="identity"/>
         <id>
    
        <property name="Title"/>
        <property name="Text"/>
        <property name="PostedAt"/>
    
    
        <filter name="NoDeleted" condition="Status <> 'Deleted'"/>
    </class>
    

    Then when you query:

     session.EnableFilter("NoDeleted")
    

    For more: http://ayende.com/blog/3993/nhibernate-filters