Does OrderBy, Select, and Where clause order in Linq-to-entities

Suppose I have a student table with tons of columns. I want the equivalent of EF

SELECT id,lastname,firstname 
FROM students 
WHERE coursename='Eurasian Nomads'
ORDER BY lastname,firstname

I just want a subset of the complete model Student, so I made a view model

public class StudentView{
    public int ID{get;set;}
    public string LastName{get;set;}
    public string FirstName{get;set;}
}

and this EF code works:

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();

But my question is, does the order of these articles really matter, and if so, what rules should be followed for better performance?

For example, this also works:

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();
+4
source share
1 answer

The order in which you create your request before executing it with the server does not matter in most cases.

, .

, sql.

, . , . EF, NotSupportedException:

System.NotSupportedException: The specified type member 'CourseName' is not supported in LINQ to Entities.

, CourseName (StudentView), . , .

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

, , .

+3
source

Source: https://habr.com/ru/post/1654042/


All Articles