NHibernate查询子查询组通过连接回主实体

时间:2013-04-12 15:35:09

标签: sql nhibernate fluent-nhibernate queryover

您好我正在尝试实现以下SQL

SELECT this_.*
 FROM WorkItems this_ 
 WHERE this_.UserId = (

 SELECT this_1_.y0_ as y0_
 FROM
 (
    SELECT top 1 this_0_.UserId as y0_, count(this_0_.UserId) as y1_ 
    FROM WorkItems this_0_ 
    WHERE this_0_.StateId = 1 and this_0_.Type like 'Data' 
    GROUP BY this_0_.UserId 
    ORDER BY y1_ desc
  ) this_1_

); 
到目前为止,我已经制造了相当接近的产品。我错过了我只选择userId的部分。 继到目前为止的查询

var subquery = QueryOver.Of<WorkItem>().Where(w => w.State == state)
                                .AndRestrictionOn(w => w.Type).IsLike(type, MatchMode.Exact)
                                .SelectList(list =>
                                            list.SelectGroup(w => w.UserId)
                                                .WithAlias(() => resultAlias.userId)
                                                .SelectCount(w => w.UserId)
                                                .WithAlias(() => resultAlias.count))
                                .OrderByAlias(() => resultAlias.count)
                                .Desc().Take(1);

        var query =
            CurrentSession.QueryOver<WorkItem>()
                          .WithSubquery
                          .WhereProperty(p => p.UserId)
                          .Eq(subquery);

1 个答案:

答案 0 :(得分:1)

试试这个: -

var subquery = QueryOver.Of<WorkItem>().Where(w => w.State == state)
                .AndRestrictionOn(w => w.Type).IsLike(type, MatchMode.Exact)
                .SelectList(list => list.SelectGroup(w => w.UserId))
                    .OrderBy(Projections.Count<WorkItem>(x => x.UserId))
                .Desc().Take(1);

var query = CurrentSession.QueryOver<WorkItem>()
              .WithSubquery
              .WhereProperty(p => p.UserId)
              .Eq(subquery);