Improve NHibernate QueryOver with Restrictions and ICriterion
Goals
Produce compact and comprehensive code using NHibernate QueryOver, Restrictions and ICriterion.
Context
We will take an example with an entity Period
, defined by a name, a start date and a end date.
Period
Needs
We want to request database to get periods corresponding some criteria :
- all the periods that contains a date
- all the periods that overlap another period
Implementation
We will use PeriodCriteriaBuilder
to build the ICriterion
blocks :
Some methods build small criteria :
BuildBeginBeforeOrEqualCriterion(DateTime date)
BuildEndAfterOrEqualCriterion(DateTime date)
BuildBeginBetweenCriterion(DateTime start, DateTime end)
BuildEndBetweenCriterion(DateTime start, DateTime end)
Then we can combine them with logical Restrictions
expression to provide more advanced predicates :
BuildBeginOrEndBetweenCriterion(DateTime start, DateTime end)
BuildContainsDateCriterion(DateTime date)
BuildContainsStartOrEndDateCriterion(DateTime start, DateTime end)
BuildOverlapsPeriodCriterion(DateTime start, DateTime end)