Paging in servicestack ormlite

∥☆過路亽.° 提交于 2019-12-03 06:04:39

Found the answer in ormlite's tests. Essentially we could use SqlExpressionVisitor's Limit() like this:

var result = db.Select<K>( q => q.Where(predicate).Limit(skip:5, rows:10 ) );

I built a higher-level wrapper if you prefer working with Page and PageSize:

public static class PagingExtensions
{
    public static SqlExpression<T> Page<T>(this SqlExpression<T> exp, int? page, int? pageSize)
    {
        if (!page.HasValue || !pageSize.HasValue)
            return exp;

        if (page <= 0) throw new ArgumentOutOfRangeException("page", "Page must be a number greater than 0.");
        if (pageSize <= 0) throw new ArgumentOutOfRangeException("pageSize", "PageSize must be a number greater than 0.");

        int skip = (page.Value - 1) * pageSize.Value;
        int take = pageSize.Value;

        return exp.Limit(skip, take);
    }

    // http://stackoverflow.com/a/3176628/508681
    public static int? LimitToRange(this int? value, int? inclusiveMinimum, int? inclusiveMaximum)
    {
        if (!value.HasValue) return null;
        if (inclusiveMinimum.HasValue && value < inclusiveMinimum) { return inclusiveMinimum; }
        if (inclusiveMaximum.HasValue && value > inclusiveMaximum) { return inclusiveMaximum; }
        return value;
    }
}

Then you can write your query as:

var results = Db.Select<K>(predicate.Page(request.Page, request.PageSize));

Or, using the additional helper method to keep Page and PageSize to sensical and (possibly) performant values:

var results = Db.Select<K>(predicate.Page(request.Page.LimitTo(1,null) ?? 1, request.PageSize.LimitTo(1,100) ?? 100);

Which will enforce reasonable limits on Page and PageSize

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!