nHibernate - 使用order by选择select

时间:2014-04-03 12:50:17

标签: c# sql nhibernate

我与许多消息进行了对话,我想按照ConversationMessages表中最后一条消息的创建日期的顺序排序对话。

我如何在nHibernate的queryOver中编写它。我应该使用subQuery吗?

select distinct c.ConversationId,
  (select max(CreatedDate) 
    from tConversationMessage mess where mess.ConversationId = c.ConversationId
  ) as LastMessage 
from tConversation c order by LastMessage

1 个答案:

答案 0 :(得分:3)

通过猜测你的C#命名,NHibernate映射...这将是这样的:

Conversation conversation = null;
ConversationMessage message = null;

// the subselect of a max
var subQuery = QueryOver.Of<ConversationMessage>(() => message)
    .Where(() => message.Conversation.ID == conversation.ID)
    .Select(Projections.Max("CreatedDate"));

// the alias of the Conversation to be injected into subquery
var query = session.QueryOver<Conversation>(() => conversation);

// a select and group by (distinct) clause
query.SelectList(l => l
    .SelectGroup(s => conversation.ID)
    .Select(Projections.SubQuery(subQuery))
    );

// Order by the max Created date (asc)
var list = query
    .OrderBy(Projections.SubQuery(subQuery))
        .Asc
    .List<object[]>()
    ;

对于每个对话ID,我们将获得ConversationMessage的最大值(CreateDate)