To deal with this competition problem, I create the entity in question and another controlling entity. So:
1- create the main entity, in this case: Request
public class Request
{
public Guid RequestId { get; set; } = Guid.NewGuid();
public int Number { get; set; }
// demais propriedades necessárias
}
2- 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;
}
3- Na Action of Controller, I call Obter requestcounter() to obtain the number.
public ActionResult Create(Request request)
{
if (ModelState.IsValid)
{
request.Number = ObterRequestCounter();
_repository.Adicionar(request);
return RedirectToAction("Index");
}
return View(request);
}
4- I create the private method where I add a Requestcounter with the Requestcounterid generated by me (when instant) and then I make the query using it to recover 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, no matter how many users will make an addition to Request at the same time. With the Requestcounterid of Requestcounter generated in the code (before going to the bank), I can recover which was the Number automatically generated by the bank without competition.
In my case, the table of Requestcounter is historical, but if my client at some future time decides that old records should be erased, I can do so using the property Dth for that reason.
That’s it.
Which is the database?
– dcastro
Junior, have you solved this problem yet? Still need help?
– Andre Calil
is Sql server dcastro! I haven’t solved Andre yet. dcastro’s answer doesn’t think it’s correct. I don’t want a counter for my key.
– Valter Junior
You need the number BEFORE the Insert in the database, that’s it?
– iuristona
Yes @iuristona.
– Valter Junior