From 461b3b3c20ca716440baee05aa7a14fe5b7eac37 Mon Sep 17 00:00:00 2001 From: maxime Date: Wed, 6 Mar 2024 23:04:35 +0100 Subject: [PATCH] fix concurrency issue when adding a new step to the same tactic --- DbServices/DbTacticService.cs | 37 ++++++++++++++++++++++------------- WebAPI.sln | 4 ++++ 2 files changed, 27 insertions(+), 14 deletions(-) diff --git a/DbServices/DbTacticService.cs b/DbServices/DbTacticService.cs index 72910e9..42d70e1 100644 --- a/DbServices/DbTacticService.cs +++ b/DbServices/DbTacticService.cs @@ -9,6 +9,7 @@ namespace DbServices; public class DbTacticService(AppContext.AppContext context) : ITacticService { + public Task> ListTacticsOf(int userId) { return Task.FromResult( @@ -111,25 +112,33 @@ public class DbTacticService(AppContext.AppContext context) : ITacticService public async Task AddTacticStep(int tacticId, int parentStepId, string initialJson) { - if (!context.Tactics.Any(t => t.Id == tacticId)) + + var tactic = await context.Tactics.FirstOrDefaultAsync(t => t.Id == tacticId); + if (tactic == null) { return null; } - var nextStepId = context.TacticSteps - .Where(s => s.TacticId == tacticId) - .Max(s => s.StepId) + 1; - - var entity = new TacticStepEntity + TacticStepEntity entity; + int nextStepId; + lock (tactic) { - JsonContent = initialJson, - ParentId = parentStepId, - TacticId = tacticId, - StepId = nextStepId - }; - - await context.AddAsync(entity); - await context.SaveChangesAsync(); + nextStepId = context.TacticSteps + .Where(s => s.TacticId == tacticId) + .Max(s => s.StepId) + 1; + + entity = new TacticStepEntity + { + JsonContent = initialJson, + ParentId = parentStepId, + TacticId = tacticId, + StepId = nextStepId + }; + + context.Add(entity); + context.SaveChanges(); + } + return entity.StepId; } diff --git a/WebAPI.sln b/WebAPI.sln index 4cb00ad..0e5f8c6 100644 --- a/WebAPI.sln +++ b/WebAPI.sln @@ -54,5 +54,9 @@ Global {465819A9-7158-4612-AC57-ED2C7A0F243E}.Debug|Any CPU.Build.0 = Debug|Any CPU {465819A9-7158-4612-AC57-ED2C7A0F243E}.Release|Any CPU.ActiveCfg = Release|Any CPU {465819A9-7158-4612-AC57-ED2C7A0F243E}.Release|Any CPU.Build.0 = Release|Any CPU + {9C5EAD2F-FA50-43C2-BB86-1065ED661C52}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9C5EAD2F-FA50-43C2-BB86-1065ED661C52}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9C5EAD2F-FA50-43C2-BB86-1065ED661C52}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9C5EAD2F-FA50-43C2-BB86-1065ED661C52}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection EndGlobal