Tuesday, June 28, 2011

NHibernate Validation Event Listener

I'm a little tired of posts on the web describing how to perform the validation within NHibernate listeners facilities (even though few of them quite helpful). And to hook to the event listeners at all, by the way.

I'm not sure which version these posts are about, but 3.0.0. has this funny comment in MergeEvent.cs:

This shows that there is no possibility to invoke this event using a null entity, yet the custom made listener below showed that the entity for the merge event is always null.
As a recap, Merge event should happen on persisting the detached entity. That is, you've retrieved the entity from persistent storage, manipulate over it and want to save it now, but the session is (or just might be) flushed already. In this case one should call session.Merge(entity) to have it merged into the session. All the related entities on 'leafs' of this one will be persisted firing regular SaveOrUpdate events.
Simple enough huh.
Refined code for ValidationEventListener then should be:
Don't forget to run the save, merge or whatnot within unit of work (aka business transaction), since sometimes you want to throw the exceptions to consumer code showing that validation failed. The exception should stop any persistence operations and roll back the entire transaction.

Now, the RegistrableEventListener is just a shortcut to have various configuration providers and have them register the listeners on their will:

No comments:

Post a Comment