Nhibernate将ICriteria迁移到QueryOver

时间:2016-11-06 06:01:05

标签: c# nhibernate queryover nhibernate-criteria

我们正在使用ICriteria,现在我们想在Nhibernate中切换到更具可读性的QueryOver

有人可以给我一个提示,告诉我如何将Icriteria的这个通用分页逻辑转换为QueryOver吗?

public static PagedList<T> PagedList<T>(this ICriteria criteria, 
    ISession session, int pageIndex, int pageSize) where T : class
{
    if (pageIndex < 0)
        pageIndex = 0;

    var countCrit = (ICriteria)criteria.Clone();
    countCrit.ClearOrders(); // so we don’t have missing group by exceptions

    var results = session.CreateMultiCriteria()
        .Add<long>(countCrit.SetProjection(Projections.RowCountInt64()))
        .Add<T>(criteria.SetFirstResult(pageIndex * pageSize).SetMaxResults(pageSize))
        .List();

    var totalCount = ((IList<long>)results[0])[0];

    return new PagedList<T>((IList<T>)results[1], totalCount, pageIndex, pageSize);
}

1 个答案:

答案 0 :(得分:1)

我使用它的方式:

var session = ... // get a ISession

// the QueryOver
var query = session.QueryOver<MyEntity>();
// apply all filtering, sorting...
query...

// GET A ROW COUNT query (ICriteria)
var rowCount = CriteriaTransformer.TransformToRowCount(query.UnderlyingCriteria);

// ask for a list, but with a Future, to combine both in one SQL statement
var list = query
    .Future<MyEntity>()
    .ToList();

// execute the main and count query at once
var count = rowCount
    .FutureValue<int>()
    .Value;

// list is now in memory, ready to be used
var list = futureList
    .ToList();

因此,我们正在使用QueryOver,并从基础标准和变换器中获利。使用 Future ,我们也可以在一个命令中执行所有操作。