views:

333

answers:

2

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?

A: 

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.

Kenny Eliasson
True, but I think this would require making the relationship uni-directional in the object model (the SubArea would have a reference to Area aswell) but in this case I don't want or need that.
James Allen
A: 

NH issues INSERT statement in order to know the Id of the object if it cannot known (IDENTITY or SEQUENCE for example).

So if you want to void that you need to use an id generator that do not require roundtript to the DB (such as guid or guid.combo).

Dmytrii Nagirniak