组QueryOver Nhibernate后返回MAX值列表

时间:2014-09-01 13:46:22

标签: c# .net nhibernate subquery queryover

请帮忙,我可以通过nhibernate查询吗?

select max(Id) from transTable
group by PortfolioId.

我已经尝试过了。

 var subquery = QueryOver.Of(() => q)
                       .SelectList(list => list.SelectGroup(() => q.PortfolioId))
                           .Where(Restrictions.EqProperty(
                               Projections.Property(() => p.Id),
                               Projections.Max(() => q.Id)))
                           .And(Restrictions.EqProperty(
                               Projections.Property(() => p.Id),
                               Projections.Property(() => q.Id)));

然后

var filter = QueryOver.Of(() => p)
                        .WithSubquery.WhereExists(subquery)
                        .Select(Projections.Property(()=>p.Id));

但它不起作用。它返回表中的所有数据。我只想获得每个用户的最后一个sequenceID。

请帮忙。感谢

1 个答案:

答案 0 :(得分:1)

我会说,你几乎就在那里。这些是我们应该进行的调整,以获取过滤项目的列表。

// group by PortfolioId
// HAVING for outer 'p.ID'
var subquery = QueryOver.Of(() => q)
    .SelectList(list => list
        .SelectGroup(() => q.PortfolioId)
        .SelectMax(() => q.Id)
    )
    .Where(Restrictions.EqProperty( // HAVING
        Projections.Property(() => p.Id),
        Projections.Max(() => q.Id)))
     ;

// now select the list of p.Id, prefiltered by above subquery
var filter = QueryOver.Of(() => p)
    .WithSubquery.WhereExists(subquery)
    .Select(Projections.Property(() => p.Id));

// finally the result as a set of q entities
// ready for paging
var result = session.QueryOver(() => q)
    .WithSubquery
        .WhereProperty(() => q.Id)
        .In(filter)
    // .Skip(0) -- paging could be used
    // .Take(25)
    .List()
    ;

在此类似查询中检查已定义SQL的结构:Query on HasMany reference