与DateTimeOffset.Date属性进行比较时,我们发现客户端与服务器端评估的结果不一致。
给出实体:
public partial class PreHire
{
public int PreHireId { get; set; }
public DateTimeOffset StartDate { get; set; }
}
以及以下逻辑:
DateTime startDate = DateTime.Now;
//Pulls preHire with a start date of '2019-11-25 14:42:54.0833333 +00:00'
PreHire clientComparePreHire = context.PreHire.Where(x => x.PreHireId == 22407).FirstOrDefault();
if(clientComparePreHire.StartDate.Date >= startDate.Date)
{
Console.WriteLine("This works.");
}
List<PreHire> serverComparePreHires = context.PreHire.Where(q => q.StartDate.Date >= startDate.Date).ToList();
if(serverComparePreHires.Count == 0)
{
Console.WriteLine("This doesn't. This shouldn't be empty.");
}
我们得到以下日志:
info: Microsoft.EntityFrameworkCore.Database.Command[20100]
Executing DbCommand [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT TOP(1) [p].[PreHireID], [p].[StartDate]
FROM [TBL].[PreHire] AS [p]
WHERE [p].[PreHireID] = 22407
This works.
info: Microsoft.EntityFrameworkCore.Database.Command[20100]
Executing DbCommand [Parameters=[@__startDate_Date_0='2019-11-25T00:00:00' (DbType = DateTimeOffset)], CommandType='Text', CommandTimeout='30']
SELECT [p].[PreHireID], [p].[StartDate]
FROM [TBL].[PreHire] AS [p]
WHERE CONVERT(date, [p].[StartDate]) >= @__startDate_Date_0
This doesn't. This shouldn't be empty.
这表明serverComparePreHires为空,但是如果我手动运行上述查询,则会得到预期的结果:
SELECT [p].[PreHireID], [p].[StartDate]
FROM [TBL].[PreHire] AS [p]
WHERE CONVERT(date, [p].[StartDate]) >= '2019-11-25T00:00:00'
PreHireID StartDate
22407 2019-11-25 14:42:54.0833333 +00:00
总而言之,当处理此特定linq查询服务器端时,EF Core会生成一个有效的SQL查询,但无法返回匹配的PreHire
条目。我在这里想念什么吗?根据我的研究,EF Core应该能够处理任何DateTime.Date
查询。
其他详细信息
EF核心版本:3.0.0(与3.0.1相同的结果)
数据库提供者:Microsoft.EntityFrameworkCore.SqlServer
目标框架:.NET Core 3.0(从2.1迁移)
操作系统:Windows 10
IDE:Visual Studio 2019 16.3.7