Search code examples
c#nhibernatefluent-nhibernatefluent-nhibernate-mapping

NHibernate fetch creates right query and then performs N+1


I have three entities, configured as

Contact
  HasOne(e => e.User).PropertyRef(e => e.Contact).Cascade.All();

User
  HasMany(e => e.Requests);
  References(e => e.Contact);

Request
  References(e => e.User);

And then I do query like this:

  CurrentSession.Query<Request>()
                .Fetch(x => x.User)
                .ThenFetch(x => x.Contact)
                .ToList();

And it looks like Fetch is working, because in first select I see all the tables joined (omitted other fields for brevity):

SELECT request0_.Id                 as Id128_0_,
   user1_.Id                       as Id131_1_,
   contact2_.Id                    as Id77_2_,
FROM   requests request0_
   left outer join users user1_
     on request0_.user_id = user1_.Id
   left outer join contacts contact2_
     on user1_.contact_id = contact2_.Id

And then follow N+1 selects for some reason, I can't understand and have no ideas how to troubleshoot the issue:

SELECT user0_.Id                as Id131_0_,
FROM   users user0_
WHERE  user0_.contact_id = 200 /* @p0 - contact_id */

Solution

  • Currently it is a bug in NHibernate.