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.

ddc0660
  • 4,022
  • 2
  • 21
  • 30
Josh Close
  • 22,935
  • 13
  • 92
  • 140
  • Sorry for the billion retags. I was trying to get the right tag for lambda expressions that didn't get truncated. – ddc0660 Sep 14 '09 at 18:01

2 Answers2

3
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
  • 4,022
  • 2
  • 21
  • 30
0

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
  • 3,295
  • 1
  • 19
  • 11