【发布时间】:2021-06-13 03:41:02
【问题描述】:
我正在使用带有 SQLite 的 EF Core 来存储一堆天气报告:
public class WeatherReport
{
[Key]
public string ReportId { get; set; }
public float Temperature { get; set; }
public DateTime ReportDate { get; set; }
}
在我的 API 控制器中,我像这样返回它们:
IEnumerable<Models.TemperatureGetDTO> weatherReports = await _db.WeatherReports
.Select(g => new Models.TemperatureGetDTO {
ReportDate = g.ReportDate,
Temperature = g.Temperature
})
.ToListAsync();
return Ok(weatherReports);
返回以下 JSON 化数据:
{"reportDate":"2021-03-13T23:56:14.0135403","temperature":22},
{"reportDate":"2021-03-13T23:57:14.1441771","temperature":22},
{"reportDate":"2021-03-13T23:58:14.2924322","temperature":22},
{"reportDate":"2021-03-13T23:59:14.4499289","temperature":21.9},
{"reportDate":"2021-03-14T00:00:14.651818","temperature":22},
{"reportDate":"2021-03-14T00:01:14.7563863","temperature":22},
{"reportDate":"2021-03-14T00:02:14.886777","temperature":22},
{"reportDate":"2021-03-14T00:03:15.0797178","temperature":22},
{"reportDate":"2021-03-14T00:04:15.2898459","temperature":22}
...
但是,现在,我想按小时对温度进行分组,并获得每小时的第一份天气报告(分组)。我试过这样写查询:
var weatherReports = await _db.WeatherReports
.GroupBy(w => w.ReportDate.Hour)
.Select(g => new {
Hour = g.Key,
Temperature = g.OrderBy(w => w.ReportDate).First().Temperature
})
.ToListAsync();
然而,这会产生以下错误:
LINQ 表达式 'GroupByShaperExpression: KeySelector: CAST(strftime('%H', w.ReportDate)) AS INTEGER), ElementSelector:EntityShaperExpression:EntityType:WeatherReport ValueBufferExpression:ProjectionBindingExpression: EmptyProjectionMember IsNullable: False
.Select(s => s.Temperature) .First()' 无法翻译。任何一个 以可以翻译的形式重写查询,或切换到 通过插入对“AsEnumerable”的调用来显式评估客户端, “AsAsyncEnumerable”、“ToList”或“ToListAsync”。看 https://go.microsoft.com/fwlink/?linkid=2101038 了解更多信息。
我在这里做错了什么?要从组中获取第一项,我不应该使用 First() 吗?
【问题讨论】:
标签: c# linq group-by entity-framework-core