SQL:在Linq中从x左联接y中选择SELECT id,MAX(y.DateCreated)吗?

时间:2018-10-15 22:13:04

标签: c# entity-framework linq

我似乎无法将此SQL重写为EF Linq:

SELECT      Conversation.Id
FROM        Conversation LEFT JOIN Message
                ON  Conversation.Id = Message.ConversationId
GROUP BY    Conversation.Id
ORDER BY    MAX(Message.DateCreated) DESC

我认为类似的方法会起作用:

 _dbContext.Conversation
           .OrderByDescending(c => c.Messages.DefaultIfEmpty().Max(m => m.DateCreated))
           .Select(cm => cm.Id);

但这给了我错误System.InvalidOperationException : Sequence contains no elements.

也是这样:

_dbContext.Conversation
          .Select(c => new {c.Id, MaxDate = c.Messages.DefaultIfEmpty().Max(m => m.DateCreated)})
          .OrderByDescending(c => c.MaxDate)
          .Select(cm => cm.Id);

但这给了我System.ArgumentException : At least one object must implement IComparable.

正确的方法是什么?

3 个答案:

答案 0 :(得分:1)

您能尝试一下吗?

from r in Conversation
              join ru in Message
              on r.Id equals ru.ConversationId into ps
              from ru in ps.DefaultIfEmpty()
              group ru by new { ru.ConversationId, ru.DateCreated } into rug
              select new {
                  id = ru.ConversationId,
                  datecreated = rug.Max(ru => ru.datecreated)
              }).OrderByDescending(x => x.datecreated);

这可能无法编译,因为我没有用于测试的代码(像小提琴一样)

答案 1 :(得分:1)

不过,您很接近,只需放下DefaultIfEmpty

_dbContext.Conversation.Select(con => new 
    {
        con.Id,
        MaxDateCreated = (DateTime?) con.Messages.Max(msg => msg.DateCreated)
    })
.OrderByDescending(con => con.MaxDateCreated)
.ToArray()

这是要生成的东西

SELECT 
[Project2].[C1] AS [C1], 
[Project2].[Id] AS [Id], 
[Project2].[C2] AS [C2]
FROM ( SELECT 
    [Project1].[Id] AS [Id], 
    1 AS [C1], 
     CAST( [Project1].[C1] AS datetime2) AS [C2]
    FROM ( SELECT 
        [Extent1].[Id] AS [Id], 
        (SELECT 
            MAX([Extent2].[DateCreated]) AS [A1]
            FROM [dbo].[Message] AS [Extent2]
            WHERE [Extent1].[Id] = [Extent2].[ConversationId]) AS [C1]
        FROM [dbo].[Conversation] AS [Extent1]
    )  AS [Project1]
)  AS [Project2]
ORDER BY [Project2].[C2] DESC

答案 2 :(得分:1)

我相信这会生成您要查找的SQL(加上或减去嵌套子查询):

No implicit conversion of Array into String

但是,在LINQ中,您可以使用组联接而不是常规联接。这也应该做您想要的,但是在SQL中使用子选择,因此我不确定哪个在服务器上更有效。普遍的想法似乎是加入更好,但是像现代足够的优化程序那样,逐个加入可能会使它变得毫无意义。我发现的另一篇文章说,子查询(CIS)效率更高,所以可能更好。

var ans = from c in Conversation
          join m in Message on c.Id equals m.ConversationId into mj
          from m in mj.DefaultIfEmpty()
          group m by c.Id into mg
          orderby mg.Max(m => m.DateCreated) descending
          select mg.Key;