In key duplication when burning with EntityFrameWork in competition with many users, it only allows 5 attempts and in 6 SaveChange () tag (example 1).
If it is with SqlConnection it does not give a problem (example 2).
Example 1:
Public Sub AdicionaAux(ByRef Tentativas As Integer)
Dim inBlnRepete As Boolean = False
Try
Using ctx As New BD.Dinamica.Aplicacao
Using trans As DbContextTransaction = ctx.Database.BeginTransaction(IsolationLevel.RepeatableRead)
Try
Dim t As tbArtigos = ctx.tbArtigos.FirstOrDefault
ctx.tbArtigos.Attach(t)
ctx.Entry(t).State = EntityState.Added
ctx.SaveChanges()
Catch ex As Exception
trans.Rollback()
Throw
End Try
End Using
End Using
Catch
inBlnRepete = True 'RepeteFuncaoPorConcorrencia(ex, Tentativas)
If inBlnRepete And Tentativas < 5 Then
AdicionaAux(Tentativas)
Else
Throw
End If
End Try
End Sub
Example 2:
Public Sub AdicionaAux(ByRef Tentativas As Integer)
Try
Dim appServidorSQL As String = ConfigurationManager.AppSettings("ServidorSQL")
Dim appInstanciaSQL As String = ConfigurationManager.AppSettings("InstanciaSQL")
Dim appBDEmpresa As String = ConfigurationManager.AppSettings("BDEmpresa")
Using connection As New SqlConnection("Server=" & appServidorSQL & "\" & appInstanciaSQL & ";User ID=sa;Initial Catalog=" & appBDEmpresa & ";")
connection.Open()
Dim command As SqlCommand = connection.CreateCommand()
Dim transaction As SqlTransaction
transaction = connection.BeginTransaction("SampleTransaction")
command.Connection = connection
command.Transaction = transaction
Try
command.CommandText = _
"Insert into tbDestinos (Codigo, Descricao, Ativo, Sistema, DataCriacao, UtilizadorCriacao) VALUES ('POR', 'Description',1,1,getdate(),'xxx')"
command.ExecuteNonQuery()
transaction.Commit()
Catch ex As Exception
transaction.Rollback()
Throw
End Try
End Using
Catch
AdicionaAux(Tentativas)
End Try
End Sub