2010-10-07 46 views
0

我需要對所有插入,更新和刪除等更改進行審計,並且我使用了一個簡單的SQLDataSource和GridView以及自動生成的INSERT/UPDATE/DELETE語句。問題是,當行更新時,我想獲得ID(主鍵)並將其放入審計表中 - 但由於UPDATE查詢的唯一參數是實際數據而不是主鍵,所以我不知道如何獲取這些信息。這裏是我的UPDATE查詢:在更新或插入時返回gridview的PK(ASP.NET,C#)

InsertCommand="INSERT INTO [NominalCode] ([VAXCode], [Reference], [CostCentre], [Department], [ReportingCategory]) VALUES (@VAXCode, @Reference, @CostCentre, @Department, @ReportingCategory)" 

這裏是auditting代碼隱藏:

protected void SqlDataSource1_Updating(object sender, SqlDataSourceCommandEventArgs e) 
    { 
     string fields = e.Command.Parameters[0].Value.ToString() + "," + e.Command.Parameters[1].Value.ToString() + "," + e.Command.Parameters[2].Value.ToString() + "," + e.Command.Parameters[3].Value.ToString() + "," + e.Command.Parameters[4].Value.ToString(); 
     System.Security.Principal. WindowsPrincipal p = System.Threading.Thread.CurrentPrincipal as System.Security.Principal.WindowsPrincipal; 
     string[] namearray = p.Identity.Name.Split('\\'); 
     string name = namearray[1]; 
     string queryString = "INSERT INTO Audit (source, action, item, userid, timestamp) VALUES (@source, @action, @item, @userid, @timestamp)"; 
     using (SqlConnection connection = new SqlConnection("con string removed for privacy")) 
     { 
      SqlCommand command = new SqlCommand(queryString, connection); 
      command.Parameters.AddWithValue("@source", "Nominal"); 
      command.Parameters.AddWithValue("@action", "Update"); 
      command.Parameters.AddWithValue("@item", fields); 
      command.Parameters.AddWithValue("@userid", name); 
      command.Parameters.AddWithValue("@timestamp", DateTime.Now); 
      connection.Open(); 
      try 
      { 
       command.ExecuteNonQuery(); 
      } 
      catch (Exception x) 
      { 
       Response.Write(x); 
      } 
      finally 
      { 
       connection.Close(); 
      } 
     } 
    } 

回答

0

好吧,我覺得愚蠢。當然,ID位於SQL查詢的WHERE子句中!我出於某種原因粘貼了INSERT命令。