I configured a PreInsert and PreDelete event listener in NHibernate
2.1. For inserts and deletes on a specific table, I want to write an
audit event to a separate auditing table. By tracing, I see that the
session transaction is being committed before the event listener code
is executed. I tried post-insert/post-delete instead of pre-insert/pre-
delete, but it didn't make any difference. Why wouldn't the event
listener be invoked before the transaction is committed?
Here is the basic structure of the code generating the insert, using
DAOs (managers):
manager = _managerFactory.GetArticleManager();
var article = manager.GetById(articleId);
manager.UnitOfWork.BeginTransaction();
SetRelationships(article);
manager.UnitOfWork.CommitTransaction();
Here is the event listener code:
public class AuditEventListener : IPreInsertEventListener,
IPreDeleteEventListener
{
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)
{
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);
}
}
--
You received this message because you are subscribed to the Google Groups
"nhusers" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/nhusers?hl=en.