Nhibernate查询选择按行分组的计数

时间:2012-11-19 11:48:42

标签: nhibernate select count group-by subquery

我需要使用NHibernate获取此查询:

Select RequestStatus.[Status], Count(ApprovalRequest.Id)
    From ApprovalRequest Inner Join RequestStatus On ApprovalRequest.CurrentStatusId = RequestStatus.Id
    Where RequestStatus.[Status] In ('Approved', 'Queried') And ApprovalRequest.Deleted != 1
Group By RequestStatus.[Status]

这是我的课程:

 public class ApprovalRequest
    {
        public ApprovalRequest()
        {
            Id = Guid.NewGuid();
            Statuses = new List<RequestStatus>();
        }

        /// <summary>
        /// Identity No.
        /// </summary>
        public Guid Id { get; set; }


        /// <summary>
        /// Represents the current status of the request e.g. Approved.
        /// </summary>
        public RequestStatus CurrentStatus { get; set; }

        /// <summary>
        /// The statuses that the request experiences.
        /// </summary>
        public IList<RequestStatus> Statuses { get; set; }

    }
}


public class RequestStatus
{
    public RequestStatus()
    {
        Id = Guid.NewGuid();
    }

    public Guid Id { get; set; }

    public StatusEnum Status { get; set; }
}

我尝试了这个查询:

   var lst = uow.Session.QueryOver<ApprovalRequest>()
                .JoinQueryOver<RequestStatus>(req => req.CurrentStatus)
                .SelectList(list =>
                    list
                    .SelectCount(p => p.Id)
                    .SelectGroup(p => p.CurrentStatus.Status)
                    ).List();

但是我收到了一个错误:

无法解析属性:CurrentStatus.Status:ApprovalRequest(NHibernate)

1 个答案:

答案 0 :(得分:5)

您需要将已连接的表绑定到别名。

ApprovalRequest approvalRequestAlias = null;
RequestStatus requestStatusAlias = null;

var lst = uow.Session.QueryOver<ApprovalRequest>(() => approvalRequestAlias)
    .JoinAlias(() => approvalRequestAlias.CurrentStatus, () => requestStatusAlias)
    .SelectList(list => list
        .SelectCount(p => p.Id)
        .SelectGroup(p => requestStatusAlias.Status)
    ).List();