Samuel Goldenbaum
Samuel Goldenbaum

Reputation: 18939

NHibernate Projections - How to project a value from within associations

I am trying to project a single value from an entity's association with no luck. Only want the city name from the TrainerAddress in the query below. Trainer address is mapped as a component of Trainer.

session.QueryOver<Trainer>()
   .JoinAlias(x=>x.TrainerAddress.City, ()=> cityAlias, JoinType.LeftOuterJoin)
   .OrderBy(x => x.Name).Asc
   .SelectList(list => list
        .Select(x => x.Id).WithAlias(() => dto.Id)
        .Select(x => x.Name).WithAlias(() => dto.Name)
        .Select(x => x.TrainerAddress.City.Name).WithAlias(() => dto.City))//issue projecting here
  .TransformUsing(Transformers.AliasToBean<TrainerDTO>())
  .List<TrainerDTO>();

Is this possible?

Upvotes: 1

Views: 964

Answers (1)

Martin Ernst
Martin Ernst

Reputation: 5679

You're specifying an alias for TrainerAddress.City but you don't use that alias anywhere? I'm not 100% sure if NHibernate supports components well in QueryOver, I know there were some issues with it using Criteria, but maybe this will work:

session.QueryOver<Trainer>()
   .JoinAlias(x=> x.TrainerAddress.City, ()=> cityAlias, JoinType.LeftOuterJoin)
   .OrderBy(x => x.Name).Asc
   .SelectList(list => list
        .Select(x => x.Id).WithAlias(() => dto.Id)
        .Select(x => x.Name).WithAlias(() => dto.Name)
        .Select(x => cityAlias.Name).WithAlias(() => dto.City))
  .TransformUsing(Transformers.AliasToBean<TrainerDTO>())
  .List<TrainerDTO>();

Upvotes: 2

Related Questions