I have a concurrency control problem when inserting data from a table. The scenario is as follows:
There is a table that records daily data according to the user request, and this data can not be duplicated. The current concurrency control checks if there is any record of this data in the table that day, and if it does, it blocks the insertion.
The problem is that this implementation is inefficient because when two users simultaneously click the button, the verification is done simultaneously (resulting in "No data in the database") and the insertion also, creating duplicate data in the table.How can I implement a concurrency control without the use of a lock on the table, since this table is constantly used and a lock would probably make the transaction slower?
public void InserirFoo(Foo variavel, int id)
{
var diaDeHoje = DateTime.Now;
if (!VerificarInsercao(id, diaDeHoje))
{
contexto.FooDataSet.inserir(variavel);
contexto.SaveChanges();
}
}
private bool VerificarInsercao(int id, DateTime dataAtual)
{
return contexto.FooDataSet.Any(e => e.id == id && e.dataInsercao == dataAtual);
}