Search code examples
c#entity-frameworkorm

Entity Framework: does Select after OrderBy still guarantee ordered projections?


Let's say I have an Entity Framework 6 query which looks like this:

var orderedPayInfoes = context.Employees
       .Where(x => x.EmployeeId > 5)
       .OrderBy(x => x.CreatedOn)
       .Select(x => x.PayInfo);

I know that typings will not respect the previous declared order. e.g the type will be IQueryable<PayInfo> and not IOrderedQueryable<PayInfo>. Does the guarantee order?

Note: this cannot be validated properly only through testing since QueryConverter internally has optimizations which change the way SQL is written depending on the query provided.


Solution

  • Yes, in simple cases, it is guaranteed that the order is not changed after Select. Select is just a projection that retrieves only the needed fields.

    However, there is Eager Loading, and if you select collection properties like this:

    query.Select(x => new { x.PayInfo, x.Payers.ToList() });
    

    the single query algorithm may add an additional ORDER BY. See Single vs. Split Queries. Single query is the default behavior in EF6.

    The order can be changed after operations such as GroupBy, Distinct, Join, GroupJoin, and SelectMany.