jenson-button-event
jenson-button-event

Reputation: 18941

NHibernate - why is this collection not initialized / eager fetched?

Considering this:

var pfs = Session.QueryOver<Pegfile>()
                .JoinAlias(pf => pf.Responses, () => responseAlias)
                .List();

followed by this

Debug.Print(pfs.First().Responses.Count.ToString());

Why would that debug statment make NHibernate go back and requery the Response collection, surely it was initialized in the first query?

Upvotes: 1

Views: 331

Answers (2)

jenson-button-event
jenson-button-event

Reputation: 18941

Gets me every single time, why don't i remember? The join has to be a Lefty - grr love and hate NH in equal measures.

var pfs = Session.QueryOver<Pegfile>()
                .Left.JoinAlias(pf => pf.Responses, () => responseAlias)
                .List();

Upvotes: 0

Jamie Ide
Jamie Ide

Reputation: 49251

You need to use Fetch to pre-load the collection:

var pfs = Session.QueryOver<Pegfile>()
                .JoinAlias(pf => pf.Responses, () => responseAlias)
                .Fetch(pf => pf.Responses).Eager
                .List();

JoinAlias aliases the collection so that you can reference it in a where clause, etc.

I'm not sure about QueryOver but the LINQ provider also uses several optimizations that would cause the collection to not be loaded, such as issuing a SQL aggregate COUNT query when you invoke Count.

Upvotes: 3

Related Questions