Carl Raymond
Carl Raymond

Reputation: 4479

NHibernate query with criteria on child collection member returns only partial child collection

I have a parent-child relationship between Teacher and StudentReport. Each StudentReport has a timestamp field recording when the teacher finished the report. I have a query to find all teachers who have completed one or more of their reports as of a certain number of minutes ago:

    public IList<Teacher> FindRecentlyActiveTeachers(int intervalMinutes)
    {
        if (intervalMinutes <= 0)
            throw new ArgumentException("Interval must be a positive number of minutes");

        DateTime activityCutoff = DateTime.Now.AddMinutes(-1 * intervalMinutes);

        return Session.QueryOver<Teacher>()
            .Left.JoinQueryOver<StudentReport>(t => t.StudentReports)
            .Where(r => r.FirstSaveTimestamp >= activityCutoff)
            .TransformUsing(Transformers.DistinctRootEntity)
            .List<Teacher>();
    }

This returns the correct list of teachers, but the child collection for each teacher only contains the reports that match the selection criterion. I would like the report collection of each matching teacher to contain all of the reports, not just the few reports that meet the criteria.

Is there some way I can either load the full child collection eagerly, or omit loading it in this query and rely on lazy loading it?

Update

This is the solution:

        return Session.QueryOver<Teacher>()
            .Fetch(t => t.StudentReports).Eager
            .JoinQueryOver<StudentReport>(t => t.StudentReports)
            .Where(r => r.FirstSaveTimestamp >= activityCutoff)
            .TransformUsing(Transformers.DistinctRootEntity)
            .List<Teacher>();

Upvotes: 6

Views: 2619

Answers (1)

mathieu
mathieu

Reputation: 31202

Use Fetch

return Session.QueryOver<Teacher>()
    .Fetch(t => t.StudentReports)
    .Where(r => r.FirstSaveTimestamp >= activityCutoff)
    .TransformUsing(Transformers.DistinctRootEntity)
    .List<Teacher>();

Upvotes: 2

Related Questions