一 如何让实体发生更新时,同时记录它更新的内容到日志表
在日常生活中,有个订阅的事,如,订个报纸,当出版社出版后,报纸就会送到您家,你不用管它什么时候出版。
在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
这样的问题是什么呢?不够灵活,这时,只要调用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方法成功操作后,就会触发InsertLog这个方法,来将Logs记录插入。
事实上,有时我们总是说“事件用不到”,做WEB开发的“用不到事件”,其实,可能是我们不太了解事件,在以后的学习中,我还会去写“事件有道”这个系列。
作者:仓储大叔,张占岭,
荣誉:微软MVP