2014-04-03 43 views
2

我與很多消息進行了會話,我想按照ConversationMessages表中最後一條消息的創建日期的順序排列會話。nHibernate - 選擇後的子選擇

我該如何在nHibernate的queryOver中寫這個。我應該使用子查詢嗎?

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

回答

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)