NHibernate Criteria API: Operator Overloading
Today I took the time to add a small but extremely nice feature to NHibernate, operator overloading with the criteria API. I used Steve Eichert's solution (thanks, Steve!).
For reference, here is the the code that I added (below are some examples of using it):
#region Operator Overloading
public static AbstractCriterion operator &(AbstractCriterion lhs, AbstractCriterion rhs)
{
return new AndExpression(lhs, rhs);
}
public static AbstractCriterion operator |(AbstractCriterion lhs, AbstractCriterion rhs)
{
return new OrExpression(lhs, rhs);
}
public static AbstractCriterion operator !(AbstractCriterion crit)
{
return new NotExpression(crit);
}
/// <summary>
/// See here for details:
/// http://steve.emxsoftware.com/NET/Overloading+the++and++operators
/// </summary>
public static bool operator false(AbstractCriterion criteria)
{
return false;
}
/// <summary>
/// See here for details:
/// http://steve.emxsoftware.com/NET/Overloading+the++and++operators
/// </summary>
public static bool operator true(AbstractCriterion criteria)
{
return false;
}
#endregion
Here is how you would use it:
IList<Customer> orders = session
.CreateCriteria(typeof(Customer))
.Add(Expression.Eq("Name", "Ayende") &&
Expression.Between("Registered", lastYear, DateTime.Today))
.List<Customer>();
It gets even better when you use the query generator:
IList<Customer> orders = session
.CreateCriteria(typeof(Customer))
.Add(Where.Customer.Name.Eq("Ayende") &&
Where.Customer.Registered.Between(lastYear, DateTime.Today))
.List<Customer>();
This code makes me happy.
Comments
Comment preview