views:

238

answers:

4

Hi, My objects of type Object1 contain List Children1 property. I would love to get these objects without children.

Seems like detachedCriteria.SetFetchMode ("Children1", FetchMode.Lazy) should be the thing, but apparently it's not :( I tried getting the data in using (new SessionScope()) and setting null to .Children1 but it didn't succeed (the data was already fetched).

Any ideas would be appreciated.

A: 

When you map the collection, are you specifying not to use lazy loading? Try specifying lazy loading at this point.

David M
I did not specify anything, so default values apply, however I don't know what is a default value.BTW, problem is "solved". I'll add a comment in a few minutes.
wysek
A: 

We had the same problem in our current solution and setting Lazy in the mapping didn't work. We had to set default-lazy to true and suddenly it worked.

This would work best if all relations should be lazy by default.

Henning
Ok, I've set Lazy=true on the HasMany attribute and now it works,but in other (more frequent) use-cases I need eager loading...I would prefer to have eager loading by default and lazy on demand,but if that's too complicated... I'll try fixing those other use-cases (now I get LazyInitializationException ... failed to lazily initialize a collection of role ... no session or session was closed)
wysek
You get that exception because your session has been closed, like the message says. You need to inject your session into your repository/dataaccess class and control the session lifetime from the outside.You'd want the session to last the entire request lifetime, especially if you have lazy loading.We use a UnitOfWork attribute on our mvc controllers to initiate and close down a session, and if any nhibernate exceptions are thrown, it is cought and session is rolled back
Henning
A: 

When using the ICriteria API to retrieve your entities, you can specify (override) the fetchmode that has to be used for the associations:

ICriteria crit = session.CreateCriteria (typeof(MyEntity));
crit.SetFetchMode ("someAssociationPath", FetchMode.Lazy);
Frederik Gheysels
I've tried that. Have you actually read my question? ;)BTW, problem is "solved". I'll add a comment in a few minutes.
wysek
A: 

It seems to me that you are using one-to-one mapping. In this case lazy loading will not work by design. If it's so please check this article. Otherwise please provide a bit more code and mappings.

zihotki
Why does it seem to you as a one-to-one mapping? when Object1 has List<Children1> I think it is clear that it is at least one-to-many.BTW, problem is "solved". I'll add a comment in a few minutes.
wysek
@wysek, you didn't provided any code so I just assumed the most likelihood reason from my point of view. Sorry, I'm not well at mind reading.
zihotki