How to craft a linq query with a multi-column "Group By"

问题描述 投票:0回答:1

如何将以下内容转换为 LINQ 表达式?我有一个用于数据库模型的活动 EntityFramework 上下文,我只是迷失了看 LINQ“组”文档。

SELECT TOP 1
    ContributorId,
    MAX(Version) 'Version',
    CASE
        WHEN CONVERT(varchar, max(CreateTS), 23) >= CONVERT(varchar, max(UpdateTS), 23) 
            THEN CONVERT(varchar, max(CreateTS), 23)
        ELSE CONVERT(varchar, max(UpdateTS), 23) 
    END 'Date'
FROM [MyDB].[dbo].[Contributions]
WHERE ContributorId = '08db4b393b1f'
GROUP BY 
    ContributorId,
    Version,
    CONVERT(varchar, CreateTS, 23),
    CONVERT(varchar, UpdateTS, 23)
ORDER BY 
    Version DESC
c# entity-framework linq .net-6.0
1个回答
0
投票
var result = dbContext.Contributions
    .Where(c => c.ContributorId == "08db4b393b1f")
    .GroupBy(c => new { c.ContributorId, c.Version, Date = (c.CreateTS >= c.UpdateTS ? c.CreateTS.Date : c.UpdateTS.Date) })
    .Select(g => new {
        g.Key.ContributorId,
        Version = g.Max(c => c.Version),
        Date = g.Max(c => (c.CreateTS >= c.UpdateTS ? c.CreateTS.Date : c.UpdateTS.Date))
    })
    .OrderByDescending(r => r.Version)
    .Take(1)
    .SingleOrDefault();

我觉得应该是这样吧

© www.soinside.com 2019 - 2024. All rights reserved.