Eagerly fetch multiple collection properties (using QueryOver/Linq)?

后端 未结 2 1316
误落风尘
误落风尘 2020-12-13 09:16

I found 2 similar questions:

  • Multiple Fetches in linq to nhibernate
  • Is this the right way of using ThenFetch() to load multiple collections?
2条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-13 09:59

    I prefer to use the linq provider if at all possible especially if you are using newer versions of nhibernate (>= 4.0). As long as you have your collections mapped as ISets (requires .net framework >= 4) which we converted to such that we could do eager loading and avoid cartesian products. I feel like this isn't something that is heavily advertised but I prefer this method where applicable over anything else :

    public class Person
    {
        public virtual int Id { get; private set; }
        public virtual ISet Books { get; set; }
        public virtual ISet
    Articles { get; set; } public virtual ISet
    Addresses { get; set; } } public Person() { this.Books = new HashSet(); this.Articles = new HashSet
    (); this.Addresses = new HashSet
    (); }

    If you have your collections defined like the above then you can do the following and still avoid cartesian product issues:

    var persons = session.Query()
                         .FetchMany(x => x.Books)
                         .FetchMany(x => x.Articles)
                         .FetchMany(x => x.Addresses)
                         .ToList();
    

提交回复
热议问题