Feb 20 2010

NHibernate Detached Criteria

Category: ali @ 00:25

I'm not going to discuss NHibernate, what it is or why you should consider it (over Entity Framework, for one) as an ORM.  I have nothing against the speed of stored procedures and ADO.net calls but the time it takes to write all of that code...  My snippet here is just to share a delight I had today in using NHibernate's DetachedCriteria in composing dyanamic SQL for one of the few methods that would ever require it.

This segment of code accepts a fluently composed instance of an app-specific criteria object and feeds it to an NHibernate session to retrieve data.

Having written this sort of code in several languages over the years I'm happy to see things getting more elegant over time : )

        
	public IList<app> Find(ApplicationQueryCriteria queryCriteria) {
            if (queryCriteria.Id > 0) { // a get against pk is always a preferable shortcut if we can do so
                List<app> result = new List<app>();
                result.Add(nHSession.Get<app>(queryCriteria.Id));
                return result;
            } else {
                DetachedCriteria criteria = DetachedCriteria.For<app>();
                if (queryCriteria.MaxResults > 0)
                    criteria = criteria.SetMaxResults(queryCriteria.MaxResults);
                if (queryCriteria.StartAtRow > 0)
                    criteria = criteria.SetFirstResult(queryCriteria.StartAtRow);
                if (queryCriteria.OwnerAccountID > 0)
                    criteria = criteria.Add<app>(a => a.OwnerAccount.Id == queryCriteria.OwnerAccountID);
                return criteria.GetExecutableCriteria(nHSession).List<app>();
            }
        }

A really polished solution to this situation would be handle the parsing of criteria objects internally to the criteria object itself and exposing the detached criteria instance (or something easily convertible to one).  However, that route would require defining a common interface among the criteria and the overhead of processing items into a collection only to be passed to another collection.  I'm skipping the added processing time and added coding time for now.

Tags:

Comments

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading