我想知道爲什麼Entity框架會生成如此低效的SQL查詢。在我的代碼我預計其中一旦該行動INCLUDE:實體框架生成效率低下的SQL
db.Employment.Where(x => x.Active).Include(x => x.Employee).Where(x => x.Employee.UserID == UserID)
但我結束了一個雙重SQL JOIN:
SELECT [x].[ID], [x].[Active], [x].[CurrencyID], [x].[DepartmentID], [x].[EmplEnd], [x].[EmplStart], [x].[EmployeeID], [x].[HolidayGroupID], [x].[HourlyCost], [x].[JobTitle], [x].[ManagerID], [x].[WorkScheduleGroupID], [e].[ID], [e].[Active], [e].[Address], [e].[BirthDate], [e].[CitizenshipID], [e].[City], [e].[CountryID], [e].[Email], [e].[FirstName], [e].[Gender], [e].[LastName], [e].[Note], [e].[Phone], [e].[PostalCode], [e].[TaxNumber], [e].[UserID]
FROM [Employment] AS [x]
INNER JOIN [Employee] AS [x.Employee] ON [x].[EmployeeID] = [x.Employee].[ID]
INNER JOIN [Employee] AS [e] ON [x].[EmployeeID] = [e].[ID]
WHERE ([x].[Active] = 1) AND ([x.Employee].[UserID] = @__UserID_0)
我發現這個查詢將創造更好的SQL:
db.Employment.Where(x => x.Active).Where(x => x.Employee.UserID == UserID)
SELECT [x].[ID], [x].[Active], [x].[CurrencyID], [x].[DepartmentID], [x].[EmplEnd], [x].[EmplStart], [x].[EmployeeID], [x].[HolidayGroupID], [x].[HourlyCost], [x].[JobTitle], [x].[ManagerID], [x].[WorkScheduleGroupID]
FROM [Employment] AS [x]
INNER JOIN [Employee] AS [x.Employee] ON [x].[EmployeeID] = [x.Employee].[ID]
WHERE ([x].[Active] = 1) AND ([x.Employee].[UserID] = @__UserID_0)
但是,這裏引用的實體不會從數據庫中檢索到的問題。
爲什麼兩個代碼不會生成相同的SQL?
首先,您應該比較他們的查詢計劃 - 他們可能是相同的。 –
我在這裏沒有看到這一點,我使用EF作爲SQL的一個抽象層,如果我必須一直到查詢計劃,我可能更適合自己編寫SQL,而不是讓EF來執行它。 – Marko
在應用Include之後,您可以在使用&&運算符的方法中將兩個條件組合在一起。這應該會產生不同的查詢。 –