2013-06-05 106 views
0

我有一個保存按鈕,它將在我的'IncidentActions'表中添加新數據,並同時更新'Incident'表中的3列。如何在一個表中插入數據並使用linq更新sql數據庫中的另一個表

我怎麼會去這樣做

這裏是我使用的嘗試做到這點的C#代碼。

protected void cmdSave_Click(object sender, EventArgs e) 
    { 
     Context db = new Context(); 

     // This will check the Action from the actions table and 
     var actionID = (from i in db.Actions 
         where i.Actions == tbActionType.Text 
         select i.ActionsID).First(); 

     long ID = Convert.ToInt64(Request.QueryString["IncidentID"]); 


     // TODO: update the incident table accordingly 
     IncidentAction act = new IncidentAction 
     { 
      IncidentID = ID, 
      ActionDate = (DateTime)dpActionDate.SelectedDate, 
      ActionsID = Convert.ToInt32(actionID), 
      StatusID = statID, 
      IsPublic = false, 
      Title = tbTitle.Text.Trim(), 
      PeriodValue = Convert.ToInt64(txtDuration.Text), 
      Description = txtDescription.Text.Trim(), 
      EstimatedCost = txtEstimatedCost.Text == string.Empty ? (decimal?)null : Convert.ToDecimal(txtEstimatedCost.Text), 
      ActualCost = txtActualCost.Text == string.Empty ? (decimal?)null : Convert.ToDecimal(txtActualCost.Text), 
      LastUpdated = DateTime.Now, 
      UpdatedBy = Convert.ToString(loggedInUserName), 
      CreatedByUserID = Convert.ToInt32(loggedInUserID), 
      Active = true 
     }; 


       db.IncidentActions.Add(act); 
       db.SaveChanges(); 

       Incident inc = new Incident 
       { 
        IncidentID = ID, 
        StatusID = statID_new, 
        IncidentPendingDate = DateTime.Now 
       }; 
       db.SaveChanges(); 
      } 

    } 
+0

這個代碼

db.IncidentActions.Add(act); db.SaveChanges(); Incident inc = new Incident { IncidentID = ID, StatusID = statID_new, IncidentPendingDate = DateTime.Now }; db.SaveChanges(); 

的結果是什麼問題此時此刻? – SamiHuutoniemi

+1

啊其所有好帥哥, 我得到它排序:D 虐待我的答案tomoro一旦我能夠回答我自己的問題 – user2343291

回答

0

一個問題似乎是您沒有引用數據庫中正確的Incident記錄。您可以先查詢數據庫以獲取要更新的記錄。

如果您想在「同一時間」(即在同一交易中)執行這兩項操作,請刪除第一個db.SaveChanges()。然後第二個將一起插入和更新。

此外,DateTime.Now每次調用時都會返回不同的值。如果要在每條記錄上匹配時間戳,只需調用DateTime.Now一次,將結果保存到一個變量中,然後在兩個地方使用它。

事情是這樣的:

Context db = new Context(); 
var now = DateTime.Now; 

IncidentAction act = new IncidentAction 
{ 
    IncidentID = ID, 
    ... 
    LastUpdated = DateTime.Now, 
}; 


db.IncidentActions.Add(act); 

Incident inc = db.Incidents.First(i => i.IncidentID == ID); 
inc.StatusID = statID_newl 
inc.IncidentPendingDate = now; 

db.SaveChanges(); 
0

,我沒有把它清除出來謝謝

我改變了這個

// add to the IncidentAction table. 
       db.IncidentActions.Add(act); 
       db.SaveChanges(); 

       // Update the Incident Table. 
       Incident inc = (from i in db.Incidents 
           where i.IncidentID == ID 
           select i).First(); 

       inc.StatusID = statID_new, 
       inc.IncidentPendingDate = DateTime.Now; 
       db.SaveChanges(); 
相關問題