Sunday, August 30, 2009

Initialize NHibernate with cascade

The Hibernate lazy associations is a wonderful feature which minimize the database communication when loading (large) sets of data.
But sometimes you need to load the full dataset, and you don't want to set the lazy flag in the mapping files to false. The solution is to use the static method NHibernate.NHibernateUtil.Initialize(), but the problem is that this method doesn't cascade to associated objects, you only initialize the current object, and no underlying collection. The following is a snippet of code that initialize all collections, and their collections, and so on. 

protected void InitializeWithCascade(object rootObject)
{
  PropertyInfo[] propInfos = rootObject.GetType().GetProperties();

  foreach (PropertyInfo property in propInfos)
  {
   MethodInfo mi = property.GetGetMethod();
   System.Collections.ICollection collection = mi.Invoke(rootObject, null) as System.Collections.ICollection;

   if (collection != null)
   {
    // This is a collection
    System.Collections.IEnumerator iter = collection.GetEnumerator();
    while (iter.MoveNext())
    {
     // Initialize the collection
     NHibernate.NHibernateUtil.Initialize(iter.Current);

     // Iterate the set
     InitializeWithCascade(iter.Current);
    }
   }
  }
}

No comments:

Post a Comment