NHibernate Eager Fetching Over Multiple Levels

后端 未结 5 1898
野的像风
野的像风 2020-12-12 22:53

I have a 3-leveled hierarchy of entities: Customer-Order-Line, which I would like to retrieve in entirety for a given customer, using ISession.Get(id). I have the following

5条回答
  •  别那么骄傲
    2020-12-12 23:27

    If you need to keep your one-to-manys as bags, then you can issue 2 queries, each with only 1 level of hierarchy. eg something like this:

    var temp = session.CreateCriteria( typeof( Order ) )
        .SetFetchMode( "Lines", NHibernate.FetchMode.Eager )
        .Add( Expression.Eq( "Customer.ID", id ) )
        .List();
    
    var customer = session.CreateCriteria( typeof( Customer ) )
        .SetFetchMode( "Orders", NHibernate.FetchMode.Eager )
        .Add( Expression.Eq( "ID", id ) )
        .UniqueResult();
    

    Lines get loaded into the NH cache in the first query, so they won't need lazy loading when later accessing eg customer.Orders[0].Lines[0].

提交回复
热议问题