Katalonis
Katalonis

Reputation: 701

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?

Upvotes: 21

Views: 20879

Answers (2)

Erik Hart
Erik Hart

Reputation: 1324

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.

Upvotes: 3

Diego Mijelshon
Diego Mijelshon

Reputation: 52725

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.

Upvotes: 30

Related Questions