我們使用實體象下面這樣:
public class Audit
{
[Required]
[StringLength(6)]
public string Action { get; set; }
public string Changes { get; set; }
public string PK { get; set; }
[Required]
public DateTime RevisionStamp { get; set; }
[Required]
[StringLength(50)]
public string TableName { get; set; }
[Required]
[StringLength(50)]
public string Username { get; set; }
}
我們用這個審覈所有的表。 Action
屬性說明發生了什麼類型的更改,如「更新」,「插入」或「刪除」。變化之前和之後的列值保存在Changes
列的JSON象下面這樣:
[{"FieldName":"ID","ValueBefore":"2","ValueAfter":"2"},{"FieldName":"SettingTypeIndex","ValueBefore":"FiscalYear","ValueAfter":"FiscalYear"},{"FieldName":"Value","ValueBefore":"2015","ValueAfter":"2016"},{"FieldName":"Year","ValueBefore":"0","ValueAfter":"0"},{"FieldName":"DateInserted","ValueBefore":"2016-04-11 8:45:08 AM","ValueAfter":"2016-04-11 8:45:08 AM"},{"FieldName":"DateModified","ValueBefore":"2016-07-28 9:45:46 AM","ValueAfter":"2016-07-28 9:47:17 AM"},{"FieldName":"CreatorUserID","ValueBefore":"b44792db-1fbd-44d2-9f7d-cf05c6a2f922","ValueAfter":"b44792db-1fbd-44d2-9f7d-cf05c6a2f922"},{"FieldName":"UpdaterUserID","ValueBefore":"b44792db-1fbd-44d2-9f7d-cf05c6a2f922","ValueAfter":"b44792db-1fbd-44d2-9f7d-cf05c6a2f922"}]
所以這樣我們就可以使用回滾功能(在需要時)。已更改記錄的主鍵保存在PK
屬性中。更改日期保存在RevisionStamp
propery中,最後表名和用戶名分別保存在TableName
和Username
屬性中。當然,這個實體被映射到數據庫中的一個表,並且數據被保存在該表中。
如果您使用的是entityframework,則可以覆蓋DbContext.SaveChanges()
方法並獲取所有ChangeTracker.Entries().Where(e=>e.State != EntityState.Unchanged)
項目並使用這些項目創建您的審計數據。
請看[Audit.EntityFramework](https://github.com/thepirat000/Audit.NET/tree/master/src/Audit.EntityFramework#auditentityframework)庫。 – thepirat000