我正在使用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
我只是敲了我自己的SQL做查詢,它在一秒鐘內運行良好,sheesh .... SELECT * FROM Events AS E INNER JOIN People_Event_Link AS PE ON E.E_ID = PE。 E_ID INNER JOIN PEOPLE作爲P.P_ID = PE.P_ID其中P.P_ID = 291 – Calanus 2009-08-05 15:35:44