Bank table does not update

Asked

Viewed 154 times

1

I have in my database some tables they already contain data saved, but I am not able to update this data.

I have the method below that performs the insertion of a new item in the table if the table does not have the item, if it has the data that is in the table should be updated.

The insertion part is working, the problem is in the table update when I already have the item. For example, I want to buy a stock in a particular company. When I don’t have it works, but if I already have it and I want to add more, it’s not updating. Instead it is inserting another record in the table instead of updating the data.

I already debugged the code and realized that it checks if I already have that action and jumps right into the Else block of the code above. when I search the values I have in the database I realized that in Select in Linq obj.Cpf and obj.codigo do not present values to compare, but even so I receive the data stored in the database the values updates are made and the methods.

The method is this:

 public void compraAcoes(string cepf, string codigo, int quantidade)
    {


        string cd = codigo;
        try
        {

            string cpf;
            BuscaNet busca = new BuscaNet();
            Cotacao objeto = new Cotacao();

            objeto = busca.buscaInformacao(codigo);
            cpf = cepf;
            string empresa = objeto.empresa;
            string tipo = objeto.tipo;
            DateTime data = Convert.ToDateTime(objeto.data);
            string hora = objeto.hora;
            double abertura = objeto.abertura;
            double maxima = objeto.maxima;
            double minima = objeto.minima;
            double media = objeto.media;
            double fechamento = objeto.fechamento;
            double fechamento_anterior = objeto.fechamento_anterior;
            Int32 volume = objeto.volume;
            Int32 volume_financeiro = objeto.volume_financeiro;
            Int32 negocio = objeto.negocio;
            double oferta_de_compra = objeto.oferta_de_compra;
            double oferta_de_venda = objeto.oferta_de_venda;
            Int32 quantidade_ofertada_compra = objeto.quantidade_ofertada_compra;
            Int32 quantidade_ofertada_venda = objeto.quantidade_fertada_venda;
            double variação = objeto.variacao;
            string status = objeto.status;
            string fase = objeto.fase;


            string cod = codigo;
            bancotccEntities bc = new bancotccEntities();
            acao ac = bc.acao.FirstOrDefault(obj => obj.cpf == cepf && obj.codigo == cod);
            // Verifica se o usuario possui a ação
            if (ac == null)
            { 
                // Insere a nova ação no banco
                double vatotal_acao = (quantidade * fechamento);
                double valor_investido = vatotal_acao + taxas;

                banco.inserirAcao(cepf, cod, empresa, tipo, data, hora, abertura, maxima, minima, media, fechamento, fechamento_anterior, volume, volume_financeiro, negocio,
                          oferta_de_compra, oferta_de_venda, quantidade_ofertada_compra, quantidade_ofertada_venda, variação, status, fase);

                banco.inserirCarteira(cepf, cod, fechamento, quantidade, vatotal_acao, valor_investido, valor_inicial);


            }
            else
            {
                //atualiza a ação no banco
                carteira ca = bc.carteira.FirstOrDefault(obj => obj.cpf == cepf && obj.codigo == cod);

               ca.qtdacao = ca.qtdacao + quantidade;
               ca.vtotalacao = ca.vtotalacao + quantidade * fechamento;
               ca.vinvestido = ca.vinvestido +ca.vtotalacao + taxas;
               ca.vinicial = ca.vinicial;

               int quant = Convert.ToInt32(ca.qtdacao);
               double valor_da_acao = fechamento;
               double valor_gasto = Convert.ToDouble(ca.vtotalacao);
               double valor_investido = Convert.ToDouble(ca.vinvestido);

                 banco.atualizaAcao(cepf, codigo, empresa, tipo, data, hora, abertura, maxima, minima, media, fechamento, fechamento_anterior,
                         volume, volume_financeiro, negocio, oferta_de_compra, oferta_de_venda, quantidade_ofertada_compra,
                         quantidade_ofertada_venda, variação, status, fase);

                 banco.atualizarCarteira(cepf, cod,valor_da_acao, quant, valor_gasto,valor_investido);

            }




        }
      /*  catch (Exception e)
        {

            throw new Exception(e.Message.ToString());
        }*/
        catch (DbEntityValidationException dbEx)
        {
            foreach (var validationErrors in dbEx.EntityValidationErrors)
            {
                foreach (var validationError in validationErrors.ValidationErrors)
                {
                    Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                }
            }
        }
    }

The action update method and this:

 public void atualizaAcao(string cpf, string codigo, string empresa, string tipo, DateTime data, string hora, double abertura,
                                   double maxima, double minima, double media, double fechamento, double fechamento_anterior, int volume,
                                   int volume_financeiro, int negocio, double oferta_de_compra, double oferta_de_venda, int quantidade_ofertada_compra,
                                   int quantidade_fertada_venda, double variação, string status, string fase)
    {
        try
        {
            validaAtualizaAcao(cpf, codigo, empresa, tipo, data, hora, abertura, maxima, minima, media, fechamento, fechamento_anterior,
                              volume, volume_financeiro, negocio, oferta_de_compra, oferta_de_venda, quantidade_ofertada_compra,
                              quantidade_fertada_venda, variação, status, fase);
            bancotccEntities bco = new bancotccEntities();
            string codi = codigo;
            acao papel = bco.acao.FirstOrDefault(obj => obj.cpf == cpf && obj.codigo == codi);
            if (papel == null) { throw new Exception("Codigo não localizado, possivelmente você não possui esta ação!"); }
            papel.cpf = cpf;
            papel.codigo = codi;
            papel.empresa = empresa;
            papel.tipo = tipo;
            papel.data = Convert.ToDateTime(data);
            papel.hora = hora;
            papel.abertura = abertura;
            papel.maxima = maxima;
            papel.minima = minima;
            papel.medio = media;
            papel.fechamento = fechamento;
            papel.f_anterior = fechamento_anterior;
            papel.volume = volume;
            papel.v_financeiro = volume_financeiro;
            papel.negocio = negocio;
            papel.ofcompra = oferta_de_compra;
            papel.ofvenda = oferta_de_venda;
            papel.qtd_of__compra = quantidade_ofertada_compra;
            papel.qtd_of_venda = quantidade_fertada_venda;
            papel.variacao = Convert.ToString(variação);
            papel.status = Convert.ToInt32(status);
            papel.fase = fase;


            // Adiciona o objeto ao banco
            bco.acao.Add(papel);
           // bco.AddToacao(papel);

            //Salva as modificações no banco
            bco.SaveChanges();

           // SubmitChanges(); 
        }
       /* catch (Exception e)
        {

            throw new Exception(e.Message.ToString());
        }*/
        catch (DbEntityValidationException e) { foreach (var eve in e.EntityValidationErrors) { Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State); foreach (var ve in eve.ValidationErrors) { Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage); } } throw; } 

    }

The portfolio update method is this:

public void atualizarCarteira(string cpf, string codigo, double valor, int quant, double vtotal, double vinvestido)
    {
        try
        {
            validaAtualizarCarteira(cpf, codigo, valor, quant, vtotal, vinvestido);
            // instancia  o banco de dados
            bancotccEntities bco = new bancotccEntities();
            string cod = codigo;
            // busca na tabela carteira do banco uma ação correspondente ao código e atualiza-a 
            carteira crt = bco.carteira.FirstOrDefault(obj => obj.cpf == cpf && obj.codigo == cod);
            if (crt == null) { throw new Exception("Codigo não localizado, possivelmente você não possui esta ação!"); }
            crt.cpf = cpf;
            crt.codigo = codigo;
            crt.valoracao = valor;
            crt.qtdacao = crt.qtdacao + quant;
            crt.vtotalacao = crt.vtotalacao + vtotal;
            crt.vinvestido = crt.vinvestido + vinvestido;
            crt.vinicial = crt.vinicial;

            bco.carteira.Add(crt);
            bco.SaveChanges();

        }
        catch (Exception e)
        {

            throw new Exception(e.Message.ToString());
        }
    }

1 answer

2


You are wrong.

Modify your code to the following:

bco.Entry(papel).State = System.Data.Entity.EntityState.Modified;
bco.SaveChanges();

The same goes for carteira:

bco.Entry(crt).State = System.Data.Entity.EntityState.Modified;
bco.SaveChanges();

Add() is for inclusion only. To update, you need to mark the object in context as modified and then invoke the method to save the modifications.

  • 1

    OK gypsy thank you worked.

Browser other questions tagged

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