c# - Is it possible for a NHibernate EventListener to modify the contents of a HasMany relationship? -


i working application has several domain objects own mapping similar list of hasmany domain objects. application running on-top of brownfield database, structure cannot changed. each parent fluent mapping looks similar to:

hasmany(x => x.locations)   // location type applicable given parent     .asbag()     .keycolumn("parent_sk")     .lazyload()     .inverse()     .cascade.alldeleteorphan(); 

every time location on parent domain object changed associated parent objects must have location properties synchronized (some new locations added, deleted, others left is) within same transaction.

i've created , registered nhibernate event listener implements ipreupdateeventlistener, ipreinserteventlistener, , ipredeleteeventlistener. event listener fires expected when change made location domain objects.

once fired proper parents found , location collections manipulated in order add/remove locations. parents sent appropriate repository save method. i'd expect changes locations collection cascade. not case.

when debugging i've verified expected values present in collection, nothing modified in database, nor attempted far can tell via show_sql logs. if in process modify non-relationship property on parent changes indeed persisted on parent, yet children remain unchanged.

is there proper way configure listener modify children of hasmany in cascade?

i say, answer found in q&a:

that in fact in ayende's article:

...here comes subtlety, however. cannot update entity state. reason quite simple, the entity state extracted entity , placed in entity state, change make entity state not reflected in entity itself. may cause database row , entity instance go out of sync, , make cause whole bunch of nasty problems wouldn’t know begin debugging.

and description how solve issue:

you have update both entity , the entity state in these 2 event listeners (this not case in other listeners, way)...

a small code snippet, must adjusted above needs (handling collection elements)

public bool onpreupdate(preupdateevent @event) {     ...     set(@event.persister, @event.state, "updatedat", time); ...  // way how assure state updated private void set(ientitypersister persister, object[] state           , string propertyname, object value) {     var index = array.indexof(persister.propertynames, propertyname);     if (index == -1)         return;     state[index] = value; } 

so, keeping both entity , entity state updated, solution here.


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -