-2
I’m developing a system where I need to generate one random number and single and write to the bank, this system will run every day generating new numbers based on business rules.
With the help of colleagues in the comments I modified my code, now putting in the bank the column "coupon" as unique, so when trying to record will never allow if there is already an equal value in the bank.
My problem now is that when it happens that there already exists a number equal to what was generated, my system generates a recording error and I can’t make it generate a new number to try to record again.
I need that when I can not record because the number already exists it enters in "loop", generating a new coupon until it is not in the bank and can continue the execution.
To generate the random number:
public string CupomCampanha()
{
string numeroAleatorio = "";
var random = new Random();
var possibilidades = Enumerable.Range(0, 10).ToList();
var resultado = possibilidades.OrderBy(number => random.Next()).Take(10).ToArray();
return numeroAleatorio = String.Join("", resultado);
}
To do the Insert in the bank
public void InserirIndicacaoContas(string cpf)
{
if (cpf != "-")
{
var conexao = AbrirConexao();
var comando = conexao.CreateCommand();
comando.CommandText =
$"INSERT INTO campanhaCupons (cpf, cupon, idProduto, dataImportacao) VALUES (@cpf, @cupon, @idProduto, @dataImportacao)";
comando.Parameters.AddWithValue("cpf", cpf);
comando.Parameters.AddWithValue("cupon", _geraCupon.CupomCampanha());
comando.Parameters.AddWithValue("idProduto", "1");
comando.Parameters.AddWithValue("dataImportacao", Convert.ToDateTime(DateTime.Now).ToString("yyyy/MM/dd HH:mm:ss"));
ExecutaComando(comando);
}
I hope I can explain better now.
For having extended himself in the comments, the conversation was moved to the chat and can proceed there by the link provided
– Bacco
The questions here need to explain objectively and punctually the difficulty found, accompanied by a [mcve] problem and attempt to solve. To better enjoy the site, understand and avoid closures and negativations worth understanding What is the Stack Overflow and read the Stack Overflow Survival Guide (summarized) in Portuguese. Moreover, from the wording of the question, this is probably a XY problem, worth a read on the link.
– Bacco
Reversed. Do not change the scope of questions after they have been accepted. If you want to modify first take the acceptance or ask a new question.
– Augusto Vasques