NHibernate Join Fetch(Kind)
Asked Answered
O

1

6

Given a Team -> Athlete relationship and querying all athletes. What am I misunderstanding about fetch="Join"? Should this mapping cause the Team to be loaded via a join? When iterating the athletes, it still lazy loads the Team.

public class AthleteMap : ClassMapping<Athlete>
{
        public AthleteMap()
        {
            ManyToOne(a => a.Team, o =>
                                       {
                                           o.Fetch(FetchKind.Join);
                                           o.Lazy(LazyRelation.NoLazy);
                                       }
                );    
        }    
}

Which produces this HBM:

<class name="Athlete" table="Athletes">
    <id name="Id" type="Int32" />
    <property name="FirstName" />
    <property name="LastName" />
    <many-to-one name="Team" fetch="join" lazy="false" />
    <property name="Created" />
</class>

iterating:

var session = factory.OpenSession();

 foreach (var athlete in session.Query<Athlete>())
     Console.WriteLine("{0} {1}", athlete.FirstName, athlete.Team.Name); 
Opus answered 22/11, 2011 at 19:13 Comment(3)
Do you get a exception? Wich?Hegumen
So when you iterate you see queries fetching a Team per athlete? I mean, the mapping is correct, apart from the eager fetch?Comedienne
No Exception. @GertArnold yes while iterating, it queries the Team on every iteration.Opus
H
14

The NHibernate Linq Query doesn't use the fetch strategy of the mapping. You have to Fetch() in your linq query like this.

var session = factory.OpenSession();

foreach (var athlete in session.Query<Athlete>().Fetch(x => x.Team))
   Console.WriteLine("{0} {1}", athlete.FirstName, athlete.Team.Name); 

The fetch strategy defined in the mapping document affects:

  • retrieval via Get() or Load()
  • retrieval that happens implicitly when an association is navigated
  • ICriteria queries
  • HQL queries if subselect fetching is used

source:performance-fetching

Hegumen answered 22/11, 2011 at 21:36 Comment(1)
Thanks... shame their Linq implementation is incomplete like this.Peltast

© 2022 - 2024 — McMap. All rights reserved.