I want to construct ICriteria's and pass that on to a function. That function will open a session and transaction. Then the function executes the ICriteria.List(); and returns the list of objects, like the code below.
I want to do this because I only want to write using(ISession Session = ...
and Using(ITransaction Transaction = ...
once for collecting a list of objects. Otherwise I am repeating myself so many times.
/// <summary>
/// Executes a ICriterion in a new session using a transaction.
/// </summary>
/// <typeparam name="T">The type of object to operate on.</typeparam>
/// <param name="Criterion">The criterion to get the list of objects by.</param>
/// <returns>The result of <c>(List<T>)Session.CreateCriteria(typeof(T)).Add(Criterion).List()</c></returns>
public static List<T> CriterionToList<T>(ICriterion Criterion)
{
List<T> Objects = default(List<T>);
using (ISession Session = SessionFactory.OpenSession())
{
using (ITransaction Transaction = Session.BeginTransaction())
{
Objects = (List<T>)Session.CreateCriteria(typeof(T)).Add(Criterion).List<T>();
Transaction.Commit();
}
}
return Objects;
}
The only thing ICriteria.Add() accepts is a ICriterion
.
The Question
ICriterion
does not have a .Add(..
So I can't do this:
ICriterion criterion = Restrictions.Eq(Property, Value).Add(...
How can I still achieve this, should I cast it to ICriteria
first like so?
ICriterion criterion = ((ICriteria)Restrictions.Eq(Property, Value)).Add(...
NOTE: The problem is that I am converting a huge project that uses DataTables to strong typed objects (compatible with NHibernate). So I have many, many compile errors that prevents me from testing my code without converting the whole project first.
I think you can achieve this with DetachedCriteria. The syntax and usage would be like this:
var det = DetachedCriteria.For<T>.Add(Restrictions.Eq(prop, val));
using (var session = Config.OpenSession())
using (var txn = session.BeginTransaction())
{
var result= det.GetExecutableCriteria(session).List();
}
You could easily encapsulate the transaction in a separate function:
public IList<T> GetList<T>(DetachedCriteria detachedCriteria)
{
IList<T> result;
using (var session = Config.OpenSession())
using (var txn = session.BeginTransaction())
{
result = detachedCriteria.GetExecutableCriteria(session).List<T>();
txn.Commit();
}
return result;
}