开发者

(NHibernate) PerformSaveOrUpdate event not saving correctly

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

.ExposeConfiguration(c => c.SetListener(ListenerType.SaveUpd开发者_JS百科ate, 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."


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜