5
votes

I have a fairly deep object graph (5-6 nodes), and as I traverse portions of it NHProf is telling me I've got a "Select N+1" problem (which I do).

The two solutions I'm aware of are

  1. Eager load children
  2. Break apart my object graph (and eager load)

I don't really want to do either of these (although I may break the graph apart later as I forsee it growing)

For now....

Is it possible to tell NHibernate (with FluentNHibernate) that whenever I try to access children, to load them all in one go, instead of select-n+1-ing as I iterate over them?

I'm also getting "unbounded results set"s, which is presumably the same problem (or rather, will be solved by the above solution if possible).

Each child collection (throughout the graph) will only ever have about 20 members, but 20^5 is a lot, so I don't want to eager load everything when I get the root, but simply get all of a child collection whenever I go near it.

Edit: an afterthought.... what if I want to introduce paging when I want to render children? Do I HAVE to break my object graph here, or is there some sneakiness I can employ to solve all these issues?

2

2 Answers

10
votes

It sounds to me that you want to pursue the approach of using your domain model rather than creating a specific nhibernate query to handle this scenario. Given this, I would suggest you take a look at the batch-size attribute which you can apply to your collections. The Fluent NHibernate fluent interface does not yet support this attribute, but as a work around you can use:

HasMany(x => x.Children).AsSet().SetAttribute("batch-size", "20")

Given the general lack of information about your exact scenario, I cannot say for sure whether batch-size is the ideal solution, but I certainly recommend you give it a go. If you haven't already, I suggest you read these:

http://www.nhforge.org/wikis/howtonh/lazy-loading-eager-loading.aspx

http://nhibernate.info/doc/nhibernate-reference/performance.html

The NHibernate performance documentation will explain how batch-size works.

Edit: I am not aware of any way to page from your domain model. I recommend you write NH queries for scenarios where paging is required.

0
votes

Edit: an afterthought.... what if i want to introduce paging when i want to render children? do i HAVE to break my object graph here, or is there some sneakyness i can employ to solve all these issues?

Well, if you only load the children then you can page them :). But if you want something like : LoadParent AND PageChildren , then I don't think you can do that.