gpt4 book ai didi

mysql - 如何优化 Entity Framework 查询

转载 作者:可可西里 更新时间:2023-11-01 07:29:31 25 4
gpt4 key购买 nike

我正在使用 Linq-To-Entities 执行查询,该查询仅返回 947 行但运行时间为 18 秒。我已经完成了一个“ToTraceString”来获取底层的 sql 并直接在数据库上运行相同的东西并获得相同的时间。

我使用了调优顾问并创建了几个索引,尽管影响很小。

查看查询执行计划,有几个嵌套循环占用了 95% 的时间,但这些循环已经在处理索引了?

有没有人对如何强制对 EF 查询进行某些优化有任何想法?

编辑:提供额外信息

三个表的基本ER图如下:

People >----People_Event_Link ----< Events
P_ID P_ID E_ID
E_ID

我正在运行的 linq 旨在为特定的人(使用 P_ID)取回所有事件:

        var query = from ev in genesisContext.Events
join pe in genesisContext.People_Event_Link
on ev equals pe.Event
where pe.P_ID == key
select ev;
return query;

这是生成的 SQL(深呼吸!):

SELECT 
1 AS [C1],
[Extent1].[E_ID] AS [E_ID],
[Extent1].[E_START_DATE] AS [E_START_DATE],
[Extent1].[E_END_DATE] AS [E_END_DATE],
[Extent1].[E_COMMENTS] AS [E_COMMENTS],
[Extent1].[E_DATE_ADDED] AS [E_DATE_ADDED],
[Extent1].[E_RECORDED_BY] AS [E_RECORDED_BY],
[Extent1].[E_DATE_UPDATED] AS [E_DATE_UPDATED],
[Extent1].[E_UPDATED_BY] AS [E_UPDATED_BY],
[Extent1].[ET_ID] AS [ET_ID],
[Extent1].[L_ID] AS [L_ID]
FROM [dbo].[Events] AS [Extent1]
INNER JOIN [dbo].[People_Event_Link] AS [Extent2] ON EXISTS (SELECT
1 AS [C1]
FROM ( SELECT 1 AS X ) AS [SingleRowTable1]
LEFT OUTER JOIN (SELECT
[Extent3].[E_ID] AS [E_ID]
FROM [dbo].[Events] AS [Extent3]
WHERE [Extent2].[E_ID] = [Extent3].[E_ID] ) AS [Project1] ON 1 = 1
LEFT OUTER JOIN (SELECT
[Extent4].[E_ID] AS [E_ID]
FROM [dbo].[Events] AS [Extent4]
WHERE [Extent2].[E_ID] = [Extent4].[E_ID] ) AS [Project2] ON 1 = 1
WHERE ([Extent1].[E_ID] = [Project1].[E_ID]) OR (([Extent1].[E_ID] IS NULL) AND ([Project2].[E_ID] IS NULL))
)
WHERE [Extent2].[P_ID] = 291

最佳答案

是的。重写 LINQ 查询。大多数 LINQ to Entities 查询都可以用多种不同的方式编写,并且会以不同的方式转换为 SQL。由于您既没有显示 LINQ 也没有显示 SQL 也没有显示查询计划,所以我只能说这些。

不过,您很聪明,尝试直接执行 SQL。查询编译也可能需要时间,但您已通过确定 SQL 占所有测量时间来排除这种情况。

尝试:

    var query = from pe in genesisContext.People_Event_Link
where pe.P_ID == key
from ev in pe.Event // presuming one to many
select ev;

或者如果 pe.Event 是一对一的:

    var query = from pe in genesisContext.People_Event_Link
where pe.P_ID == key
select pe.Event;

return query;

关于mysql - 如何优化 Entity Framework 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1233245/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com