I have one controller method which creates new order in database with incremental custom order id (i.e. ABC000005
)
Order table has below fields
Id (PK)
Name
CustomOrderId
DateTime
To implement that I have written a method like below
var lastOrder = _dbContext.Order.OrderByDescending(x=>x.DateTime).First();
var lastOrderCustomId = lastOrder.CustomOrderId;
// Some other code which takes around 2 seconds
var newOrderId = //Calculation to increment custom order id (i.e. ABC000005 to ABC000006)
var newOrder = new Order();
newOrder.Name = "abc";
newOrder.DateTime = DateTime.UtcNow;
newOrder.CustomOrderId = newOrderId;
_dbContext.Order.Add(newOrder);
_dbContext.SaveChanges();
Above code works well when there are sequential requests to server, but when there are concurrent requests 2 requests will fetch same CustomOrderId
from database and creates two new identical CustomOrderId
values in database.
One of the solution I had implemented to overcome this was to use thread lock
above the code so that only one thread can access this code, but in that case concurrent requests takes more time and overall functionality to create order slows down.
Is there any other solution to this particular problem?