[英]Does the order of OrderBy, Select and Where clauses in Linq-to-entities matter
假設我有一張學生桌子,上面有許多列。 我想相當於EF
SELECT id,lastname,firstname
FROM students
WHERE coursename='Eurasian Nomads'
ORDER BY lastname,firstname
我只想要完整Student
模型的一部分,所以我制作了一個視圖模型
public class StudentView{
public int ID{get;set;}
public string LastName{get;set;}
public string FirstName{get;set;}
}
並且此EF代碼似乎有效:
List<StudentView> students=context.Students
.Where(s=>s.CourseName=="Eurasian Nomads")
.OrderBy(s=>s.LastName)
.ThenBy(s=>s.FirstName)
.Select(s=>new StudentView(){ID=s.ID,LastName=s.LastName,FirstName=s.FirstName})
.ToList();
但是我的問題是這些子句的順序是否根本重要,如果是的話,我應該遵循哪種規則以獲得最佳性能?
例如,這似乎也起作用:
List<StudentView> students=context.Students
.Select(s=>new StudentView(){ID=s.ID,LastName=s.LastName,FirstName=s.FirstName})
.OrderBy(s=>s.LastName)
.ThenBy(s=>s.FirstName)
.Where(s=>s.CourseName=="Eurasian Nomads")
.ToList();
在大多數情況下,針對服務器執行查詢之前創建查詢的順序並不重要。
實際上,優點之一是能夠通過串聯where,order by和其他子句來逐步創建查詢。
但是有時在某些地方順序會影響生成的sql。
提取您提供的樣本。 它們都可以正確編譯,但是第二個實際上並沒有執行。 如果您嘗試對EF數據庫運行此查詢,則會收到NotSupportedException :
System.NotSupportedException: The specified type member 'CourseName' is not supported in LINQ to Entities.
此處的關鍵是您嘗試通過視圖模型(StudentView)中的CourseName屬性而不是實體的屬性來過濾查詢。 所以你得到這個錯誤。
對於第一個查詢,它會正確生成此sql:
SELECT
[Extent1].[ID] AS [ID],
[Extent1].[LastName] AS [LastName],
[Extent1].[FirstName] AS [FirstName]
FROM [dbo].[Students] AS [Extent1]
WHERE N'Eurasian Nomads' = [Extent1].[CourseName]
ORDER BY [Extent1].[LastName] ASC, [Extent1].[FirstName] ASC
因此,您可以看到有時訂單很關鍵。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.