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

childrenevent handlingevent-listenereventsnhibernate

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?

Best Answer

Not 100% related to your question but if you map with inverse="true" on your collection you atleast dont get the insert AND update statements.

Related Topic