0

I have an object that has many assocations to other objects. All of these are fetched lazily by nHibernate, which is good in almost all cases.

In a particular scenario, in this case an export of a lot of records, I want to set the Fetchmode to eager on all associations. Is there a way to do this, without having to manually specify each one:

ICriteria crit = CreateCriteria().
  .SetFetchMode("Address", FetchMode.Eager)
  .SetFetchMode("ContactPerson", FetchMode.Eager);

The method I would like to find, but haven't been able to:

// This doesn't work.
ICriteria crit = CreateCriteria().SetFetchMode(FetchMode.Eager);
Ruben Steins
  • 2,782
  • 4
  • 27
  • 48

2 Answers2

2

You could try to use the NHibernate Metadata.

ISessionFactory sessionFactory;

Type type = typeof(MyEntity);
IClassMetadata meta = sessionFactory.GetClassMetadata(type);
foreach (string mappedPropertyName in meta.PropertyNames)
{
    IType propertyType = meta.GetPropertyType(mappedPropertyName);
    if (propertyType.IsAssociationType)
    {
      // initialize property
      // recursively go through the properties of the associated entity
    }

    if (propertyType.IsCollectionType)
    {
      // initialize collection
      // if it is a collection of entities, 
      // recursively go through the properties of the associated entity

      // Use NHibernateUtil.Initialize
    }
}

I'm not sure if it is worth the effort.

Stefan Steinegger
  • 63,782
  • 15
  • 129
  • 193
  • Thanks. I'm performing the operation at a level where I don't have access to the sessionfactory, so I doubt this appraoch will do me any good. But I will look into MetaData! – Ruben Steins Dec 23 '09 at 09:58
  • You could implement this whole stuff where you know the session factory and provide it by an interface to the other part. – Stefan Steinegger Dec 23 '09 at 10:16
1

No, there is no way to do this in a blanket fashion.

David M
  • 71,481
  • 13
  • 158
  • 186
  • Alas... tis the truth. I've used a different approach by fetching the records one by one and appending to the export, flusing the session in between. Now, the server doesn't run out of memory anymore. This at least is the quick fix we implemented to get the release out :P – Ruben Steins Jan 06 '10 at 14:00