LINQ与SelectMany,Group和Take

时间:2019-01-03 12:46:37

标签: c# sql linq nhibernate linq-to-nhibernate

我被查询困住了。也许有人可以帮我吗?我有一个带有消息的表,另一个带有接收器(1:N)的表。最初我有以下查询:

var messages = 
  (from message in query
  from receiver in message.ReceiverList
  where ... // some message and receiver checks
  select new { Message = message, Receiver = receiver }
  ).GroupBy(m => m.Message);

效果很好,并返回了消息,每个消息都有一个收件人列表。在SQL查询中没有GROUP BY

现在,我只需要接收前5条消息,无论我如何编写查询,它都会失败。我尝试像这样向其中添加OrderByTake

var messages = 
  (from message in query
  from receiver in message.ReceiverList
  where ... // some message and receiver checks
  select new { Message = message, Receiver = receiver }
  ).GroupBy(m => m.Message).OrderBy(x => x.Key.Id).Take(5);

但随后由于“未实现方法或操作”而失败。

我还尝试在order by之前编写select,然后由于GroupBy而失败,因为它被翻译为

TOP 5 ... FROM ... WHERE ... 
GROUP BY message.ID 
ORDER BY message.ID ASC

我什至尝试过两次过滤掉接收者的外观很糟糕的选择:

var messages = query
                .Where(<message conditions> &&
                    message.ReceiverList.Any(<receiver conditions>) 
                .Select(message => new
                {
                    Message = message,
                    Receivers = message.ReceiverList
                        .Where(<receiver conditions>)
                })
                .Where(message => message.Receivers.Count() > 0)
                .OrderBy(message => message.Message.Id)
                .Take(5)
                .ToList();

但是这只返回表的前五行,而我需要所有接收者的前5条消息。

只接收5条消息的正确方法是什么?

0 个答案:

没有答案