如果您更喜欢使用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;
}
}
然后你可以把你的查询写成:
var results = Db.Select<K>(predicate.Page(request.Page, request.PageSize));
或者,使用额外的辅助方法将 Page 和 PageSize 保持为合理和(可能)性能值:
var results = Db.Select<K>(predicate.Page(request.Page.LimitTo(1,null) ?? 1, request.PageSize.LimitTo(1,100) ?? 100);
Page
这将对和执行合理的限制PageSize