开发者

How do I set the Fetchmode on all assocations of a nHibernate ICriteria in one go?

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 particu开发者_运维知识库lar 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);


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜