使用NHibernate上的QueryOver限制孩子数量

时间:2011-06-13 16:21:15

标签: .net nhibernate queryover

如何使用QueryOver并且不使用公式字段来执行以下操作。

我有以下父/子关系

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;}
}

我有以下查询返回15个俱乐部并将结果转换为DTO,我需要在此查询中添加属于每个俱乐部并且未取消的会员资格的RowCount。

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 个答案:

答案 0 :(得分:9)

经过一些研究,这是生成的查询:

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