您的位置:首页 > 其它

事件之道~一 如何让实体发生更新时,同时记录它更新的内容到日志表

2012-06-01 17:19 411 查看

一 如何让实体发生更新时,同时记录它更新的内容到日志表

在日常生活中,有个订阅的事,如,订个报纸,当出版社出版后,报纸就会送到您家,你不用管它什么时候出版。

在OA系统或者后台管理系统中,修改一条记录,总是想把它记住,等数据出问题后,好有据可查。

如何去实现这样的效果呢,难道为每一个方法都写一个insertLog(log)方法吗?这也太不面向对象了吧,呵呵,做为一个懒型程序员,不会这样做的,呵呵。

像这样:

Log log=new Log{...};
product.Update(entity);
logRepository.insertLog(log);

Log log=new Log{...};
user.Update(entity);
logRepository.insertLog(log);


这样的程序没有任何可扩展性和复用性,可能有些人会把程序改成这样,即针insertlogs写在update方法里

this.update(entity);
logRepository.insertLog(entity.Log);


这样的问题是什么呢?不够灵活,这时,只要调用update方法,都将会插入日志记录,有时,我们可能不想记录日志,这时怎么办呢?不会还要让我再一个update方法吧

解决这种问题,就是事件机制,首先让希望插入日志的对象去订阅插日志的事件,然后在统一的update方法里去触发它,这样,谁订阅了这个事件,就去为谁服务,不是很好,呵呵。

以下是统一实体类EntityBase的代码:

1    public EntityBase Log { get; set; }
#region Events 一组实体修改相关事件
/// <summary>
/// 修改前
/// </summary>
public event Action ModifyBefore;
/// <summary>
/// 修改后
/// </summary>
public event Action<EntityBase> ModifyAfter;
#endregion

#region Public Methods 触发实体修改事件的方法
public void OnModifyBefore()
{
if (ModifyBefore != null)
this.ModifyBefore();
}

public void OnModifyAfter(EntityBase log)
{
if (ModifyAfter != null)
this.ModifyAfter(log);
}
#endregion


RepositoryBase类相关代码完成对日志的插入:

#region System Logs
/// <summary>
/// 插入日志
/// </summary>
/// <param name="log"></param>
public void InsertLog(EntityBase log)
{
//写日志DB.Insert(log);
if (log != null)
this.InsertEntity(log);
}
#endregion


在更新方法中进行事件的触发:

try
{
entity.OnModifyBefore(); //为更新注入记录日志的事件
DB.ExecuteCommand(builder.ToString(), arguments.ToArray());
entity.OnModifyAfter(entity.Log);
}
catch (Exception ex)
{
Debug.WriteLine(ex);
throw;
}


在前台调用时,就变成了这样:

1                entity.ModifyBefore += delegate
{
entity.Log = new WebEntityLogs
{
CreateDate = DateTime.Now,
Info = entity.Name,
Operator = "zzl",
Title = "帮助中心"
};
};
entity.ModifyAfter += new HelperCenterCategoryRepository().InsertLog;
iHelperCenterCategoryRepository.Update(entity);


这样,当iHelperCenterCategoryRepository方法成功操作后,就会触发InsertLog这个方法,来将Logs记录插入。

事实上,有时我们总是说“事件用不到”,做WEB开发的“用不到事件”,其实,可能是我们不太了解事件,在以后的学习中,我还会去写“事件有道”这个系列。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: