Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
412 views
in Technique[技术] by (71.8m points)

nhibernate - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"/>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...