NHibernate Pitfalls: The SaveOrUpdate Event

This is part of a series of posts about NHibernate Pitfalls. See the entire collection here.

You may be familiar with the NHibernate SaveOrUpdate event. In fact, you may have already attempted to use it in order to “audit stamping” your entities, by setting properties like CreatedBy, CreatedAt, UpdatedBy, UpdatedAt, etc.

It happens that you shouldn’t do it, mostly because SaveOrUpdate may be raised even when the session is not dirty and, consequently, there are no dirty entities. It happens on some circumstances as part of the NHibernate session’s dirty check procedure.

Instead, you should be using FlushEntity event, but you must also be sure that the entity that is passed to the event handler is not changed, before, well, changing it with the aforementioned “audit” properties. You should do the check using the event properties FlushEntityEvent.Status and FlushEntityEvent.HasDirtyCollection.

Fabio Maulo, the NHibernate team leader, has a post on it on his blog: http://fabiomaulo.blogspot.com/2011/05/nhibernate-bizarre-audit.html.

Bookmark and Share

                             

No Comments