nHibernate Eager Loading at runtime

2019-08-29 10:53发布

We're using NCommon's UnitOfWorkScope which wraps nHibernate ISession functionality. Our goal is to eager-load complex properties on demand vs. always eagerly loading them via configuration. The idea is that a given service that retrieves an entity can be customized a bit by the calling code - sometimes we want only the parent entity to be hydrated, other times we may want the complex child properties hydrated, too.

To accomplish this, we're doing the following:

  var iSession = unitOfWorkScope.CurrentUnitOfWork<NHUnitOfWork>().GetSession<ParentEntity>();

  iSession.CreateCriteria<ParentEntity>().SetFetchMode("Children", FetchMode.Eager);

Once that's setup on the session, we use NCommon's IRepository functionality to retrieve the entities:

  var parent = parentRepository.FirstOrDefault(x => x.Id == 123);

However, when we check the parent.Children collection we get:

  NHibernate.Collection.Generic.PersistentGenericBag<ChildEntity>

... which tells me the Eager-loading did not occur. When we modify the NH mapping to always force an eager load, then we see the children correctly.

Can anyone shed light on this? I assume we're missing something since the FetchMode.Eager is ignored.

1条回答
登录 后发表回答