NHibernate Eager loading multi-level child objects
Asked Answered
A

1

26

I have a hierarchy of objects, Order, Contact, Address:

public class Order {
     public virtual Contact BillingContact { get; set; }
}

public class Contact {
     public virtual Address Address { get; set; }
}

I want to query an order by id, and eager load the billingcontact, along with it's address.

var criteria = DetachedCriteria.For<Order>()
     .SetFetchMode("BillingContact", FetchMode.Eager)

This criteria eager loads the BillingContact, but understandably not the address of the BillingContact. If i add:

     .SetFetchMode("BillingContact.Address", FetchMode.Eager)

This does nothing to help.

Also note that these relationships are unidirectional:

public OrderMap()
{
    References(x => x.BillingContact)
        .Not.Nullable()
        .Cascade.All();
}

public ContactMap()
{
    HasOne(x => x.Address)
        .Cascade.All()
        .FetchType.Join();
}

public AddressMap()
{
    Map(x => x.Address1);
} 

How can I construct a criteria object that will load the child of the child? Do these relationship mappings seem correct?

Autostrada answered 18/2, 2009 at 23:3 Comment(0)
A
27

I believe you might need to add an alias to BillingContact to allow you access to it's Address.

Something like:

var criteria = DetachedCriteria.For<Order>()
  .CreateAlias("BillingContact", "bc")
  .SetFetchMode("BillingContact", FetchMode.Eager)
  .SetFetchMode("bc.Address", FetchMode.Eager)
Artificer answered 19/2, 2009 at 14:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.