7

How can I do the following using QueryOver and no Formula Fields.

I have the following parent child relationship

public class Club
{
    public string Name { get; set; }

    public IList<Membership> Memberships { get; set; }
}

public class Membership
{
    public boolean Cancelled { get; set; }

    public Club Club { get; set; }
}

I have the following query that returns 15 Clubs and transforms the results to a DTO, I need to add to this query a RowCount of Memberships that belong to each club and that are not Cancelled.

IEnumerable<ClubIndexViewModelLineSummary> results = _querySession.QueryOver<Club>()
    .OrderBy(c => c.IsActive).Desc
    .OrderBy(c => c.Name).Asc
    .SelectList(list => list
                        .Select(c => c.Id).WithAlias(() => sum.Id)
                        .Select(c => c.Name).WithAlias(() => sum.Name)
                        .Select(c => c.IsActive).WithAlias(() => sum.IsActive)
                        .Select(c => c.NumberOfWeeks).WithAlias(() => sum.NumberOfWeeks))
    .TransformUsing(Transformers.AliasToBean<ClubIndexViewModelLineSummary>())
    .Skip(start)
    .Take(15)
    .Future<ClubIndexViewModelLineSummary>();
ahsteele
  • 26,243
  • 28
  • 134
  • 248
aattia
  • 613
  • 4
  • 17

1 Answers1

10

After some more research, this is the resulting query that works:

Club clubAlias = null;

IEnumerable<ClubIndexViewModelLineSummary> results = 
 _querySession.QueryOver<Club>(() => clubAlias)
    .OrderBy(c => c.IsActive).Desc
    .OrderBy(c => c.Name).Asc
    .SelectList(list => list
                            .Select(c => c.Id).WithAlias(() => sum.Id)
                            .Select(c => c.Name).WithAlias(() => sum.Name)
                            .Select(c => c.IsActive).WithAlias(() => sum.IsActive)
                            .Select(c => c.NumberOfWeeks).WithAlias(() => sum.NumberOfWeeks)
                            .SelectSubQuery
                            (
                                QueryOver.Of<ClubMembership>()
                                    .Where(c => c.Canceled == false)
                                    .And(c=> c.Club.Id == clubAlias.Id)
                                    .ToRowCountQuery()
                            ).WithAlias(()=> sum.ActiveMembers))
    .TransformUsing(Transformers.AliasToBean<ClubIndexViewModelLineSummary>())
    .Skip(start)
    .Take(15)
    .Future<ClubIndexViewModelLineSummary>();
ahsteele
  • 26,243
  • 28
  • 134
  • 248
aattia
  • 613
  • 4
  • 17