【问题标题】:Retrieving the last record in each group with EF Core使用 EF Core 检索每个组中的最后一条记录
【发布时间】:2021-09-28 03:21:13
【问题描述】:

我正在尝试像这里一样检索每个组中的最后一条记录

https://stackoverflow.com/a/20770779/4789608

但在 Entity Framework Core 中。根据链接上的内容,我可以使用 SQL 来恢复正确的数据

select * 
from [Location] 
where [LocationModelId] in (select max([LocationModelId]) 
                            from [Location] 
                            group by [UserModelId])

select m1.* 
from [Location] m1 
left outer join [Location] m2 on (m1.[LocationModelId]< m2.[LocationModelId] 
                              and m1.[UserModelId] = m2.[UserModelId])

这是我根据该链接得到的最接近的结果

locationDetails = _context.Location
    .GroupBy(p => p.UserModelId)
    .Select(p => p.FirstOrDefault(w => w.UserModelId == p.Max(m => m.UserModelId)))
    .OrderBy(p => p.DateCreated)
    .ToList();

它返回此错误消息,所以它肯定不起作用。

LINQ 表达式 'GroupByShaperExpression:\r\nKeySelector: l.UserModelId, \r\nElementSelector:EntityShaperExpression: \r\n EntityType: LocationModel\r\n ValueBufferExpression: \r\n ProjectionBindingExpression: EmptyProjectionMember\r\n IsNullable : False\r\n\r\n .FirstOrDefault(w => w.UserModelId == GroupByShaperExpression:\r\n KeySelector: l.UserModelId, \r\n ElementSelector:EntityShaperExpression: \r\n EntityType: LocationModel\r \n ValueBufferExpression: \r\n ProjectionBindingExpression: EmptyProjectionMember\r\n IsNullable: False\r\n\r\n .Max(m => m.UserModelId))' 无法翻译。以可翻译的形式重写查询,或通过插入对“AsEnumerable”、“AsAsyncEnumerable”、“ToList”或“ToListAsync”的调用显式切换到客户端评估

【问题讨论】:

标签: c# entity-framework-core


【解决方案1】:

这个查询应该会得到你想要的输出。它不如只有带有窗口函数的 SQL 快,但应该可以接受。

var unique = _context.Location
    .Select(x => new {x.UserModelId})
    .Distinct();

var query =
    from u in unique
    from l in _context.Location
        .Where(x => x.UserModelId == u.UserModelId)
        .OrderByDescending(x.DateCreated)
        .Take(1)
    select l;

var locationDetails = query.ToList();

【讨论】:

    猜你喜欢
    • 2010-11-21
    相关资源
    最近更新 更多