none
Not able to save changes into the database with entity framework and sql server RRS feed

  • Question

  • Hi,

    I am trying to create a new project using entity framework, but I am not able to save anything into the database. It also does not work when I try to populate a data grid view with one record that I have manually inserted into the database for testing.

    I have already manually copied the .mdf file into the bin and release folders, and it does not work, as well as it wouldn't show any error. I have also trying changing the "Copy to Output Directory" property to "Do not copy", to "Copy Always" and also to "Copy if newer", nothing worked.

    Could someone please take a look and let me know what's I am missing ?

    public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }

            private void Form1_Load(object sender, EventArgs e)
            {
                using (var db = new TesteEntities())
                {
                    bsCliente.DataSource = db.Clientes.ToList();
                }
            }

            private void button1_Click(object sender, EventArgs e)
            {
                using (var db = new TesteEntities())
                {
                    bsCliente.DataSource = db.Clientes.ToList();

                    Cliente cliente = new Cliente();

                    cliente.nome = txtNome.Text;
                    cliente.telefone = txtTelefone.Text;


                    db.Clientes.Add(cliente);

                    try
                    {
                        db.SaveChanges();
                        label1.Visible = true;
                        label1.Text = "Saved Successfully";
                    }
                    catch (Exception ex)
                    {
                        label1.Visible = true;
                        label1.Text = ex.Message;
                    }


                    bsCliente.DataSource = db.Clientes.ToList();

                }
            }
        }

    I really appreciate it.

    Thanks,

    Filipe



    Tuesday, March 7, 2017 5:59 PM

All replies

  • Hi Filipe Geissler,

    Based on your description and related code, I create a simple demo, it works well.

    Please check the following option.

    1. please check if the connection string (initial catalog) and database is the same.

    2. please check if the table named Clientes has a primary key with identity.

    Best regards,

    Cole Wu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, March 8, 2017 7:31 AM
    Moderator