Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

nhibernate

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>();
like image 429
Carl Raymond Avatar asked May 31 '11 20:05

Carl Raymond


1 Answers

Use Fetch

return Session.QueryOver<Teacher>()
    .Fetch(t => t.StudentReports)
    .Where(r => r.FirstSaveTimestamp >= activityCutoff)
    .TransformUsing(Transformers.DistinctRootEntity)
    .List<Teacher>();
like image 134
mathieu Avatar answered Oct 01 '22 00:10

mathieu