Fluent NHibernate N+1 issue with complex objects

后端 未结 2 1280

I\'m having a problem with NHibernate querying the database way too many times. I just realized it likely relates to the n+1 problem but I can\'t figure out how to change my map

相关标签:
2条回答
  • 2021-02-20 08:58

    You can specify fetch paths in the query. For example, this fetch path can tell the query to eagerly join product and main objects, as well as an imaginary association on the collection of clients:

    public IQueryable<Report> ReadAll(DateTime since)
    {
        return m_session.QueryOver<Report>()
           .JoinQueryOver(r => r.Mail)
           .Where(m => m.Received >= since)
           .Fetch(x => x.Product).Eager
           .Fetch(x => x.Mail).Eager
           .Fetch(x => x.ReadBy.First().SomeProp).Eager
           .List()
           .AsQueryable();
    }
    

    If you want that always to happen, try using .Fetch.Join() instead of .Not.LazyLoad() for the assocations. But I would not recommend that because it can cause simple queries to become huge. Batching or subqueries can help too.

    0 讨论(0)
  • 2021-02-20 09:10

    The way to go is to use batch fetching. Read more about it here:

    How to Eager Load Associations without duplication in NHibernate?

    On every entity mapping apply BatchSize (for many-to-one relation - avoiding 1 + N)

    public ReportMap()
    {
       Table(...)
       BatchSize(25);
       ...
    

    And on every collection (solves issue with one-to-many 1 + N)

    HasMany(x => x.Reports)
          .KeyColumn("StackTraceId")
          .BatchSize(25)
          ...
    
    0 讨论(0)
提交回复
热议问题