views:

19

answers:

1

I have a custom event listener being added (fluently) to my configuration using:

.ExposeConfiguration(c => c.SetListener(ListenerType.SaveUpdate, listener))

My listener just captures before a save or update and handles audit fields (CreatedBy, Modified By, etc.)

protected override object PerformSaveOrUpdate(SaveOrUpdateEvent sender)
{
      var entity = sender.Entity as IEditableEntity;

      if (entity != null)
      {
         if (entity.IsNew())
            ProcessEntityBeforeInsert(entity);
         else
            ProcessEntityBeforeUpdate(entity);
      }

      return base.PerformSaveOrUpdate(sender);
}

The 'entity.IsNew()' is a method that checks if the Id of the entity is '> 0' and evaluates correctly. However the 'base.PerformSaveOrUpdate' is trying performing an insert when it should be an update and is passing null in as the Id (it is mapped as GeneratedBy.Identity()) and I get the following exception:

"Cannot insert the value NULL into column 'Id', table '...'; column does not allow nulls. INSERT fails.\r\nThe statement has been terminated."
+1  A: 

You should use the PreInsert and PreUpdate methods for that purpose.

Here's a full example: http://ayende.com/Blog/archive/2009/04/29/nhibernate-ipreupdateeventlistener-amp-ipreinserteventlistener.aspx

Diego Mijelshon
Those events seem to do the trick, thanks!
jwarzech