nhibernate queryover join with subquery to get aggregate column

杀马特。学长 韩版系。学妹 提交于 2019-11-29 04:02:52
noir

After reading hundreds of similar questions in here, I have found the answer: a correlated sub-query. Like this:

// aliases
Branch branch = null; AssignmentBranch assignment = null;

var subquery = QueryOver.Of<AssignmentBranch>(() => assignment)
    .Where(() => assignment.Branch.ID == branch.ID)
    .ToRowCountQuery();

var query = session.QueryOver<Branch>(() => branch)
     .Where(() => branch.Project.ID == projectID)
     .SelectList
     (
         list => list
         .Select(b => b.ID)
         .Select(b => b.Name)
         .SelectSubQuery(subquery)
     )
     .TransformUsing(Transformers.AliasToBean<BranchAssignments>())
     .List<BranchAssignments>();

The similar question I got my answer from is this one.

its not that easy with QueryOver, because it is currently not possible to have statements in the FROM clause. One thing that comes to my mind (not the most efficient way i think)

var branches = session.QueryOver<Branch>().Future();

var assignmentMap = session.QueryOver<BranchAssignment>()
    .Select(
        Projections.Group<BranchAssignment>(ab => ab.Branch.Id).As("UserId"),
        Projections.RowCount())
    .Future<object[]>()
    .ToDictionary(o => (int)o[0], o => (int)o[1]);

return branches.Select(b => new { Branch = branch, AssignmentCount = assignmentMap[branch.Id] });

with LINQ it would be

var branchesWithAssignementCount = session.Query<Branch>()
    .Select(b => new { Branch = b, AssignmentCount = b.Branch.Count })
    .ToList();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!