NHibarnate – using event listeners to set entity modification date

I think, that it is a common practice to store information about creation and modification date of entities. However keeping appropriate columns up to date manually is error prone. We must remember that every time we modify entity, we also have to change its modification date. Fortunately thanks to event listeners, NHibernate can do all of this boring stuff for us. Let’s start from creating class which implements two interfaces:

  • IPreInsertEventListener
  • IPreUpdateEventListener

As You probably guessed OnPreInsert method is invoked before insert, and OnPreUpdate is called before update of entity. Having prepared the basic skeleton of class, it is time to configure NHibernate to use our event listeners. The basic configuration is taken from my previous post about NHibernate automappings, so I will only extend it by appending event listeners

Now we can put some logic into OnPreInsert and OnPreUpdate functions. First of all we have to somehow identify entities which hold information about creation and modification time. In order to do that I created simple interface IDateInfo

In the next step we have to modify OnPreInsert and OnPreUpdate methods, so that they can set creation and modification date of entities which implement IDateInfo interface.

Unfortunately at this moment saving entity (which implements IDateInfo interface) will throw exception
Despite the fact that we set values of ModificationDate and CreationDate properties , NHiberante seems not to notice that. That is why we have to manually update values of State object from PreInsertEvent and PreUpdateEvent. According to the documentation State object from class PreInsertEvent holds values which should be inserted and State object from class PreUpdateEvent holds values which should be updated. Function which update values of state object might look like that

Updated NHListener class now looks like that

As You can see, after setting values of IDateInfo I also call function SetState and update state of appropriate properties. From now everything works fine and our entities can be saved without problems. Source code for this post can be found here

NHibarnate – using event listeners to set entity modification date