0

我想构建ICriteria并将其传递给函数。该函数将打开一个会话和事务。然后函数执行 ICriteria.List(); 并返回对象列表,如下面的代码。

我想这样做是因为我只想写using(ISession Session = ...一次Using(ITransaction Transaction = ...来收集对象列表。否则我会重复自己很多次。

    /// <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;
    }

ICriteria.Add() 唯一接受的是ICriterion.

问题

ICriterion没有.Add(..所以我不能这样做:

ICriterion criterion = Restrictions.Eq(Property, Value).Add(...

我怎样才能做到这一点,我应该ICriteria像这样先把它投下来吗?

ICriterion criterion = ((ICriteria)Restrictions.Eq(Property, Value)).Add(...

注意:问题是我正在将一个使用 DataTables 的大型项目转换为强类型对象(与 NHibernate 兼容)。所以我有很多很多的编译错误,阻止我在没有先转换整个项目的情况下测试我的代码。

4

1 回答 1

4

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;
}
于 2013-10-07T13:49:54.990 回答