Search code examples
nhibernatequeryover

Session.QueryOver: What does error : variable 'rg' of type ReportingGroup referenced from scope , but it is not defined" mean?


This is the query:

 var reportingGroupYears = _session.QueryOver<ReportingGroup>()
                            .Where(x => x.Number == request.ReportingGroupNumber)
                            .Select(rg=> rg.Year.ToString())
                            .List<string>();

I don't understand what is wrong with it. Defining 'rg' as string is not allowed either, as it give message that it would give rg a different meaning than the one defined in parent scope.


Solution

  • In this case, the Select clause is an issue for NHibernate. It expects the property (during the expression tree parsing) to be converted into SELECT statement. But there is a method call: .ToString().

    One way how to solve it, could be explicit Projection like this (see doc QueryOver 16.6. Projections)

    var reportingGroupYears = session
        .QueryOver<ReportingGroup>()
        .Where(x => x.Number == request.ReportingGroupNumber)
        .Select(Projections.ProjectionList()
            .Add(Projections.Cast(NHibernateUtil.String, Projections.Property("Year"))
            ))
            .List<string>();