我有一个名为BPIrequests
的表,其中有28M行,我正在使用Entity Framework查询日期范围。这是它产生超时的查询:
SELECT
[Extent1].[Id] AS [Id],
[Extent1].[Request ID] AS [Request ID],
[Extent1].[Date] AS [Date],
[Extent1].[Lumen URL] AS [Lumen URL],
[Extent1].[Copyright owner ID] AS [Copyright owner ID],
[Extent1].[Copyright owner name] AS [Copyright owner name],
[Extent1].[Reporting organization ID] AS [Reporting organization ID],
[Extent1].[Reporting organization name] AS [Reporting organization name],
[Extent1].[URLs removed] AS [URLs removed],
[Extent1].[URLs that were not in Google's search index] AS [URLs that were not in Google's search index],
[Extent1].[URLs for which we took no action] AS [URLs for which we took no action],
[Extent1].[URLs pending review] AS [URLs pending review],
[Extent1].[From Abuser] AS [From Abuser]
FROM
[dbo].[BPIrequests] AS [Extent1]
WHERE
((convert (datetime2, convert(varchar(255), [Extent1].[Date], 102) , 102)) >= (convert (datetime2, convert(varchar(255), convert(datetime2, '2019-01-11 19:44:10.0000000', 121), 102) , 102)))
AND ((convert (datetime2, convert(varchar(255), [Extent1].[Date], 102) , 102)) <= (convert (datetime2, convert(varchar(255), convert(datetime2, '2019-01-26 19:44:10.8392197', 121), 102) , 102)))
如果我在SSMS中将查询编辑为如下所示,它将立即运行:
SELECT
[Extent1].[Id] AS [Id],
[Extent1].[Request ID] AS [Request ID],
[Extent1].[Date] AS [Date],
[Extent1].[Lumen URL] AS [Lumen URL],
[Extent1].[Copyright owner ID] AS [Copyright owner ID],
[Extent1].[Copyright owner name] AS [Copyright owner name],
[Extent1].[Reporting organization ID] AS [Reporting organization ID],
[Extent1].[Reporting organization name] AS [Reporting organization name],
[Extent1].[URLs removed] AS [URLs removed],
[Extent1].[URLs that were not in Google's search index] AS [URLs that were not in Google's search index],
[Extent1].[URLs for which we took no action] AS [URLs for which we took no action],
[Extent1].[URLs pending review] AS [URLs pending review],
[Extent1].[From Abuser] AS [From Abuser]
FROM
[dbo].[BPIrequests] AS [Extent1]
WHERE
[Extent1].[Date] >= '2019-01-11'
AND [Extent1].[Date] <= '2019-01-26'
以下是用于比较的查询计划:
如何使Entity Framework使用日期索引?
答案 0 :(得分:1)
看起来EF查询中的日期来自一个字符串字段,而sql查询将字符串转换为日期,这使查询优化器感到困惑,并且索引从未得到利用。
您在Management Studio中编写的查询已将值视为日期,因此使用了索引。
您应该更改EF模型类,以将DateTime用作“日期”字段的类型