Ritesh,
I've been trying to figure this out on my own, but I'm afraid I need
to ask you for some help.
I'm trying to create a fetching strategy to eager load two (at the
moment) lists on Order entity:
class Order {
public IList<OrderItem> Items;
public IList<OrderDetail> Details;
}
My fetching strategy's Define method is as follows:
void Define(IRepository<Order> repository){
repository.With(o => o.Items);
repository.With(o => o.Details);
}
My test DB contains 3 items and 9 details for an order. Resulting SQL
returns Cartesian product (as I understand it, ICriteria, which
NHibernate.Linq relies on, does Cartesian joins) - 27 rows (3*9).
Now, the problem:
1. For some reason, both Items and Details collections contain 27
entries each. I check IPostLoadEventListener.OnPostLoad() and see that
3 Items and 9 Details are being hydrated and created, but then lists
are populated by repeating each of the elements 9 and 3 times
respectively.
2. I tried to replicate this in nCommon unit tests by introducing an
extra entity, table, etc, but couldn't - lists seem to be properly
populated. This threw me off completely as I cannot see any difference
in the code.
3. In my case, Detail contains complex identifier (composite-id) with
one of the elements in this identifier being complex in it's turn
(composite-id as well for the element) and mapped as <key-many-to-one>
node in hbm file. Maybe this has some sort of side effect on the
result? I do have defined Equals(), getHashCode() methods on
everything I can think of for this scenario - thinking that NHibernate
may do some sort of comparison before adding elements to a collection.
4. In general it seems like a bad idea to load any entity with eagerly
fetched multiple lists, because this will lead to a possible explosion
of returned data which is based on Cartesian product. Am I correct in
my understanding? I was searching for details on the net and found
that a better approach is to use MultiQuery or MultiCriteria methods
[1]. Why doesn't this happen automatically (is it even possible to
make NHibernate to use MultiCriteria in this case)?
Hopefully you can find some time to answer these questions. I do
realize that my knowledge in these areas is quite limited and it might
be a case that these limitations are well understood and I am just not
aware of them.
Thank you in advance,
Alex
[1] -
http://nhforge.org/blogs/nhibernate/archive/2008/09/06/eager-loading-aggregate-with-many-child-collections.aspx