Search code examples
nhibernatefluent-nhibernateaudit-trail

NHibernate Interceptor , auditing and logging to the database


I am using this piece of code as a part of my auditTrail Class but I am facing a stackOverFlow Exception when I try to log the changes to the database.

public void OnPostInsert(NHibernate.Event.PostInsertEvent @event)
    {
        if (!(@event.Entity is IAuditable))
        {
            using (ITransaction transaction = @event.Session.BeginTransaction())
            {

                if (@event.State != null)
                {
                    for (int i = 0; i < @event.State.Length; i++)
                    {
                        string propertyName = @event.Persister.PropertyNames[i];
                        if (@event.State[i] != null)
                        {
                            if (@event.State[i].GetType().Namespace.StartsWith("Averma.Fda.Domain"))
                            {
                                CompareIfOldStateIsNull(@event.State[i], Convert.ToInt32(@event.Id), @event.Entity.GetType().ToString(), @event.Session, false);
                            }
                            else
                            {
                                string auditEntry = "New value for " + SplitPropertyName(propertyName) + " has been added, the new value is " + @event.State[i];
                                @event.Session.Save(new AuditTrail() { AuditEntry = auditEntry, RelatedEntityId = Convert.ToInt32(@event.Id), RelatedEntityType = @event.Entity.GetType().ToString(), OperationType = Shared.Enums.OperationType.Insert });
                            }
                        }
                    }
                }
                transaction.Commit();//the error occurs here 
            }
        }
    }

Could anyone guide me about how to resolve this issue and how can I log the changes to the database .


Solution

  • Do not begin a new transaction and commit it inside the NHibernate interceptor because a transaction is already open and will be committed after the interceptor finishes its work, all what you want to do is to remove using (ITransaction transaction = @event.Session.BeginTransaction()) and to remove transaction.Commit(); and things will be ok.