Fernando
Fernando

Reputation: 457

Change value of a propery before update nhibernate

I'm trying to change a entity property value in the PreUpdateEventListener, but the new value is not persisted, the generated sql contains the old value of the property.

The code is very simple:

        public bool OnPreUpdate(PreUpdateEvent @event)
    {
        var p = @event.Entity.GetType().GetProperty("audit_version");

        if (p != null && p.CanWrite && p.CanRead)
        {
            int val = (int)p.GetValue(@event.Entity, null);
            p.SetValue(@event.Entity, val + 1, null);
        }

        return false;
    }

and the configuration configuration.EventListeners.PreUpdateEventListeners = new IPreUpdateEventListener[1] { new AuditListener() };

Tks a Lot!

Upvotes: 2

Views: 1025

Answers (1)

James Kovacs
James Kovacs

Reputation: 11651

You should be updating @event.State, not @event.Entity. @event.State contains the data to be used in the update. You might want to update @event.Entity as well to keep everything consistent, but by the time OnPreUpdate fires, the entity's data has already been read into State. You can find the previous state as it exists in the database in @event.OldState.

Upvotes: 5

Related Questions