Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IPreUpdateEventListener and dynamic-update="true"

I have been trying to do a very simple auditing scenario following Ayende's blog which seem to be the resource everyone is refering to when it comes to IPreUpdateEventListener and IPreInsertEventListener.

However no matter how hard I tried, I couldn't get it to work. The event fired correctly, everything looked ok when I stepped through it but no update of my "changedtime" was ever issued to the database.

I spent about a day googling this and finally found the answer here.

It just won't work when you have your entity mapped with dynamic-update="true". And sure enough, that was the case for me. Since it was so hard for me to find this piece of information, is it uncommon to use dynamic-update="true"? We use it on all our entities.

As this is a major bump in the road for us I wanted to ask if there's any way around this at all?

I have been looking at IInterceptor but it's always refered to as outdated, so what's the drawbacks with this? Also I haven't been able to find a really good tutorial on how to archieve the same auditing (with insert/update timestamps) with IInterceptor (I'm fairly new to NHibernate).

Any help would be appreciated!

like image 986
ds99jove Avatar asked Feb 23 '11 06:02

ds99jove


2 Answers

I ran into this exact issue. This is how I fixed it:

public class MyFlushEntityEventListener : DefaultFlushEntityEventListener
{
    protected override void DirtyCheck(FlushEntityEvent e)
    {
        base.DirtyCheck(e);
        if (e.DirtyProperties != null &&
            e.DirtyProperties.Any() &&
            //ITrackUpdate is my inteface for audited entities
            e.Entity is ITrackUpdate)
            e.DirtyProperties = e.DirtyProperties
             .Concat(GetAdditionalDirtyProperties(e)).ToArray();
    }

    static IEnumerable<int> GetAdditionalDirtyProperties(FlushEntityEvent @event)
    {
        yield return Array.IndexOf(@event.EntityEntry.Persister.PropertyNames, 
                                   "UpdateTime");
        yield return Array.IndexOf(@event.EntityEntry.Persister.PropertyNames, 
                                   "UpdateUser");
        //You can add any additional properties here.
        //Some of my entities do not track the user, for example.
    }
}

Then, just replace the event listener in the NH config file:

<listener type="flush-entity"
          class="MyFlushEntityEventListener, MyAssembly"/>
like image 169
Diego Mijelshon Avatar answered Oct 20 '22 08:10

Diego Mijelshon


I had the same issue, however I found I could work around it by using OnFlushDirty.

You can find my solution here.

like image 37
Daniel Little Avatar answered Oct 20 '22 08:10

Daniel Little