How to prevent a record when edited to save in duplicity?

Asked

Viewed 45 times

-1

This snippet of code saves the themes of a record. However, when I edit a record by adding a new client, the last theme of that record duplicates. That is, every time I edit a record it duplicates the theme of that record. In the example below I clicked on edit, but did not do any editing, only saved without changes.

This is the editing screen

inserir a descrição da imagem aqui

And this is the screen of the themes: See that in the second image he duplicated the theme of the customers that had in the record.

inserir a descrição da imagem aqui

for (int j = 0; j < dadosTela.listaIdCliente.Count(); j++) {
  //salvar os tema se o cliente não tem
  using(var conexao3 = new ferbaEntities()) {
    int ClienteId = dadosTela.listaIdCliente[j];
    var tbTemasTela = conexao3.tbTema.Where(x => x.FgApagado == 0 && x.FgAtivo == 1 && x.IdCliente == ClienteId && x.IdTema == dadosTela.tema.IdTema).OrderBy(x => x.DsTema).ToList();
    if (tbTemasTela.Count() == 0) {
      var tbNewTemasTela = conexao3.tbTema.Where(x => x.FgApagado == 0 && x.FgAtivo == 1 && x.IdTema == dadosTela.tema.IdTema).OrderBy(x => x.DsTema).ToList();

      var tema = new tbTema();
      tema.DsTema = tbNewTemasTela[0].DsTema;
      tema.DsRGB = tbNewTemasTela[0].DsRGB;
      tema.IdCor = tbNewTemasTela[0].IdCor;
      tema.IdCliente = dadosTela.listaIdCliente[j];
      tema.FgApagado = 0;
      tema.FgAtivo = 1;

      conexao3.tbTema.Add(tema);
      conexao3.SaveChanges();
    }

  }

1 answer

0

Difficult to analyze the error just with this code.

Your theme is duplicating when you edit or add a client?

Make sure that when saying the customer theme, you’re letting the Entity framework do the mapping of it. For example :

            var TemaEscolhidoPeloCliente = "Tema";

            Cliente.Tema = _context.Temas.FirstOrDefault(x => x.TemaNome == TemaEscolhidoPeloCliente);

            _context.Update(Cliente);
            _context.SaveChanges();

Another thing, your Theme class has an identifier?

            [Key]
            public string TemaNome { get; set; }

This way entityFramework will not allow a duplicated record and you will be required to do an existence check before.

            if(_context.Temas.Any(x => x.TemaNome == TemaEscolhidoPeloCliente))
            {
                //Existe esse tema
            }
            else
            {
                _context.Add(Tema);
                _Context.SaveChanges();
            }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.