views:

72

answers:

2

I need to find out how to perform some action (flush cache) when an object of type X is updated.

So when I save object of type Y, nothing is done, when I save unchanged object of type X nothing should happed, but when this object is changed and UPDATE is made, I want to know it.

I tried various NHibernate events (IPostUpdateEventListener, IFlushEntityEventListener, etc.) but did not succeed.

Can anybody help please? Thanks

+1  A: 

you want an IPostUpdateEventListener. why dont you post your code that doesnt work, then we can help ;)

Andrew Bullock
A: 

I was experiencing problem in implemented method, because in some cases I had to call the same method on default implementation, otherwise the code path ended in my code.

private readonly DefaultFlushEntityEventListener _impl = new DefaultFlushEntityEventListener();

public void OnFlushEntity(FlushEntityEvent flushEntityEvent)
{
   ... my code goeas here ... 
   _impl.OnFlushEntity(flushEntityEvent);
}

In OnFlush method of IFlushEntityEventListener I cannot detect dirty properties... etc.

But what really works is (thanks Andrew) is this code

public void OnPostUpdate(PostUpdateEvent postUpdateEvent)
{
   var dirtyProperties = postUpdateEvent.Persister.FindDirty(postUpdateEvent.State, postUpdateEvent.OldState, postUpdateEvent.Entity, postUpdateEvent.Session);
   int dirty = dirtyProperties.Length;

   if (dirty == 0) // I want detect only modififed entities
      return;
   Trace.WriteLine(string.Format("OnPostUpdate({0}, {3}) in session#{1} - dirty props. {2}", postUpdateEvent.Entity.GetType().Name, postUpdateEvent.Session.GetHashCode(), dirty, postUpdateEvent.Entity.GetHashCode()));
   lock (_objects)
   {
     if (!_objects.Contains(postUpdateEvent.Entity)) // I will manipulate this list in `AbstractFlushingEventListener.PostFlush` method
        _objects.Add(postUpdateEvent.Entity);
   }
 }
Karel Frajtak