Paging in servicestack ormlite

后端 未结 2 553
走了就别回头了
走了就别回头了 2021-02-07 20:28

I am looking for a good way to implement paging in ormlite and I found another question, which has this snippet:

var data = db.Select

(predicate).Ski
2条回答
  •  情歌与酒
    2021-02-07 20:59

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

    public static class PagingExtensions
    {
        public static SqlExpression Page(this SqlExpression 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(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(predicate.Page(request.Page.LimitTo(1,null) ?? 1, request.PageSize.LimitTo(1,100) ?? 100);
    

    Which will enforce reasonable limits on Page and PageSize

提交回复
热议问题