Reputation: 123
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 .
Upvotes: 1
Views: 949
Reputation: 6054
The problem is when you save your audit entry, it tries to create another audit log entry for the first audit entry and it repeats. The fix would be to check the target table is audit log table and not to create entry if it's the case.
Upvotes: 0
Reputation: 4251
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.
Upvotes: 1