nhibernatenhlambdaextensions

NHibernate Lambda Extensions - CreateCriteria Issue


I want to convert a NHibernate CreateCriteria over to a NHLambdaExtensions criteria, but I'm getting errors that I don't know how to fix.

The NHibernate criteria looks like this:

var departments = DepartmentService
    .CreateCriteria()
    .CreateAlias( "Goals", "goal" )
    .Add( Expression.Eq( "goal.Company.Id", companyId ) )
    .Add( Expression.Eq( "goal.Program.Id", programId ) )
    .List<Business.Department>();

The NHLambdaExtensions criteria that I'm trying to create looks like this:

Business.Goal goalAlias = null;
var departments = DepartmentService
    .CreateCriteria()
    .CreateAlias<Business.Goal>( g => g.Department, () => goalAlias )
    .Add<Business.Goal>( g => g.Company.Id == companyId )
    .Add<Business.Goal>( g => g.Program.Id == programId )
    .List<Business.Department>();

The error I'm getting is "Could not resolve property Department of: Business.Department". The error obviously has to do with "g => g.Department", and there is nothing in the original NHibernate query that has something similar, but there are no overloads that don't take the expression.


Solution

  • Business.Goal goalAlias = null;
    var departments = DepartmentService
        .CreateCriteria(typeof(Business.Department)) // need to specify the first criteria as Business.Department
            .CreateCriteria<Business.Department>(d => d.Goals, () => goalAlias)
                .Add<Business.Goal>( g => g.Company.Id == companyId )
                .Add<Business.Goal>( g => g.Program.Id == programId )
        .List<Business.Department>();
    

    Look for "Create Criteria Association With Alias" in NHibernate Lambda Extensions (V1.0.0.0) - Documentation

    EDIT:

    You can actually write this more efficiently as:

    // no alias necessary
    var departments = DepartmentService
        .CreateCriteria<Business.Department>()
            .CreateCriteria<Business.Department>(d => d.Goals)
                .Add<Business.Goal>( g => g.Company.Id == companyId )
                .Add<Business.Goal>( g => g.Program.Id == programId )
        .List<Business.Department>();