Pak
Pak

Reputation: 2766

Nhibernate EagerLoad on demand

I am new to fluent nhibernate and encounter the following NHibernante error :

Initializing[Toto.Business.Catalog.Unit#059fb247-df11-4457-8a4d-7c8b984a155e]-failed to lazily initialize a collection of role: Toto.Business.Catalog.Unit.Values, no session or session was closed

when I try to access item.Product.Product.Unit.Values. I thought to solve it by using .Not.LazyLoad() on my overriding of IAutoMappingOverride but it brakes on other view that I can't touch.

I have try some things like :

        NHibernateSession.Current.Query<BasketItem>()
                         .Fetch(e => e.Product.Product)
                         .ThenFetchMany(e => e.Unit.Values);

that don't change anything. I try to add:

   foreach (var item in CurrentUserBasket.Items.Where(item => item.Product != null && item.Product.Product != null && item.Product.Product.Unit != null))
            {               
                NHibernateSession.Current.Load<IList<UnitValue>>(item.Product.Product.Unit.Values);
            }

But I gives me error :

Unable to locate persister for the entity named 'System.Collections.Generic.IList`1[[Toto.Business.Catalog.UnitValue, Toto.Business, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]'.

EDIT

I want to have access to item.Product.Product.Unit.Values in my View, how do I do that?

Upvotes: 0

Views: 144

Answers (1)

Phill
Phill

Reputation: 18796

I don't believe this is possible with the Query<T> api, I'm pretty sure it only allows you to fetch a max depth of 1.

You can do this with QueryOver<T> API.

Something along the lines of

Product product = null;
Product nestedProduct = null;
Unit unit = null;
Value value = null;

var result = NHibernateSession
    .Current
    .QueryOver<BasketItem>()
    .JoinAlias(x => x.Product, () => product)
    .JoinAlias(x => x.Unit, () => unit)
    .JoinAlias(() => product.Product, () => nestedProduct)
    .JoinAlias(() => unit.Values, () => value)

Also its worth remembering, FluentNHibernate is just an alternative mapping for nhibernate, it doesn't change how you use nhibernate in terms of querying.

Upvotes: 1

Related Questions