asp.net core + ef core 實現(xiàn)動態(tài)可擴展的分頁實踐方案
引言
歡迎閱讀,這篇文章主要面向初級開發(fā)者。
在開始之前,先問你一個問題:你做的系統(tǒng),是不是每次增加一個查詢條件或者排序字段,都要去請求參數(shù)對象里加一個屬性,然后再跑去改 EF Core 的查詢邏輯?
如果是,那這篇文章應該對你有用。我會帶你做一個統(tǒng)一的、擴展起來不那么麻煩的分頁查詢方案。整體思路是四件事:?統(tǒng)一入?yún)?、統(tǒng)一出參、動態(tài)排序、動態(tài)過濾?。
統(tǒng)一請求參數(shù)
先定義一個公共的 QueryParameters 解決這個問題:
public class QueryParameters
{
private const int MaxPageSize = 100;
private int _pageSize = 10;
public int PageNumber { get; set; } = 1;
// 限制最大值,防止前端傳一個很大數(shù)值把數(shù)據(jù)庫搞崩了
public int PageSize
{
get => _pageSize;
set => _pageSize = value > MaxPageSize ? MaxPageSize : value;
}
// 支持多字段排序,格式:"name desc,price asc"
public string? SortBy { get; set; }
// 通用關(guān)鍵詞搜索
public string? Search { get; set; }
// 動態(tài)過濾條件
public List<FilterItem> Filters { get; set; } = [];
// 要返回的字段,逗號分隔:"id,name,price",不傳則返回全部
public string? Fields { get; set; }
}
ASP.NET Core 的模型綁定會自動把 query string 映射到這個對象,不需要手動解析。后續(xù)如果某個接口有額外參數(shù),繼承它加字段就行,不用每次從頭定義。
統(tǒng)一響應包裝器
返回值也統(tǒng)一一下,把分頁信息和數(shù)據(jù)放在一起,調(diào)用方就不用自己拼了:
public class PagedResponse<T>
{
// IReadOnlyList 防止外部隨意修改集合
public IReadOnlyList<T> Data { get; init; } = [];
public int PageNumber { get; init; }
public int PageSize { get; init; }
public int TotalRecords { get; init; }
public int TotalPages => (int)Math.Ceiling(TotalRecords / (double)PageSize);
public bool HasNextPage => PageNumber < TotalPages;
public bool HasPreviousPage => PageNumber > 1;
}
Data 是任意類型的集合,用 IReadOnlyList 防止被意外修改。TotalPages、HasNextPage 和 HasPreviousPage 三個是計算屬性,不需要單獨賦值。
擴展方法
把分頁、排序、過濾都做成 IQueryable<T> 的擴展方法,用起來像鏈式調(diào)用,調(diào)用的地方看起來會很干凈。
分頁
public static IQueryable<T> ApplyPagination<T>(
this IQueryable<T> query,
int pageNumber,
int pageSize)
{
return query
.Skip((pageNumber - 1) * pageSize)
.Take(pageSize);
}
動態(tài)排序
解析 "name desc,price asc" 這樣的字符串,動態(tài)生成排序表達式。用反射就能做到,不需要額外的庫:
public static IQueryable<T> ApplySort<T>(
this IQueryable<T> query,
string? sortBy)
{
if (string.IsNullOrWhiteSpace(sortBy))
return query;
var orderParams = sortBy.Split(',', StringSplitOptions.RemoveEmptyEntries);
var isFirst = true;
foreach (var param in orderParams)
{
var parts = param.Trim().Split(' ');
var propertyName = parts[0];
var isDesc = parts.Length > 1
&& parts[1].Equals("desc", StringComparison.OrdinalIgnoreCase);
// 用反射找屬性,找不到就跳過,避免拋異常
var prop = typeof(T).GetProperty(
propertyName,
BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
if (prop == null) continue;
// 構(gòu)建表達式樹:x => x.PropertyName
var paramExpr = Expression.Parameter(typeof(T), "x");
var body = Expression.Property(paramExpr, prop);
var lambda = Expression.Lambda(body, paramExpr);
var methodName = isFirst
? (isDesc ? "OrderByDescending" : "OrderBy")
: (isDesc ? "ThenByDescending" : "ThenBy");
var method = typeof(Queryable).GetMethods()
.First(m => m.Name == methodName && m.GetParameters().Length == 2)
.MakeGenericMethod(typeof(T), prop.PropertyType);
query = (IQueryable<T>)method.Invoke(null, [query, lambda])!;
isFirst = false;
}
return query;
}
也可以考慮
System.Linq.Dynamic.Core這個庫。
動態(tài)過濾
這是擴展性最強的一塊。前端傳字段名 + 操作符 + 值,后端用表達式樹動態(tài)拼 Where 條件,不需要每加一個篩選項就改后端代碼。
先定義過濾條件的數(shù)據(jù)結(jié)構(gòu):
public class FilterItem
{
// 字段名,對應實體屬性,不區(qū)分大小寫
public string Field { get; set; } = string.Empty;
// 操作符:eq、neq、contains、startswith、endswith、
// gt、gte、lt、lte、between、in、isnull、isnotnull
public string Op { get; set; } = "eq";
// 值,between 用逗號分隔兩個值,in 用逗號分隔多個值
public string? Value { get; set; }
}
然后實現(xiàn)過濾擴展方法:
public static IQueryable<T> ApplyFilters<T>(
this IQueryable<T> query,
IEnumerable<FilterItem> filters)
{
foreach (var filter in filters)
{
var prop = typeof(T).GetProperty(
filter.Field,
BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
// 找不到屬性,或者沒有 [Filterable] 標記,就跳過
if (prop == null || !prop.IsDefined(typeof(FilterableAttribute), false))
continue;
var param = Expression.Parameter(typeof(T), "x");
var member = Expression.Property(param, prop);
Expression? condition = null;
switch (filter.Op.ToLower())
{
case "eq":
condition = Expression.Equal(member, ParseConstant(filter.Value, prop.PropertyType));
break;
case "neq":
condition = Expression.NotEqual(member, ParseConstant(filter.Value, prop.PropertyType));
break;
case "gt":
condition = Expression.GreaterThan(member, ParseConstant(filter.Value, prop.PropertyType));
break;
case "gte":
condition = Expression.GreaterThanOrEqual(member, ParseConstant(filter.Value, prop.PropertyType));
break;
case "lt":
condition = Expression.LessThan(member, ParseConstant(filter.Value, prop.PropertyType));
break;
case "lte":
condition = Expression.LessThanOrEqual(member, ParseConstant(filter.Value, prop.PropertyType));
break;
case "contains":
condition = Expression.Call(
member,
typeof(string).GetMethod("Contains", [typeof(string)])!,
Expression.Constant(filter.Value ?? string.Empty));
break;
case "startswith":
condition = Expression.Call(
member,
typeof(string).GetMethod("StartsWith", [typeof(string)])!,
Expression.Constant(filter.Value ?? string.Empty));
break;
case "endswith":
condition = Expression.Call(
member,
typeof(string).GetMethod("EndsWith", [typeof(string)])!,
Expression.Constant(filter.Value ?? string.Empty));
break;
case "between":
// value 格式:"10,100"
var rangeParts = filter.Value?.Split(',') ?? [];
if (rangeParts.Length == 2)
{
var lower = ParseConstant(rangeParts[0].Trim(), prop.PropertyType);
var upper = ParseConstant(rangeParts[1].Trim(), prop.PropertyType);
condition = Expression.AndAlso(
Expression.GreaterThanOrEqual(member, lower),
Expression.LessThanOrEqual(member, upper));
}
break;
case "in":
// value 格式:"1,2,3",最多取 50 個,防止 OR 鏈過長
var inValues = filter.Value?.Split(',').Take(50)
.Select(v => ParseConstant(v.Trim(), prop.PropertyType))
.ToList() ?? [];
if (inValues.Count > 0)
{
condition = inValues
.Select(v => (Expression)Expression.Equal(member, v))
.Aggregate(Expression.OrElse);
}
break;
case "isnull":
condition = Expression.Equal(member, Expression.Constant(null, prop.PropertyType));
break;
case "isnotnull":
condition = Expression.NotEqual(member, Expression.Constant(null, prop.PropertyType));
break;
}
if (condition == null) continue;
var lambda = Expression.Lambda<Func<T, bool>>(condition, param);
query = query.Where(lambda);
}
return query;
}
// 把字符串值轉(zhuǎn)成對應類型的常量表達式
private static ConstantExpression ParseConstant(string? value, Type targetType)
{
var underlyingType = Nullable.GetUnderlyingType(targetType) ?? targetType;
if (value == null)
return Expression.Constant(null, targetType);
var converted = Convert.ChangeType(value, underlyingType);
return Expression.Constant(converted, targetType);
}
contains/startswith/endswith應對字符串,gt/lt/between應對對數(shù)值和日期。類型不匹配時會拋異常,生產(chǎn)代碼里可以在這里加 try-catch,捕獲后根據(jù)情況進行處理。
動態(tài)返回字段
有時候列表頁只需要 id 和 name,詳情頁才需要全量字段。與其寫兩個接口,不如讓前端自己說想要哪些字段(我經(jīng)歷的項目都是后端定義好給前端哈,不是前段自己拿,前段自己也不想拿)。
思路是:查出完整的實體,然后用反射把指定字段打包成字典返回,JSON 序列化后就只有這些字段。
public static class FieldSelectorExtensions
{
public static IDictionary<string, object?> SelectFields<T>(
this T obj,
IEnumerable<string> fields)
{
var result = new Dictionary<string, object?>(StringComparer.OrdinalIgnoreCase);
var props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var fieldName in fields)
{
var prop = props.FirstOrDefault(p =>
p.Name.Equals(fieldName, StringComparison.OrdinalIgnoreCase));
if (prop != null)
result[prop.Name] = prop.GetValue(obj);
}
return result;
}
public static IEnumerable<IDictionary<string, object?>> SelectFields<T>(
this IEnumerable<T> items,
string? fields)
{
if (string.IsNullOrWhiteSpace(fields))
{
var allProps = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Select(p => p.Name);
return items.Select(item => item.SelectFields(allProps));
}
var fieldList = fields
.Split(',', StringSplitOptions.RemoveEmptyEntries)
.Select(f => f.Trim());
return items.Select(item => item.SelectFields(fieldList));
}
}
安全性:字段白名單
動態(tài)過濾和動態(tài)返回字段功能很方便,但不是所有字段都該暴露出去,比如密碼、證件號、客戶姓名這類。用一個自定義 Attribute 來標記哪些字段允許外部操作:
[AttributeUsage(AttributeTargets.Property)]
public class FilterableAttribute : Attribute { }
public class Product
{
public int Id { get; set; }
[Filterable]
public string Name { get; set; } = string.Empty;
[Filterable]
public decimal Price { get; set; }
[Filterable]
public int Stock { get; set; }
// 不加 [Filterable],外部無法通過 filters 參數(shù)過濾這個字段
public string InternalRemark { get; set; } = string.Empty;
}
ApplyFilters 里已經(jīng)加了這個檢查(prop.IsDefined(typeof(FilterableAttribute), false)),找到屬性之后會先驗證標記,沒有就跳過。也可以反著來設計,加一個 FilterIgnore 特性,檢查的地方做相應的調(diào)整。
接到 Controller 里
有了這些擴展方法,Controller 里的邏輯就很平:
[HttpGet]
public async Task<ActionResult> GetProducts([FromQuery] QueryParameters parameters)
{
var query = _context.Products.AsQueryable();
// 動態(tài)過濾
if (parameters.Filters.Count > 0)
query = query.ApplyFilters(parameters.Filters);
// 先算總數(shù)(必須在分頁之前)
var totalRecords = await query.CountAsync();
// 排序 + 分頁
var items = await query
.ApplySort(parameters.SortBy)
.ApplyPagination(parameters.PageNumber, parameters.PageSize)
.Select(p => new ProductDto
{
Id = p.Id,
Name = p.Name,
Price = p.Price,
Stock = p.Stock
})
.ToListAsync();
// 按需返回字段
var data = items.SelectFields(parameters.Fields).ToList();
return Ok(new
{
data,
pageNumber = parameters.PageNumber,
pageSize = parameters.PageSize,
totalRecords,
totalPages = (int)Math.Ceiling(totalRecords / (double)parameters.PageSize),
hasNextPage = parameters.PageNumber < (int)Math.Ceiling(totalRecords / (double)parameters.PageSize),
hasPreviousPage = parameters.PageNumber > 1
});
}
前端請求示例:
# 查價格在 100-500 之間、名字包含"手機",只返回 id 和 name,按價格升序 GET /api/products ?filters[0].field=price&filters[0].op=between&filters[0].value=100,500 &filters[1].field=name&filters[1].op=contains&filters[1].value=手機 &fields=id,name &sortBy=price asc &pageNumber=1&pageSize=20
返回結(jié)果:
{
"data": [
{ "Id": 1, "Name": "iPhone 16" },
{ "Id": 2, "Name": "小米 15" }
],
"pageNumber": 1,
"pageSize": 20,
"totalRecords": 2,
"totalPages": 1,
"hasNextPage": false,
"hasPreviousPage": false
}
ok,你學會了嗎?
到此這篇關(guān)于asp.net core + ef core 實現(xiàn)動態(tài)可擴展的分頁實踐方案的文章就介紹到這了,更多相關(guān)asp.net core ef core分頁查詢內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- ASP.NET?Core使用EF查詢數(shù)據(jù)
- ASP.NET?Core?5.0中的Host.CreateDefaultBuilder執(zhí)行過程解析
- ASP.NET Core使用EF保存數(shù)據(jù)、級聯(lián)刪除和事務使用
- ASP.NET?Core使用EF為關(guān)系數(shù)據(jù)庫建模
- ASP.NET Core使用EF創(chuàng)建模型(必需和可選屬性、最大長度、并發(fā)標記、陰影屬性)
- ASP.NET?Core基于現(xiàn)有數(shù)據(jù)庫創(chuàng)建EF模型
- ASP.NET?Core使用EF?SQLite對數(shù)據(jù)庫增刪改查
相關(guān)文章
使用EF Code First搭建簡易ASP.NET MVC網(wǎng)站并允許數(shù)據(jù)庫遷移
這篇文章介紹了使用EF Code First搭建簡易ASP.NET MVC網(wǎng)站并允許數(shù)據(jù)庫遷移的方法,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-09-09
asp.net下一個賬號不允許多個用戶同時在線,重復登陸的代碼
asp.net下一個賬號不允許多個用戶同時在線,重復登陸的代碼,需要的朋友可以參考下。2010-10-10
JavaScript用JQuery呼叫Server端方法實現(xiàn)代碼與參考語法
從Javascript客戶端用JQuery呼叫Server端的方法,這也是一個大膽的嘗試,本人做了演示動畫以及參考語法,感興趣的朋友可以參考下,希望本人對你有所幫助2013-01-01
ASP.NET技巧:同時對多個文件進行大量寫操作對性能優(yōu)化
ASP.NET技巧:同時對多個文件進行大量寫操作對性能優(yōu)化...2006-09-09

