Generic List for NHibernate

Posted by Zafar Ullah - zafarjcp@gmail.com | 8:24 AM | , , , , , , | 0 comments »

A Generic method that takes GenericList as an argument and fill it with the data of type you pass as . Converts a non-typed collection into a strongly typed collection. This will fail if
the non-typed collection contains anything that cannot be casted to type of T.

The sample method uses CSLA framework with Database layer as NHibernate.
You can get CSLA from http://www.lhotka.net/ where as its NHibernate addon is available at http://www.codeplex.com/ under CSLA Contributions.

Here's the code you are looking for


public static void FillList(out List list)
{
list = null;
// Get an NHibernate session factory where DatabaseKey = connectionstring
ISessionFactory sessionFactory = Csla.NHibernate.Cfg.GetSessionFactory(DatabaseKey);

// Open an NHibernate session from the factory
using (ISession session = sessionFactory.OpenSession())
{
// Begin a transaction on the session
using (ITransaction transaction = session.BeginTransaction())
{
try
{

System.Collections.IList listOfObjects = session.CreateCriteria(typeof(T)).List();
T[] temp = new T[listOfObjects.Count];
listOfObjects.CopyTo(temp, 0);
list = new List(temp);
}
catch (HibernateException)
{
if (null != transaction)
{
transaction.Rollback();
}
}
}
}
}

0 comments