[NHibernate] Update your time stamp automaticaly

I was writing lately about problem with a lack of precision in date. I said about having many tables with column with time stamp of last update. You can figure it about that changing it by hand is very painful.

You can automatize that by using Listener. Listener – ekm – listen for changes that are sent to database. You can define Listner like that

public class LastChangeListener : IPreUpdateEventListener, IPreInsertEventListener
{
    public bool OnPreUpdate(PreUpdateEvent @event)
    {
        var model = @event.Entity as ILastChange;
        if (model == null)
        {
            return false;
        }

        var time = DateTime.Now;
        Set(@event.Persister, @event.State, "LastChange", time);
        model.LastChange = time;
        return false;
    }

    public bool OnPreInsert(PreInsertEvent @event)
    {
        var model = @event.Entity as ILastChange;
        if (model == null)
        {
            return false;
        }

        var time = DateTime.Now;
        Set(@event.Persister, @event.State, "LastChange", time);
        model.LastChange = time;
        return false;
    }

    private void Set(IEntityPersister persister, object[] state, string propertyName, object value)
    {
        var index = Array.IndexOf(persister.PropertyNames, propertyName);
        if (index == -1)
            return;
        state[index] = value;
    }
}

Entity have property of type DateTime and name of LastChange. Those entities implements interface ILastChange, which requires to implement property of name LastChange.

For NHibernate to start using Listener it must be registered to use when you create SessionFactory. If you use an Fluent NHibernate registration should like this:

Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2012
.ConnectionString(c => c.FromAppSetting("ConnectionString")))
.ExposeConfiguration(config =>
            {
        config.EventListeners.PreUpdateEventListeners = new IPreUpdateEventListener[]
        {
            new LastChangeListener(),
        };

        config.EventListeners.PreInsertEventListeners = new IPreInsertEventListener[]
        {
        new LastChangeListener(),
        };
}).BuildSessionFactory();

Sources

Programista, domowy kucharz i "amator amerykańskiej polityki". Zbieram informacje z całej sieci, po odrzuceniu chwastów i dodaniu swojej opinii publikuje na blogu.