Load collections eagerly in NHibernate using Criteria API

会有一股神秘感。 提交于 2019-12-11 16:06:08

问题


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


回答1:


You're trying to do a cartesian product here. I think NHibernate requires mapping the relations as sets instead of bags to do that, since bags allow duplicates.

Anyway, cartesian products are very inefficient. Use a multi-query or future queries instead.

See:

  • Nhibernate: eager loading two child collections (one being a component list)
  • https://nhibernate.jira.com/browse/NH-1471
  • http://nhibernate.info/blog/2008/09/06/eager-loading-aggregate-with-many-child-collections.html
  • http://ayende.com/Blog/archive/2010/01/16/eagerly-loading-entity-associations-efficiently-with-nhibernate.aspx


来源:https://stackoverflow.com/questions/2839357/load-collections-eagerly-in-nhibernate-using-criteria-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!