Reputation: 27407
I decided to implement the event listeners in the latest build of NHibernate to keep track of who is making edits and what those edits are. My question is this - the below does work and I can step through it but what I'm not sure how these changes get saved ... do I need to build an audit table and write a mapping for it to call a save or what method is best to get the state of the object along w/ the "updated by" and "updated date" information so I can bring this up for someone at a later date.
I thought the base class provided this (or a subset of this functionality) but I can't seem to find a good blog post on what I'm missing here. Any help would be much appreciated!
Imports NHibernate.Event
Imports NHibernate.Event.Default
Public Class CustomSaveEventListener
Inherits DefaultSaveEventListener
Protected Overloads Overrides Function PerformSaveOrUpdate(ByVal evt As SaveOrUpdateEvent) As Object
Dim entity As IEntity = TryCast(evt.Entity, IEntity)
If entity IsNot Nothing Then
ProcessEntityBeforeInsert(entity)
End If
Return MyBase.PerformSaveOrUpdate(evt)
End Function
Friend Overridable Sub ProcessEntityBeforeInsert(ByVal entity As IEntity)
Dim user As User = DirectCast(Thread.CurrentPrincipal, User)
entity.ModifiedBy = user.UserName
entity.ModifiedDate = DateTime.Now
End Sub
End Class
When I open Reflector I see the below for this base class method - but what is it doing exactly?
protected override object PerformSaveOrUpdate(SaveOrUpdateEvent @event)
{
EntityEntry entry = @event.Session.PersistenceContext.GetEntry(@event.Entity);
if ((entry != null) && (entry.Status != Status.Deleted))
{
return this.EntityIsPersistent(@event);
}
return this.EntityIsTransient(@event);
}
Upvotes: 1
Views: 2163
Reputation: 259
When an entity is made persitent (saved or loaded), NH adds it to an internal dictionary (in session.PersistenceContext). The key of this dictionary is an EntityEntry, which contains some information about the entity state (and some other stuff i guess). If the entity is not saved (transient), it won't find an EntityKey in the internal dictionary.
By reading it, it looks like this function looks it the entity is transient or not, and calls the good function (I guess EntityIsTransient triggers save behaviour, EntityIsPersitent triggers update behaviour).
EntityEntry entry = @event.Session.PersistenceContext.GetEntry(@event.Entity);
if ((entry != null) && (entry.Status != Status.Deleted))
{
return this.EntityIsPersistent(@event);
}
return this.EntityIsTransient(@event);
But about your problem, it looks like a log system. Why don't you just implement ISaveOrUpdateEvent and use log4net to log edits with it?
Upvotes: 3