如何使用多列“Group By”创建linq查询

m4pnthwp  于 2023-05-04  发布在  其他
关注(0)|答案(1)|浏览(135)

如何将以下内容转换为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
wixjitnu

wixjitnu1#

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();

我想应该就是这里了。

相关问题