Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to refresh entities in nhibernate

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?

like image 288
Katalonis Avatar asked Nov 05 '10 14:11

Katalonis


People also ask

What does NHibernate flush do?

An nHibernate session maintains all changes to the object model. At some point, it needs to synchronize these changes with the database.

What is NHibernate session?

The NHibernate session encapsulates a unit of work as specified by the unit of work pattern.


2 Answers

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.

like image 117
Diego Mijelshon Avatar answered Oct 21 '22 02:10

Diego Mijelshon


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.

like image 25
Erik Hart Avatar answered Oct 21 '22 02:10

Erik Hart