EF Core 3.1中的TimeSpan问题

时间:2019-12-29 16:05:04

标签: c# postgresql entity-framework-core timespan

我在使用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。其中(g => g.StartTime> DateTime.Now)\ r \ n。其中(g => g.StartTime.TimeOfDay> = __request_TimeFrom_0)'不能以可翻译的形式重写查询,或者通过插入对AsEnumerable(),AsAsyncEnumerable(),ToList()或ToListAsync()的调用来显式切换到客户端评估。请参见{{3 }},以获取更多信息。“

问题是同一查询在.NET Core 2.2中可以正常工作。 我尚未发现有关该问题的任何信息。

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

2 个答案:

答案 0 :(得分:2)

当前PostgreSQL EF Core 3.x查询提供程序不支持DateTime.TimeOfDay的翻译-请参见source code中的TODO注释。

很可能它通过静默使用客户端评估在2.x中“工作”。但是隐式的客户评估has been removed in 3.0并没有办法重新启用。

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

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

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

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

答案 1 :(得分:0)

我还没有尝试过,但是一种解决方案可能是将TimeOfDay保存到DateTime属性旁边的数据库中。然后,将其与您的TimeSpan变量进行比较。