What's the best way to refresh entities in nhibernate
Asked Answered
E

2

21

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?

Endways answered 5/11, 2010 at 14:2 Comment(0)
P
30

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.

Portrait answered 5/11, 2010 at 14:57 Comment(4)
Sorry to say this but that does not work:( It works in this scenario: 1) pEntity.pCollection is empty 2) I add an item to collection in database manually 3) I can see updated collection but that does not work in this scenario: 1) pEntity.pColelction has a value 2) I change a value of an item in pEntity.pCollection manually in database 3) after refreshing I still have the same items in pEntity.pCollection...Endways
Refresh alone should work in that scenario if pCollection cascades. Otherwise, you have to manually refresh its items too.Portrait
Refresh alone seems to be sufficient for me for both adds and removes to a lazy collection on an entity. A link to any known issues or caveats would be helpful if there are special cases I should be aware of.Theiss
@KalebPederson: I believe this was fixed in the latest releases (keep in mind 3.0 hadn't been released when I wrote that answer, and 2.x wasn't getting fixes since the release of 2.1.2)Portrait
B
3

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.

Byproduct answered 14/11, 2012 at 18:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.