nhibernatenhibernate-3

Eagerly loading an association after Get()


I am trying to find a better way to load the relation than this:

result = session.Get<Author>(id);
Course course = result.Courses.FirstOrDefault();

I can do this with QueryOver API like this:

result = session.QueryOver<Author>()
                .Where(item => item.Id == id)
                .Fetch(item => item.Courses).Eager
                .SingleOrDefault();

I guess it would generate the same SQL but it is too verbose.

Is there a way to do something like below?

session.Fetch(result, author => author.Courses);

Solution

  • Get is driven by mapping. If it really make sense, change your mapping (but I would not do that). There is no runtime switch of constructed mapping.

    From my experience, few more select statements during the Get(id) is not an issue... And for N + 1 you've already shown the better solution in your question.

    Interesting reading about eagar loading: http://nhforge.org/wikis/howtonh/lazy-loading-eager-loading.aspx