How to configure NHIbernate event listeners for Update and Save?

巧了我就是萌 提交于 2019-12-31 03:07:11

问题


Following on from my previous question How to implement LastUpdate in NHibernate Entities?.

I have two columns on my audited tables in my database:

  1. created datetime default getdate() not null (the creation date of this row)

  2. lastUpdate datetime null (the datetime this row was last updated)

I want to create a listener for updates only in NHibernate, because the database engine takes care of new records with the default constraint. I tried to create a Custom listener with this code:

public class CustomUpdateEventListener : DefaultSaveOrUpdateEventListener
{
    protected override object PerformSaveOrUpdate(SaveOrUpdateEvent evt)
    {
        var entity = evt.Entity as IAuditableEntity;
        if (entity != null)
        {
            ProcessEntityBeforeUpdate(entity);
        }
        return base.PerformSaveOrUpdate(evt);
    }

    internal virtual void ProcessEntityBeforeUpdate(IAuditableEntity entity)
    {
        entity.UpdateDate = DateTime.Now;
    }
}

and it works great for updates, but it also gets run for Save events (when I add new rows to the database). I don't want it to fire for new rows. I tried to change the code to listen to Update events only but I can't work it out.

I tried to change the class to inherit from DefaultUpdateEventListener but there's no UpdateEvent (only SaveOrUpdate events or PreUpdate or PostUpdate)

I'm wondering if I should use the PreUpdate event and making my listener inherit from DefaultUpdateEventListener but then I'm not sure which method I need to override. There is no Update method to override.


回答1:


You could make your class implement the IPreUpdateEventListener interface (and its OnPreUpdate method). Then add your class to the session event listerners through the config:

NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
cfg.EventListeners.PreUpdateEventListeners = 
    new IPreUpdateEventListener[] {new YourEventListener()};
sessionFactory = cfg.BuildSessionFactory();



回答2:


It appears that there is a PerformUpdate event that can be overridden from the DefaultSaveOrUpdateEventListener class

protected override void PerformUpdate(NHibernate.Event.SaveOrUpdateEvent @event, object entity, NHibernate.Persister.Entity.IEntityPersister persister)
{
    base.PerformUpdate(@event, entity, persister);
}


来源:https://stackoverflow.com/questions/8872542/how-to-configure-nhibernate-event-listeners-for-update-and-save

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!