Chr*_*s J 6 nhibernate event-listener
我在NHibernate 2.1中配置了一个PreInsert和PreDelete事件监听器.对于特定表上的插入和删除,我想将审计事件写入单独的审计表.
public class AuditEventListener : IPreInsertEventListener, IPreDeleteEventListener
{
private static readonly ILog Log = LogManager.GetLogger(typeof(AuditEventListener));
public bool OnPreInsert(PreInsertEvent @event)
{
if (!(@event.Entity is IAuditable))
return false;
return AuditEvent(@event.Session.GetSession(EntityMode.Poco),
true, (@event.Entity as IAuditable));
}
public bool OnPreDelete(PreDeleteEvent @event)
{
if (!(@event.Entity is IAuditable))
return false;
return AuditEvent(@event.Session.GetSession(EntityMode.Poco),
false, (@event.Entity as IAuditable));
}
private bool AuditEvent(ISession session, bool isInsert, IAuditable entity)
{
if (entity is ArticleBinding)
{
if (Log.IsDebugEnabled)
Log.DebugFormat(" audit event ({0}), entity is ArticleBinding", ((isInsert) ? "Insert" : "Delete"));
AddArticleBindingAuditEvent(session, isInsert,
(entity as ArticleTagBinding));
}
return false;
}
private void AddArticleBindingAuditEvent(ISession session,
bool isInsert, ArticleBinding binding)
{
var auditRecord = new AuditArticleBinding()
{
ArticleId = binding.ArticleId,
Action = (isInsert) ? "Add" : "Delete",
LoggedBy = string.IsNullOrEmpty(Thread.CurrentPrincipal.Identity.Name)
? "Unknown"
: Thread.CurrentPrincipal.Identity.Name
};
session.Save(auditRecord);
}
}
Run Code Online (Sandbox Code Playgroud)
我解决了使用相同会话的问题,这导致异常.现在,所有代码都运行正常,我的日志语句被命中,但审计记录永远不会被插入.使用NHProf,我可以看到INSERT调用永远不会发生.
为什么以上代码不会导致INSERT?
我目前正在研究完全相同的事情并遇到了同样的问题。尝试保存新实体,但该INSERT语句甚至没有执行。我发现一篇关于使用 Pre[Update|Insert]Listeners 审核每条记录的文章,其中一条评论询问是否插入新实体,而作者回复说需要子会话。
private void AddArticleBindingAuditEvent(ISession session,
bool isInsert, ArticleBinding binding)
{
var childSession = e.Session.GetSession(EntityMode.Poco);
var auditRecord = new AuditArticleBinding()
{
ArticleId = binding.ArticleId,
Action = (isInsert) ? "Add" : "Delete",
LoggedBy = string.IsNullOrEmpty(Thread.CurrentPrincipal.Identity.Name)
? "Unknown"
: Thread.CurrentPrincipal.Identity.Name
};
childSession.Save(auditRecord);
childSession.Flush();
}
Run Code Online (Sandbox Code Playgroud)
给您的另一个参考(我今天找到的)是Auditing with NHibernate Listeners。它提供了有关插入新审核日志的完整示例,但使用 Post 侦听器并且不是特定于实体的(与我使用持久器执行的操作几乎相同以查找更改的值)。我不确定这比使用 Pre 监听器有什么好处。
作为“以防万一”,您需要确保将事件侦听器连接到您的配置:
var eventListener = new AuditEventListener();
config.SetListener(ListenerType.PreInsert, eventListener);
config.SetListener(ListenerType.PreDelete, eventListener);
Run Code Online (Sandbox Code Playgroud)
全面披露:我对 NHibernate 还很陌生,所以如果我错过了什么或可以做得更好,请告诉我。上述方法对我有用,因为我的记录已成功插入数据库,但在某些情况下会失败。尽管我几乎可以肯定这是特定于我的应用程序的(我是代码库的新手,所以仍在解决问题)
| 归档时间: |
|
| 查看次数: |
5192 次 |
| 最近记录: |