Rows not being updated

你。 提交于 2019-12-24 10:58:24

问题


I have written the following function meant to update a student in my database:

public bool UpdateStudent(Student stu)
{
   Console.WriteLine("StudentManger.UpdateStudent): Called");

   int rowsChanged = 0;

   using (var cnn = new SqlConnection(
          Properties.Settings.Default.universityConnectionString))
   {
      using (var cmd = new SqlCommand("UPDATE Student " +
              "SET FirstName = @FirstName, " +
              "lastName = @LastName, " +
              "birth = @birth " +
              "WHERE id = @id", cnn))
      {
        cmd.Parameters.Add(new SqlParameter("@FirstName", stu.FirstName));
        cmd.Parameters.Add(new SqlParameter("@LastName", stu.LastName));
        cmd.Parameters.Add(new SqlParameter("@id", stu.ID));
        cmd.Parameters.Add(new SqlParameter("@birth", stu.Birth));

        cnn.Open();
        rowsChanged = (int)cmd.ExecuteNonQuery();
        Properties.Settings.Default.Save();
      }
    }
    Properties.Settings.Default.Save();
    return (rowsChanged != 0);
  }

But when I call function no data is actually getting saved to the Database

Can someone tell me why?


回答1:


With the entire solution and information you provided in chat, your code is fine. The problem is that the .mdf database file is set to "Copy to Output Directory": "Always" in your project. Change this property to "Copy if newer" (or "Do not copy" and move it to the bin folder yourself) and it will not overwrite your changes when you re-run the application. Importantly, you will not see the changes you make in your application reflected in your .mdf database file in the project's root directory. It actually gets copied to the /bin folder and that's where the changes are persisted. So, if you don't change the "Copy to Output Directory" property, it will copy from your root to your /bin folder every time you build. Thus it appears that the changes aren't being persisted, when they actually are.



来源:https://stackoverflow.com/questions/10729953/rows-not-being-updated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!