To deal with this competition problem, I create the entity in question and another control entity. So:
I create the parent entity, in this case: Request
public class Request
{
public Guid RequestId { get; set; } = Guid.NewGuid();
public int Number { get; set; }
// demais propriedades necessárias
}
I create a number control entity, type: RequestCounter
public class RequestCounter
{
public Guid RequestCounterId { get; set; } = Guid.NewGuid();
public int Number { get; set; } // no banco este campo será autoincrement
public DateTime Dth { get; set; } = DateTime.Now;
}
Controller , I call GetRequestCounter () to get the number.
public ActionResult Create(Request request)
{
if (ModelState.IsValid)
{
request.Number = ObterRequestCounter();
_repository.Adicionar(request);
return RedirectToAction("Index");
}
return View(request);
}
I create the private method where I add a RequestCounter with the RequestCounterId generated by me (when instantiated) and then query using Number .
private int ObterRequestCounter()
{
var requestCounter = new RequestCounter();
_repository.AdicionarRequestCounter(requestCounter);
var newNumber = _repository.ObterRequestCounterPorId
(requestCounter.RequestCounterId).Number;
// concateno o ano com o novo número e depois retorno para número.
return Convert.ToInt32(DateTime.Now.Year + newNumber.ToString());
}
Because of step 4, it does not matter how many users add Request at the same time. With the RequestCounterId of the RequestCounter generated in the code (before going to the bank), I can recover what was the Number automatically generated by the bank without competition.
In my case, the RequestCounter table looks like history, but if my client at some point in the future decides that old records should be deleted, I can do this using the Dth property for this.
That's it.