NHibernate save / update event listeners: listening for child object saves

Posted by James Allen on Stack Overflow See other posts from Stack Overflow or by James Allen
Published on 2009-12-29T10:37:06Z Indexed on 2010/04/22 7:03 UTC
Read the original article Hit count: 570

I have an Area object which has many SubArea children:

public class Area
{
    ...
    public virtual IList<SubArea> SubAreas { get; set; } 
}

he children are mapped as a uni-directional non-inverse relationship:

public class AreaMapping : ClassMap<Area>
{
    public AreaMapping()
    {
        HasMany(x => x. SubAreas).Not.Inverse().Cascade.AllDeleteOrphan();
    }
}

The Area is my aggregate root. When I save an area (e.g. Session.Save(area) ), the area gets saved and the child SubAreas automatically cascaded.

I want to add a save or update event listener to catch whenever my areas and/or subareas are persisted. Say for example I have an area, which has 5 SubAreas. If I hook into SaveEventListeners:

Configuration.EventListeners.SaveEventListeners = 
    new ISaveOrUpdateEventListener[] { mylistener };

When I save the area, Mylistener is only fired once only for area (SubAreas are ignored). I want the 5 SubAreas to be caught aswell in the event listener. If I hook into SaveOrUpdateEventListeners instead:

Configuration.EventListeners.SaveOrUpdateEventListeners = 
    new ISaveOrUpdateEventListener[] { mylistener };

When I save the area, Mylistener is not fired at all. Strangely, if I hook into SaveEventListeners and SaveOrUpdateEventListeners:

Configuration.EventListeners.SaveEventListeners = 
    new ISaveOrUpdateEventListener[] { mylistener };
Configuration.EventListeners.SaveOrUpdateEventListeners = 
    new ISaveOrUpdateEventListener[] { mylistener };

When I save the area, Mylistener is fired 11 times: once for the area, and twice for each SubArea! (I think because NHIbernate is INSERTing the SubArea and then UPDATING with the area foreign key).

Does anyone know what I'm doing wrong here, and how I can get the listener to fire once for each area and subarea?

© Stack Overflow or respective owner

Related posts about nhibernate

Related posts about event-handling