This simple function cleans up a lot of the Alias sillyness I have fought with in NHibernate.

        public static ICriteria CriteriaByLongAlias(this ICriteria criteria, string field)


            ICriteria byAlias = criteria.GetCriteriaByAlias(criteria.Alias + “_” + field) ??

                                criteria.CreateCriteria(field, criteria.Alias + “_” + field);

            return byAlias;


It is used any time you would previously call CreateCriteria and pass an alias.
session.CreateCriteria(typeof (Product)).CreateCriteria(“Orders”,”Product_Orders”);

The alias part is done automatically based on the criteria path. The advantage is that it works recursively, allowing for multiple criteria to be created, and then referenced without duplicates.

ICriteria criteria = session.CreateCriteria(typeof(Product)).CriteriaByLongAlias(“Orders”).CriteriaByLongAlias(“Customer”).Add(Expression.Eq(“Name”, “Ace Hardware”));


Note that in order for it to work, you have to create all your subcriteria with it.


This entry was posted in c#, NHibernate. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>