一 如何讓實體發生更新時,同時記錄它更新的內容到日志表
在日常生活中,有個訂閱的事,如,訂個報紙,當出版社出版后,報紙就會送到您家,你不用管它什么時候出版。
在OA系統或者后台管理系統中,修改一條記錄,總是想把它記住,等數據出問題后,好有據可查。
如何去實現這樣的效果呢,難道為每一個方法都寫一個insertLog(log)方法嗎?這也太不面向對象了吧,呵呵,做為一個懶型程序員,不會這樣做的,呵呵。
像這樣:
1 Log log=new Log{...}; 2 product.Update(entity); 3 logRepository.insertLog(log); 4 5 Log log=new Log{...}; 6 user.Update(entity); 7 logRepository.insertLog(log);
這樣的程序沒有任何可擴展性和復用性,可能有些人會把程序改成這樣,即針insertlogs寫在update方法里
1 this.update(entity); 2 logRepository.insertLog(entity.Log);
這樣的問題是什么呢?不夠靈活,這時,只要調用update方法,都將會插入日志記錄,有時,我們可能不想記錄日志,這時怎么辦呢?不會還要讓我再一個update方法吧
解決這種問題,就是事件機制,首先讓希望插入日志的對象去訂閱插日志的事件,然后在統一的update方法里去觸發它,這樣,誰訂閱了這個事件,就去為誰服務,不是很好,呵呵。
以下是統一實體類EntityBase的代碼:
1 public EntityBase Log { get; set; } 2 #region Events 一組實體修改相關事件 3 /// <summary> 4 /// 修改前 5 /// </summary> 6 public event Action ModifyBefore; 7 /// <summary> 8 /// 修改后 9 /// </summary> 10 public event Action<EntityBase> ModifyAfter; 11 #endregion 12 13 #region Public Methods 觸發實體修改事件的方法 14 public void OnModifyBefore() 15 { 16 if (ModifyBefore != null) 17 this.ModifyBefore(); 18 } 19 20 public void OnModifyAfter(EntityBase log) 21 { 22 if (ModifyAfter != null) 23 this.ModifyAfter(log); 24 } 25 #endregion
RepositoryBase類相關代碼完成對日志的插入:
1 #region System Logs 2 /// <summary> 3 /// 插入日志 4 /// </summary> 5 /// <param name="log"></param> 6 public void InsertLog(EntityBase log) 7 { 8 //寫日志DB.Insert(log); 9 if (log != null) 10 this.InsertEntity(log); 11 } 12 #endregion
在更新方法中進行事件的觸發:
1 try 2 { 3 entity.OnModifyBefore(); //為更新注入記錄日志的事件 4 DB.ExecuteCommand(builder.ToString(), arguments.ToArray()); 5 entity.OnModifyAfter(entity.Log); 6 } 7 catch (Exception ex) 8 { 9 Debug.WriteLine(ex); 10 throw; 11 }
在前台調用時,就變成了這樣:
1 entity.ModifyBefore += delegate 2 { 3 entity.Log = new WebEntityLogs 4 { 5 CreateDate = DateTime.Now, 6 Info = entity.Name, 7 Operator = "zzl", 8 Title = "幫助中心" 9 }; 10 }; 11 entity.ModifyAfter += new HelperCenterCategoryRepository().InsertLog; 12 iHelperCenterCategoryRepository.Update(entity);
這樣,當iHelperCenterCategoryRepository方法成功操作后,就會觸發InsertLog這個方法,來將Logs記錄插入。
事實上,有時我們總是說“事件用不到”,做WEB開發的“用不到事件”,其實,可能是我們不太了解事件,在以后的學習中,我還會去寫“事件有道”這個系列。