Load collections eagerly in NHibernate using Criteria API

Posted by Zuber on Stack Overflow See other posts from Stack Overflow or by Zuber
Published on 2010-05-15T07:56:42Z Indexed on 2010/05/15 8:04 UTC
Read the original article Hit count: 288

I have an entity A which HasMany entities B and entities C. All entities A, B and C have some references x,y and z which should be loaded eagerly.

I want to read from the database all entities A, and load the collections of B and C eagerly using criteria API. So far, I am able to fetch the references in 'A' eagerly. But when the collections are loaded, the references within them are lazily loaded.

Here is how I do it

            AllEntities_A =
            _session.CreateCriteria(typeof(A))
            .SetFetchMode("x", FetchMode.Eager)
            .SetFetchMode("y", FetchMode.Eager)
            .List<A>().AsQueryable();

The mapping of entity A using Fluent is as shown below. _B and _C are private ILists for B & C respectively in A.

        Id(c => c.SystemId);
        Version(c => c.Version);
        References(c => c.x).Cascade.All();
        References(c => c.y).Cascade.All();

        HasMany<B>(Reveal.Property<A>("_B"))
            .AsBag()                
            .Cascade.AllDeleteOrphan()
            .Not.LazyLoad()
            .Inverse()
            .Cache.ReadWrite().IncludeAll();
        HasMany<C>(Reveal.Property<A>("_C"))
            .AsBag()
            .Cascade.AllDeleteOrphan()
            .LazyLoad()
            .Inverse()
            .Cache.ReadWrite().IncludeAll();

I don't want to make changes to the mapping file, and would like to load the entire entity A eagerly. i.e. I should get a List of A's where there will be List of B's and C's whose reference properties will also be loaded eagerly

© Stack Overflow or respective owner

Related posts about nhibernate

Related posts about criteria-api