简体   繁体   中英

Misplaced call `OnPreUpdate` in Auditor Event listener implementation in NHibernate

I have a project by using NHibernate 3. I used Auditor Event Listener in NHibernate for Trim of string properties in my entities.

My code is :

public class AuditorEventListener : IPreInsertEventListener, IPreUpdateEventListener
{
    public bool OnPreInsert(PreInsertEvent preInsertEvent)
    {
        Correction(preInsertEvent.Entity);
        return false;
    }

    public bool OnPreUpdate(PreUpdateEvent preUpdateEvent)
    {
        Correction(preUpdateEvent.Entity);
        return false;
    }

    internal static void Correction(object entity)
    {
        var properties = entity.GetType().GetProperties().Where(p =>  p.PropertyType == typeof(String));

        foreach (var item in properties)
        {
            var result = item.GetValue(entity, null).ToString();
            result = result.Trim();
            item.SetValue(entity, result, null);
        }
    }
}

NHibernate config is :

<event type="pre-insert">
  <listener class="NS.NHibernate.AuditorEventListener, NS.NHibernate" />
</event>
<event type="pre-update">
  <listener class="NS.NHibernate.AuditorEventListener, NS.NHibernate" />
</event>

I used below commands for save and update for entities:

SessionInstance.Save(item);
SessionInstance.Update(item);

My problem is in save entity. When I call save method, OnPreInsert method is called. When I call CommitTransaction() OnPreUpdate is called Automatically.

Also I used Concurrency in NHibernate and this Automatically OnPreUpdate call caused to value of Version property in database be 2 instead of 1 So far no problem but for next update of this entity concurrency error would happen because value of version in this entity is 1 but value of version in database is 2 .

Why is OnPreUpdate called?

I don't know if it helps but anyway whenever you update something in entity you also should update it in preInsertEvent.State/preUpdateEvent.State. For more information look at this post http://ayende.com/blog/3987/nhibernate-ipreupdateeventlistener-ipreinserteventlistener Hope this helps

Why is OnPreUpdate called?

It looks like your "session.FlushMode" set in "FlushMode.Auto" or "FlushMode.Commit" You can use "FlushMode.Never" but you have to explicitly call "session.Flush()"

Have you seen an opportunity to use interceptor, it looks more powerfully than EventListener

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM