Malcolm
Malcolm

Reputation: 12874

Nhibernate - Cannot fetch multiple collections in a single query

I have a entity Recipe and it has 3 collections images, comments and ingredients. They are mapped as a bag.

For a website I want to load the recipe collections with the recipe i.e. not lazy load so I discovered I could do that using this query:

from Recipe r
left join fetch r.Images
left join fetch r.Ingredients
left join fetch r.Comments

But this gives an exception:

Cannot fetch multiple collections in a single query if one of them is a bag

So how do I not lazy load my recipe and have the collections loaded allowing for the fact that there may not be any rows in that collection? I'm new at this and need an explanation.

Upvotes: 0

Views: 2786

Answers (3)

Steve Willcock
Steve Willcock

Reputation: 26889

Changing to Sets will allow this, but are you sure this is what you want to do?

'Fetch'ing multiple child collections in this way is potentially very bad for your system performance. You could very easily end up with a Cartesian product fetching many times the number of rows you need from the database.

Ayende points out the potential problem here

You might want to look at session.CreateMultiQuery() or session.CreateMultiCriteria() instead.

Upvotes: 1

Samuel Goldenbaum
Samuel Goldenbaum

Reputation: 18939

To avoid a Cartesian query. I would execute 3 queries all using futures and left outer joins.

Upvotes: 1

Frederik Gheysels
Frederik Gheysels

Reputation: 56984

Map the collections as a set.

A bag is a collection that can contain multiple copies of the same item.

Upvotes: 0

Related Questions