Solucionado (ver solução)
Solucionado
(ver solução)
4
respostas

Não consigo Salvar os campos Editados usando formulários (método AtualizaCadastro).

Olá pessoal, estou seguindo os passos do curso de Entity Framework 7 usando formulários Windows Form ao invés de Console Application. Todas as funções do DAO funcionam perfeitamente, exceto o Atualizar (usando SaveChanges()). No formulário, eu modifico os campos e clico no botão salvar, porém o banco não salva as alterações devidas. A inclusão de novos cadastros está ok. Implementei este botão para salvar um novo registro se a bool "novoCadastro" for true, caso contrário no else ele deveria apenas atualizar os campos modificados:

No formulário FrmCadastroFabricante está assim:

namespace Cadastro_de_Bombas.Formularios
{
    public partial class FrmCadastroFabricantes : Form
    {
        //Instanciando as classes de contexto
        EntidadesContext contexto = new EntidadesContext();
        FabricanteDAO fabricanteDAO;

        //Variáveis públicas do formulário.
        bool novoCadastro;

        //Construtor do formulário
        public FrmCadastroFabricantes()
        {
            this.fabricanteDAO = new FabricanteDAO(this.contexto);
            InitializeComponent();
        }

        private void FrmCadastroFabricantes_Load(object sender, EventArgs e)
        {

            btnNovoFabricante.Enabled = true;
            btnSalvarFabricante.Enabled = false;
            btnCancelarFabricante.Enabled = false;
            btnExcluirFabricante.Enabled = false;
            tbPesquisaFabricantePorID.Enabled = true;
            btnPesquisarFabricantePorID.Enabled = true;

            tbIdFabricante.Enabled = false;
            cbStatusFabricante.Enabled = false;
            tbNomeFabricante.Enabled = false;

        }

        private void btnNovoFabricante_Click(object sender, EventArgs e)
        {

            btnNovoFabricante.Enabled = false;
            btnSalvarFabricante.Enabled = true;
            btnCancelarFabricante.Enabled = true;
            btnExcluirFabricante.Enabled = true;
            tbPesquisaFabricantePorID.Enabled = false;
            btnPesquisarFabricantePorID.Enabled = false;

            tbIdFabricante.Enabled = true;
            cbStatusFabricante.Enabled = true;
            tbNomeFabricante.Enabled = true;

            novoCadastro = true;

        }

//Botão Salvar (Inclui no banco se for novo e Salva alterações se os campos forem modificados
        private void btnSalvarFabricante_Click(object sender, EventArgs e)
        {


            Fabricante f = new Fabricante()
            {
                Status_Fabricante = cbStatusFabricante.Text,
                Nome_Fabricante = tbNomeFabricante.Text
            };

            if (novoCadastro)
            //Se for um novo cadastro, o registro será ADICIONADO ao banco.
            {

                contexto.Fabricantes.Add(f);
                contexto.SaveChanges();
                MessageBox.Show("Cadastro incluído com sucesso.");
            }
            else
            //Se for apenas aberto, o registro será apenas ALTERADO no banco.
            {
//Aqui deveria atualizar os campos modificados no banco:
                contexto.SaveChanges();
                MessageBox.Show("Cadastro alterado com sucesso.");
            }

            btnNovoFabricante.Enabled = true;
            btnSalvarFabricante.Enabled = false;
            btnCancelarFabricante.Enabled = false;
            btnExcluirFabricante.Enabled = false;
            tbPesquisaFabricantePorID.Enabled = true;
            btnPesquisarFabricantePorID.Enabled = true;

            tbIdFabricante.Enabled = false;
            cbStatusFabricante.Enabled = false;
            tbNomeFabricante.Enabled = false;

            tbIdFabricante.Text = "";
            cbStatusFabricante.Text = "";
            tbNomeFabricante.Text = "";
            tbPesquisaFabricantePorID.Text = "";
        }

        private void btnCancelarFabricante_Click(object sender, EventArgs e)
        {
            btnNovoFabricante.Enabled = true;
            btnSalvarFabricante.Enabled = false;
            btnCancelarFabricante.Enabled = false;
            btnExcluirFabricante.Enabled = false;
            tbPesquisaFabricantePorID.Enabled = true;
            btnPesquisarFabricantePorID.Enabled = true;

            tbIdFabricante.Enabled = false;
            cbStatusFabricante.Enabled = false;
            tbNomeFabricante.Enabled = false;

            tbIdFabricante.Text = "";
            cbStatusFabricante.Text = "";
            tbNomeFabricante.Text = "";
            tbPesquisaFabricantePorID.Text = "";
        }

        private void btnPesquisarFabricantePorID_Click(object sender, EventArgs e)
        {
            novoCadastro = false;

            Fabricante fabricanteBuscadoPorID = fabricanteDAO.BuscaFabricantePorId(Convert.ToInt32(tbPesquisaFabricantePorID.Text));

            if (fabricanteBuscadoPorID == null)
            {
                MessageBox.Show("Nenhum registro foi encontrado com o ID informado!");
            }
            else
            {

                tbIdFabricante.Text = fabricanteBuscadoPorID.ID.ToString();
                cbStatusFabricante.Text = fabricanteBuscadoPorID.Status_Fabricante.ToString();
                tbNomeFabricante.Text = fabricanteBuscadoPorID.Nome_Fabricante.ToString();

            }

            btnNovoFabricante.Enabled = false;
            btnSalvarFabricante.Enabled = true;
            btnCancelarFabricante.Enabled = true;
            btnExcluirFabricante.Enabled = true;
            tbPesquisaFabricantePorID.Enabled = false;
            btnPesquisarFabricantePorID.Enabled = false;

            tbIdFabricante.Enabled = true;
            cbStatusFabricante.Enabled = true;
            tbNomeFabricante.Enabled = true;

        }

        private void btnExcluirFabricante_Click(object sender, EventArgs e)
        {

            Fabricante fabricanteBuscadoPorID = fabricanteDAO.BuscaFabricantePorId(Convert.ToInt32(tbPesquisaFabricantePorID.Text));
            fabricanteDAO.RemoveFabricante(fabricanteBuscadoPorID);

            MessageBox.Show("Cadastro removido com sucesso.");

            btnNovoFabricante.Enabled = true;
            btnSalvarFabricante.Enabled = false;
            btnCancelarFabricante.Enabled = false;
            btnExcluirFabricante.Enabled = false;
            tbPesquisaFabricantePorID.Enabled = true;
            btnPesquisarFabricantePorID.Enabled = true;

            tbIdFabricante.Enabled = false;
            cbStatusFabricante.Enabled = false;
            tbNomeFabricante.Enabled = false;

            tbIdFabricante.Text = "";
            cbStatusFabricante.Text = "";
            tbNomeFabricante.Text = "";

        }
    }
}

E na Classe DAO (FabricanteDAO) está assim:

public class FabricanteDAO
    {
        private EntidadesContext contexto;
        public FabricanteDAO(EntidadesContext contexto)
        {
            this.contexto = contexto;
        }

        public void AdicionaFabricante(Fabricante f)
        {
            this.contexto.Fabricantes.Add(f);
            this.contexto.SaveChanges();
        }

        //Atualiza Fabricante
        public void SaveChanges()
        {
            this.contexto.SaveChanges();
        }

        public void RemoveFabricante(Fabricante f)
        {
            this.contexto.Fabricantes.Remove(f);
            this.contexto.SaveChanges();
        }

        public Fabricante BuscaFabricantePorId(int id)
        {
            return this.contexto.Fabricantes.FirstOrDefault(f => f.ID == id);
        }

    }

Obs: já tentei usar o método .Update() também e não funcionou. No console apllication seguindo os passos do Renan deu certo. Poderiam me ajudar, por favor? Grande abraço!

4 respostas

Vou dar uma resumida e colocar apenas a parte dos códigos em questão:

No form de cadastro, o botão salvar/atualizar:

private void btnSalvarFabricante_Click(object sender, EventArgs e)
        {

            Fabricante f = new Fabricante()
            {
                Status_Fabricante = cbStatusFabricante.Text,
                Nome_Fabricante = tbNomeFabricante.Text
            };

            if (novoCadastro)
            //Se for um novo cadastro, o registro será ADICIONADO ao banco.
            {

                contexto.Fabricantes.Add(f);
                contexto.SaveChanges();
                MessageBox.Show("Cadastro incluído com sucesso.");
            }
            else
            //Se for apenas aberto, o registro será apenas ALTERADO no banco.
            {
                contexto.SaveChanges();
                MessageBox.Show("Cadastro alterado com sucesso.");
            }

Na classe DAO, o método Atualiza:

 //Atualiza Fabricante
        public void SaveChanges()
        {
            this.contexto.SaveChanges();
        }
solução!

Olá Samuel,

quando vamos atualizar um registro usando o Entity Framework primeiro precisamos buscá-lo no banco com base no seu identificador para obter um objeto no estado unchanged. Depois alteramos as propriedades deste objeto e ai sim chamamos o SaveChanges para que as alterações sejam persistidas no banco

Olá Lucas, acho que entendi. Mesmo que eu esteja no form com os campos abertos, eu preciso antes de tudo dizer pro Entity Framework que este ID aberto para edição é o ID= tal que vai receber o SaveChanges(). Vou tentar acertar aqui, obrigado pela ajuda!

Resolvido Lucas!

Ficou assim:

else
            //Se for apenas aberto, o registro será apenas ALTERADO no banco.
            {

                Fabricante atualizaPorID = contexto.Fabricantes.FirstOrDefault(update => update.ID == (Convert.ToInt32(tbPesquisaFabricantePorID.Text)));

                atualizaPorID.Status_Fabricante = cbStatusFabricante.Text;
                atualizaPorID.Nome_Fabricante = tbNomeFabricante.Text;

                contexto.SaveChanges();
                MessageBox.Show("Cadastro alterado com sucesso.");
            }

Muitíssimo obrigado pela ajuda! Grande abraço!

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software