我目前在ASP.NET/C#中使用SqlDataSource來讓用戶插入,刪除和更新表格/ gridview中的條目。每個事件都需要寫入審計表。編寫前後值的審計記錄
我很容易實現插入和刪除 - 插入時,審計的主要信息只是插入查詢(e.Command.Parameters [0] .Value.ToString()等)的參數值,並且刪除很漂亮非常相似(只需在刪除查詢中獲取ID)。
但隨着更新,我需要記錄哪些字段發生了變化,以及它們的舊值。我將如何做到這一點?作爲一個例子,這裏是插入的代碼:
protected void SqlDataSource1_Inserting(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("constring - deleted for privacy "))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Parameters.AddWithValue("@source", "Nominal");
command.Parameters.AddWithValue("@action", "Insert");
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();
}
}
}
如何才能做到這一點?
這也是一個很好的觀點。無論你最終做什麼,都可以通過觸發器來實現邏輯。你必須在你的主表中存儲一個「最後由用戶ID改變」的列,這是我所知道的唯一缺點。 – Kendrick 2010-10-06 15:38:38