首页 > 解决方案 > EF Core 3.1 中的时间跨度问题

问题描述

我在使用 EF Core 3.1 查询 PostgreSQL 数据库时遇到问题。

查询很简单

var gamesQuery = this.dbContext.Games.Where(game => game.StartTime > DateTime.Now).AsQueryable();

// 'request.TimeFrom' is of type System.TimeSpan and the value is populated
gamesQuery = gamesQuery.Where(game => game.StartTime.TimeOfDay >= request.TimeFrom);

// .ToList()-int here causes the exception.
var games = gamesQuery.ToList();

异常消息明确指出无法翻译查询:

“无法翻译 LINQ 表达式 'DbSet\r\n .Where(g => g.StartTime > DateTime.Now)\r\n .Where(g => g.StartTime.TimeOfDay >= __request_TimeFrom_0)'。要么以可翻译的形式重写查询,或通过插入对 AsEnumerable()、AsAsyncEnumerable()、ToList() 或 ToListAsync() 的调用显式切换到客户端评估。请参阅https://go.microsoft.com /fwlink/?linkid=2101038了解更多信息。”

问题是相同的查询在 .NET Core 2.2 中运行良好。我还没有发现任何关于这个问题的信息。

有人知道这是什么原因还是我错过了什么?

标签: c#postgresqlentity-framework-coretimespan

解决方案


目前 PostgreSQL EF Core 3.x 查询提供程序不支持翻译DateTime.TimeOfDay- 请参阅源代码TODO中的注释。

它很可能通过静默使用客户端评估在 2.x 中“起作用”。但是隐式客户端评估已在 3.0 中删除,并且无法重新打开它。

您可以尝试以下等效构造:

.Where(game => (game.StartTime - game.StartTime.Date) >= request.TimeFrom)

至少它不会产生上述异常。

如果它不起作用,请采纳他们的建议并通过AsEnumerable()在不可翻译表达式之前的适当位置插入来明确切换到客户端评估。


推荐阅读