获取每个组的最后N个元素

时间:2015-04-09 17:01:26

标签: c# nhibernate

我尝试做的是为表格中的每个分组抓取最后N个元素(对于我的示例3)。我的表是:

create table application_sessions
(
    application_session_id int identity(1,1) primary key,
    session_type_id int not null references session_types(session_type_id),
    start_ts datetime not null,
    end_ts datetime null,
    is_successful bit not null default 0
)

在这种情况下,我尝试为每个session_type_id获取表中的最后3个条目(按start_ts排序)。要在SQL中执行此操作,我将运行此命令:

;with ranking as
(
    select *, row_number() over (partition by session_type_id order by start_ts desc) as rn
    from application_sessions
)
select * from ranking
where rn <= 3

我有一些问题使用NHibernate以这种方式从数据库中获取这些记录。鉴于下面的实体(SessionType是一个枚举),最好的方法是什么?

public class ApplicationSession
{
    public virtual int Id { get; set; }
    public virtual SessionType SessionType { get; set; }
    public virtual DateTime StartTimestamp { get; set; }
    public virtual DateTime? EndTimestamp { get; set; }
    public virtual bool IsSuccessful { get; set; }
}

我的(失败)第一次尝试是这样的:

public IList<ApplicationSession> GetLastNGroupedSessions(int count)
  {
     return _session.Query<ApplicationSession>()
                       .GroupBy(x => x.SessionType)
                       .SelectMany(y =>
                               y.OrderByDescending(z => z.StartTimestamp)
                                .Take(count))
                       .ToList();
   }

这会产生异常: 无法识别查询源:ItemName = y,ItemType = System.Linq.IGrouping`2 [RIMS.ECMS.BusinessObjects.Local.Models.SessionType,RIMS.ECMS.BusinessObjects.Local.Models.ApplicationSession],Expression = from IGrouping `2 y in {value(NHibernate.Linq.NhQueryable`1 [RIMS.ECMS.BusinessObjects.Local.Models.ApplicationSession])=&gt; GroupBy([x] .SessionType,[x])}

1 个答案:

答案 0 :(得分:1)

因此,它可能不是“最佳”解决方案,但它是一个有效的解决方案。我的一位同事指出NHibernate允许您使用CreateSQLQuery直接执行SQL。这是我提出的解决方案,以防万一其他人遇到此类问题。

  public IList<ApplicationSession> GetLastNGroupedSessions(int count)
  {

     var sqlQuery = string.Format(@";with ranking as
     (
     select *, row_number() over (partition by session_type_id order by start_ts desc) as rn
     from application_sessions
     )
     select app.application_session_id,
        app.session_type_id,
        app.start_ts,
        app.end_ts,
        app.is_successful 
     from ranking as app
     where rn <= {0}", count);

     return _session.CreateSQLQuery(sqlQuery)
        .AddEntity("app", typeof(ApplicationSession))
        .List<ApplicationSession>();
  }