I Have an endpoint that creates a new category, the category entity has a property called CategoryCode, which is unique and is calculated based on the last value in the database, for simplicity let’s just assume that i get the max CategoryCode value and increment it.
[HttpPost]
[Route(“TestAwait”)]
public async Task<ActionResult<GeneralApiResponse>> TestAwait(TestModel testId)
{
try
{
var categoryCode = await _context.Categories.MaxAsync(x => x.CategoryCode);
Debug.WriteLine($”Category Max Code {categoryCode} From {testId.StoreId}”);
var newCategoryCode = ++categoryCode;
await Task.Delay(20000); //For Testing
var newCategory = new Category()
{
CategoryName = $”Test {newCategoryCode}”,
CategoryCode = newCategoryCode,
BranchId = 1
};
await _context.Categories.AddAsync(newCategory);
await _context.SaveChangesAsync();
return Ok(newCategory);
}
catch (Exception ex)
{
return BadRequest(ex.InnerException != null ? ex.InnerException.Message : ex.Message);
}
}
Now the problem that faces me is when multiple clients call this endpoint at the same time, some of them won’t have the latest max value.
So my question here is how i can handle this secnario so that when multiple clients call the end point at the same time They well have the latest values in the database?
I’m not sure if this has nothing to do with dependency injection or
i can make this endpoint awaits for all clients not just a specific client or there some other solution?