locked
context.Entry(entity).State = EntityState.Modified; won't update my record. RRS feed

  • Question

  • User-1331222777 posted

    I have another project that uses the same way like context.Entry(entity).State = EntityState.Modified; to update a record and it works but on this project is does not. How can I fix this? and why is it happening?

    Here is my code: 

    using (Exercise2Entities db = new Exercise2Entities())
                    {
    
                        User userAcc = null;
                        if (ddlUsers.SelectedValue != "")
                        {
                            int userId = Convert.ToInt32(ddlUsers.SelectedValue);
                            //userAcc = db.Users.SingleOrDefault(u => u.Id == userId);
                            userAcc = db.Users.Find(userId);
                            
                            lblError.Text = "Reached here";
                            
                            //userAcc.Id = userId;
                            userAcc.Name = tbName.Text;
                            userAcc.Age = int.Parse(tbAge.Text);
                            userAcc.IsStudent = cbIsStudent.Checked.ToString();
                            userAcc.Date = DateTime.Parse(tbBirthdate.Text);
    
    
                            //db.Entry(userAcc).CurrentValues.SetValues(newUser);
                            db.Entry(userAcc).State = EntityState.Modified;
                        }
                        db.SaveChanges();
    
                        // reload drop down list
                        LoadUserDropDownList();
    
                        // select the one the user just saved
                        ddlUsers.ClearSelection();
                        ddlUsers.Items.FindByValue(userAcc.Id.ToString()).Selected = true;
    
                        LoadListViewWithUserInfo();
    
                    }

    Tuesday, January 28, 2020 7:28 PM

Answers

  • User-1331222777 posted

    I solved this by using the debugger and finding out a "dbentityvalidationexception" was being caught. I figured out that the textbox for tb.Name was adding spaces to the end of the string exceeding the length that the database can hold. I used .Trim() to remove the additional spaces and it updated the record successfully.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, January 29, 2020 10:47 PM

All replies

  • User303363814 posted

    You don't need to set the state.  Your entity userAcc is connected to the context db.  The flow should be something like

    if (ddlUsers.SelectedValue != "")
    {
       using (var db = new Exercise2Entities())
       {
          var userId = Convert.ToInt32(ddlUsers.SelectedValue);
          var userAcc = db.Users.Find(userId);
    
          userAcc.Name = tbName.Text;
          userAcc.Age = int.Parse(tbAge.Text);
          userAcc.IsStudent = cbIsStudent.Checked.ToString();
          userAcc.Date = DateTime.Parse(tbBirthdate.Text);
    
          db.SaveChanges()
        }
    
        // reload the dropdown list data
    }

    BTW - It is a very good investment to learn how to use the debugger rather than sprinkling code with writes to labels.  The debugger not only shows you are in the code but also allows you to see the current values of all variables.

    Another useful thing to do when learning or trying to track down problems is to get EF to show you the SQL that it is executing.  Put the next line inside the database context using blockand the console will show you the sql being executed.

    db.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);

    Tuesday, January 28, 2020 10:02 PM
  • User1120430333 posted

    db.SaveChanges();

    Have you tried placing the save inside the If-statment? And besides, the save is going to save a null userAcc if ddlUsers.SelectedValue equals empty string and blow-up the program.

    Tuesday, January 28, 2020 10:03 PM
  • User-1331222777 posted

    That still didn't work. Thank you for the SQL logging tip though.

    Tuesday, January 28, 2020 10:31 PM
  • User-1331222777 posted

    db.SaveChanges();

    Have you tried placing the save inside the If-statment? And besides, the save is going to save a null userAcc if ddlUsers.SelectedValue equals empty string and blow-up the program.

    I have fixed that, thanks.

    Tuesday, January 28, 2020 10:32 PM
  • User-1331222777 posted

    You don't need to set the state.  Your entity userAcc is connected to the context db.  The flow should be something like

    if (ddlUsers.SelectedValue != "")
    {
       using (var db = new Exercise2Entities())
       {
          var userId = Convert.ToInt32(ddlUsers.SelectedValue);
          var userAcc = db.Users.Find(userId);
    
          userAcc.Name = tbName.Text;
          userAcc.Age = int.Parse(tbAge.Text);
          userAcc.IsStudent = cbIsStudent.Checked.ToString();
          userAcc.Date = DateTime.Parse(tbBirthdate.Text);
    
          db.SaveChanges()
        }
    
        // reload the dropdown list data
    }

    BTW - It is a very good investment to learn how to use the debugger rather than sprinkling code with writes to labels.  The debugger not only shows you are in the code but also allows you to see the current values of all variables.

    Another useful thing to do when learning or trying to track down problems is to get EF to show you the SQL that it is executing.  Put the next line inside the database context using blockand the console will show you the sql being executed.

    db.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);

    It still doesn't work after changing it to your way. Thanks for the SQL logging tip though.

    Tuesday, January 28, 2020 10:34 PM
  • User303363814 posted

    Can you supply more information than 'it doesn't work'.  Use the debugger.  What is userAcc.Name? What is tbName.Text? what is userAcc.Age? what is, what is, etc (Don't guess or assume or think that you know - use the debugger to find out for certain)

    What is the value returned by SaveChanges()?

    Wednesday, January 29, 2020 10:26 PM
  • User-1331222777 posted

    I solved this by using the debugger and finding out a "dbentityvalidationexception" was being caught. I figured out that the textbox for tb.Name was adding spaces to the end of the string exceeding the length that the database can hold. I used .Trim() to remove the additional spaces and it updated the record successfully.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, January 29, 2020 10:47 PM