Detached instances, parent child, orphan reconciliation

14 views
Skip to first unread message

Michael W Powell

unread,
Jun 1, 2025, 1:23:28 PMJun 1
to nhusers
Hello,

I intend to hopefully operate with detached instances, feeding WPF, view models, views, etc. And only gin up a new session (repository pattern) instance when it comes time to save again.

In doing that, I can attach the instances to the session again? Does NH do required differencing, of individual instances gauging the upsert requirement, as well as reconciling then would be ophaned instances?

Coming from EF, I was finding I had to do some manual deletion of orphaning records. Otherwise, would find that duplicate or multiple old records would come back when the query was refreshed. This I want to obviously avoid.

(F)NH advise appreciated.

Thanks!

Best,

Michael W. Powell

Frédéric Delaporte

unread,
Jun 1, 2025, 1:51:41 PMJun 1
to nhusers
Hi,

This is documented on nhibernate.info, documentation menu, Current Reference, The NHibernate reference, updating detached objects. NHibernate sessions have an Update method meant to attach entities to the session. (While Save is meant to add new entities in the session.) There is also a SaveOrUpdate to let NHibernate do the appropriate action, if the entity mapping allows to distinguish transient entities from detached ones. That is documented at the same place. Also pay attention to the cascade mapping property on entities, if you want "updates" (reattaching entities) to be cascade to relations of an updated entity. See https://nhibernate.info/doc/nhibernate-reference/manipulatingdata.html#manipulatingdata-graphs.

This Update method is not to be confused with the SQL update statement. It is no meant to trigger immediate SQL updates. The SQL operations to be performed on entities will happen on session flush as usual.

Instead of attaching entities in another session, you may use session disconnection and reconnect it for flushing after user interaction. That is a simpler approach, but not usable with all architectures, like having the entities loaded by a service, serialized and transmitted to a client, sent back by the client modified: of course in such case the entities sent back are not attached to the original session. Reconnecting the session here would not be enough: the original entities would have to be still available (kept in the service memory) and synchronized by the service code with the modified ones.
Reply all
Reply to author
Forward
0 new messages