From 77fa9a0f171c05e4fc0f1c0d980380a571df052b Mon Sep 17 00:00:00 2001 From: yao Date: Tue, 12 Nov 2024 22:50:57 +0800 Subject: [PATCH] refactor --- .../Controllers/MembersController3.cs | 19 ++++++++++--------- .../Member/Repository/MemberDbContext.cs | 7 ++++++- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/Paging/Lab.CursorPaging/Lab.CursorPaging.WebApi/Controllers/MembersController3.cs b/Paging/Lab.CursorPaging/Lab.CursorPaging.WebApi/Controllers/MembersController3.cs index 3e17f1df..dd985c95 100644 --- a/Paging/Lab.CursorPaging/Lab.CursorPaging.WebApi/Controllers/MembersController3.cs +++ b/Paging/Lab.CursorPaging/Lab.CursorPaging.WebApi/Controllers/MembersController3.cs @@ -57,14 +57,15 @@ private int TryGetPageSize() => ? int.Parse(sizes.FirstOrDefault() ?? string.Empty) : 10; - private async Task> GetPaginatedResultsAsync(IQueryable query, - int pageSize, - string cursor = null, - bool isPreviousPage = false) + private async Task> GetPaginatedResultsAsync(IQueryable query, + int pageSize, + string cursorToken = null, + bool isPreviousPage = false) + where T : BaseEntity { - if (!string.IsNullOrEmpty(cursor)) + if (!string.IsNullOrEmpty(cursorToken)) { - var cursorValue = Convert.FromBase64String(cursor); + var cursorValue = Convert.FromBase64String(cursorToken); var cursorId = BitConverter.ToInt32(cursorValue, 0); if (isPreviousPage) @@ -78,14 +79,14 @@ private async Task> GetPaginatedResultsAsync( } else { - query = query.OrderBy(x => x.Id); + query = query.OrderBy(x => x.SequenceId); } // 取得查詢結果並確保順序 var items = await query.Take(pageSize).ToListAsync(); if (isPreviousPage) { - items.Reverse(); // 反轉以符合遞增順序 + items.Reverse(); } // 計算下一頁和上一頁的游標 @@ -96,7 +97,7 @@ private async Task> GetPaginatedResultsAsync( ? Convert.ToBase64String(BitConverter.GetBytes(items.First().SequenceId)) : null; - return new CursorPagination + return new CursorPagination { Items = items, NextCursorToken = nextCursor, diff --git a/Paging/Lab.CursorPaging/Lab.CursorPaging.WebApi/Member/Repository/MemberDbContext.cs b/Paging/Lab.CursorPaging/Lab.CursorPaging.WebApi/Member/Repository/MemberDbContext.cs index 23e81f42..853c373f 100644 --- a/Paging/Lab.CursorPaging/Lab.CursorPaging.WebApi/Member/Repository/MemberDbContext.cs +++ b/Paging/Lab.CursorPaging/Lab.CursorPaging.WebApi/Member/Repository/MemberDbContext.cs @@ -46,7 +46,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) } } -public class MemberDataEntity +public class MemberDataEntity : BaseEntity { public string Id { get; set; } @@ -70,4 +70,9 @@ public class MemberDataEntity // [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public long SequenceId { get; set; } +} + +public class BaseEntity +{ + public long SequenceId { get; set; } } \ No newline at end of file