将数据更新到数据库

时间:2012-07-10 05:40:25

标签: c# linq datagridview updating

我在将数据添加到数据库时遇到问题。我编写的代码只能更新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.");
  }
}

1 个答案:

答案 0 :(得分: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.");
  }
}