I am currently working on the same thing and have been facing the same problem. An attempt to save a new object and an INSERT
is not even performed. I found an article about using Pre [Update | Insert] Listeners for audit on the record , where one comment asks about the insertion of a new object, and the author replies that a child session is required.
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(); }
Another link for you (which I found today): Audit using NHibernate listeners . It gives a complete example of inserting a new audit log, but uses Post listeners and is not related to the entity (almost the same as me, using persister to search for changed values). I'm not sure what the advantage of this is using Pre listeners.
And like βanywayβ, you need to make sure you hook up the event listener before your configuration:
var eventListener = new AuditEventListener(); config.SetListener(ListenerType.PreInsert, eventListener); config.SetListener(ListenerType.PreDelete, eventListener);
Full disclosure . I am new to NHibernate, so if there is something that I missed or could do better, please let me know. The above method works for me in that my record is successfully inserted into the database, but in some cases it does not work. Although I'm pretty sure this is specific to my application (from which I am new to the codebase, so I'm still working)
source share