1

我在向数据库中添加数据时遇到问题。我编写的代码只能更新 shiftTiming_Start 而不能更新 shiftTiming_Stop。有人可以帮忙看看我的代码,看看出了什么问题。非常感谢。

private void btnUpdate_Click(object sender, EventArgs e) {
  using (testEntities Setupctx = new testEntities()) {
    var toBeUpdated = txtStart.Text;
    var toBeUpdated1 = txtStop.Text;
    shifthour updateShift = new shifthour();
    updateShift = Setupctx.shifthours.FirstOrDefault(u => u.shiftTiming_start == toBeUpdated);
    updateShift = Setupctx.shifthours.FirstOrDefault(p => p.shiftTiming_stop == toBeUpdated1);
    updateShift.shiftTiming_start = txtStart.Text;
    updateShift.shiftTiming_stop = txtStop.Text;
    Setupctx.SaveChanges();
    txtStart.Text = "";
    txtStop.Text = "";
    MessageBox.Show("Shift Timing Has Been Updated.");
  }
}
4

1 回答 1

0

假设我正确地关注了你(我建议使用更有意义的变量名),更新代码如下:

private void btnUpdate_Click(object sender, EventArgs e) {
  using (testEntities Setupctx = new testEntities()) {
    var toBeUpdatedStart = txtStart.Text;
    var toBeUpdatedStop = txtStop.Text;
    shifthour updateStartShift;
    shifthour updateStopShift;
    updateStartShift = Setupctx.shifthours.FirstOrDefault(u => u.shiftTiming_start == toBeUpdatedStart);
    updateStopShift = Setupctx.shifthours.FirstOrDefault(p => p.shiftTiming_stop == toBeUpdatedStop);
    if (updateStartShift != null)
    {
       updateStartShift.shiftTiming_start = txtStart.Text;
    }
    if (updateStopShift != null)
    {
        updateStopShift.shiftTiming_stop = txtStop.Text;
    }
    Setupctx.SaveChanges();
    txtStart.Text = "";
    txtStop.Text = "";
    MessageBox.Show("Shift Timing Has Been Updated.");
  }
}
于 2012-07-10T12:36:55.673 回答