Get children count with restrictions using QueryOv

2020-02-28 23:59发布

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>();

1条回答
We Are One
2楼-- · 2020-02-29 00:32

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>();
查看更多
登录 后发表回答