views:

907

answers:

2

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.

A: 

I haven't used NHLambdaExpressions (but it looks pretty cool and I'll definitely check it out soon), so I'm just guessing here. Could you do something like this:

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

I think this will root a new criteria at Goals and assign an alias via goalAlias.

Stuart Childs
That didn't work either.
Josh Close
+3  A: 
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>();
ddc0660