From d86c90a116e231094da85c1e12740e9cef6c18f9 Mon Sep 17 00:00:00 2001 From: zysim <9867871+zysim@users.noreply.github.com> Date: Wed, 23 Oct 2024 09:52:09 +0800 Subject: [PATCH] Remove unnecessary DB calls in service method --- .../Services/Impl/LeaderboardService.cs | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/LeaderboardBackend/Services/Impl/LeaderboardService.cs b/LeaderboardBackend/Services/Impl/LeaderboardService.cs index 1754ddac..ae1feba6 100644 --- a/LeaderboardBackend/Services/Impl/LeaderboardService.cs +++ b/LeaderboardBackend/Services/Impl/LeaderboardService.cs @@ -47,7 +47,7 @@ public async Task CreateLeaderboard(CreateLeaderboardRe public async Task RestoreLeaderboard(long id) { Leaderboard? lb = await applicationContext.Leaderboards.FindAsync(id); - + if (lb == null) { return new LeaderboardNotFound(); @@ -58,16 +58,18 @@ public async Task RestoreLeaderboard(long id) return new LeaderboardNeverDeleted(); } - Leaderboard? maybe = await applicationContext.Leaderboards.SingleOrDefaultAsync(board => board.Slug == lb.Slug && board.DeletedAt == null); + lb.DeletedAt = null; - if (maybe != null) + try { - return new RestoreLeaderboardConflict(maybe); + await applicationContext.SaveChangesAsync(); + } + catch (DbUpdateException e) + when(e.InnerException is PostgresException { SqlState: PostgresErrorCodes.UniqueViolation } pgEx) + { + Leaderboard conflict = await applicationContext.Leaderboards.SingleAsync(c => c.Slug == lb.Slug && c.DeletedAt == null); + return new RestoreLeaderboardConflict(conflict); } - - lb.DeletedAt = null; - - await applicationContext.SaveChangesAsync(); return lb; }