1

I want to eager load a collection of objects efficiently. The following code sample shows what I'm doing now. But the c.CommunicationMethods & c.Roles objects are loaded 1 Sql statement at a time. I saw references to the bag & batch-size... can someone provide sample mapping file references? Is that my best option? Can I keep my loop here & batch my sql statements?

Both CommunicationMethods & Roles are defined as many-to-one in the Contacts mapping file.

NHibernateUtil.Initialize(entity.Collection1);
NHibernateUtil.Initialize(entity.Collection2);

NHibernateUtil.Initialize(entity.Contacts);
foreach (var c in entity.Contacts)
{
NHibernateUtil.Initialize(c.CommunicationMethods);
NHibernateUtil.Initialize(c.Roles);
}
2
  • why don't you use prefetch paths while querying? Commented Jul 13, 2012 at 6:14
  • I'm not sure what you mean. Do you mean this: .SetFetchMode("CommunicationMethods", FetchMode.Eager) ? If not, can you point me to an example? Commented Jul 13, 2012 at 13:22

1 Answer 1

4

instead of Initialize you could specify which collections to initialise while querying and with multiqueries you could hold the cartesian product small.

// load all collection1 into cache
session.QueryOver<Entity>()
    .Where(filter)
    .Fetch(e => e.Collection1).Eager
    .Future();

// load all collection2 into cache
session.QueryOver<Entity>()
    .Where(filter)
    .Fetch(e => e.Collection2).Eager
    .Future();

var results = session.QueryOver<Entity>()
    .Where(filter)
    .Fetch(e => e.Contacts).Eager
    .Fetch(e => e.Contacts.CommunicationMethods).Eager
    .Fetch(e => e.Contacts.Roles).Eager
    .List();

// results contain all entities with initialised collection1, collection2, contacts, contact.role, contact.CommunicationMethod
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.