I would like to refresh an entity and all its child collections. What is the best way to do this? I'm talking about nhibernate:)
I've read about session.Evict, session.Refresh...
But I'm still not sure if doing like:
RefreshEntity<T>(T entity)
{
session.Evict(entity);
session.Refresh(entity);
}
would work exactly how I want it to work
Is it going to work? If not What else I can do?
An nHibernate session maintains all changes to the object model. At some point, it needs to synchronize these changes with the database.
The NHibernate session encapsulates a unit of work as specified by the unit of work pattern.
Refresh after Evict probably won't work.
Theoretically, Refresh
alone should be enough. However, it has known issues when elements of child collections have been deleted.
Evict
followed by Get
usually gets things done.
Refresh(parentObject) would be a good option, but for me, it first fetched all children one by one with single requests. No batching, no subquery, no join. Very bad!
It helped to .Clear() the child collection of the parent object; I also evicted the child objects before.
(these had been changed by a HQL update before where multiple inserts by parent/children SaveOrUpdate would cause expensive clustered index rebuilds).
EDIT: I removed the HQL update again, since the query (decrement index by a unique, large number) was more expensive than hundreds of single row updates in a batch. So I ended up in a simple SaveOrUpdate(parentObject), with no need to refresh.
The reason was a child collection with unique constraint on ParentID and Index (sequential number), which would result in uniqueness violations while updating the changed children items. So the index was first incremented by 1000000 (or an arbitrary high number) for all children, then after changes, decremented again.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With