我有一个数据库-Session,链接到另一个数据库-SyncSession,并以他们的登录名加入。我想使用Linq作为字典值来检索每个用户(每个用户1个)的最新记录的某些属性。我目前可以使用OrderByDescending进行此操作,但是性能太慢(它是一个大型数据库)。我需要使用Max,但是在实现上受阻。
这是Linq查询:
var data = await _loggingContext.SessionDatabases
.Where(x => x.DatabaseName == database)
.Include(x => x.Session)
.GroupBy(x => x.Session.LogName)
.Select(x => x.OrderByDescending(t => t.Start)
.FirstOrDefault())
.ToDictionaryAsync(x => x.Session.LogName, x => (x.Session.ClientVersion.ToString(), x.SyncResult.ToString(), x.Start));
这是一个有效的SQL查询,但是我不确定如何将其转换为Linq:
WITH LastSync ([User], [LastStart]) AS (
SELECT
s.[Logname],
MAX(s.[Start])
FROM dbo.Session s
JOIN dbo.SessionDatabase d ON d.[SessionId] = s.[Id]
WHERE d.[DatabaseName] = 'db_name'
AND s.[Logname] IN ('smaple', 'sample')
GROUP BY s.[Logname]
)
SELECT
l.[User],
l.[LastStart],
s.[ClientVersion],
s.[State]
FROM LastSync l
LEFT JOIN dbo.Session s ON s.[Start] = l.[LastStart]
AND s.[Logname] = l.[User]
应该能够使用GroupBy并选择“新建”来实现这一点>
类似:
.GroupBy(x => x.Session.LogName) .Select(x => new { LogName = x.Key, Start = x.Max(s => s.Start) } )
另请参阅:How do I get the MAX row with a GROUP BY in LINQ query?