Saving new entity in PreInsert/PreDelete event listener doesn't persist to database

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.

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);
    }
}

I worked through the issue of using the same session, which was causing an exception. Now, all of the code runs fine, and my log statements are hit, but the audit record never gets inserted. Using NHProf, I can see that the INSERT call never occurs.

Why wouldn't the above code cause an INSERT?

6
задан Chris J 13 April 2011 в 13:37
поделиться