Let's say I have the following simplified Linq query which will be run against the database using LinqToSQL:
public IEnumerable<MembershipDto> GetAllUserMemberships()
{
return (from m in _workspace.GetDataSource<UserMembership>()
join g in _workspace.GetDataSource<Group>()
on m.GroupID equals g.GroupID
join u in _workspace.GetDataSource<User>()
on m.UserID equals u.UserID
select
new MembershipDto
{
GroupID = g.GroupID,
GroupName = g.Name,
UserID = u.UserID,
UserName = u.Name
}
).Distinct()
.OrderBy(x => x.GroupName)
.ThenBy(x => x.UserName);
}
For performance sake I want as much of this query as possible to be run inside the generated SQL query; however I want the maintain the business logic in Linq so it can be easily unit tested.
The issue I have is that I am uncertain where the above query stops being executed in SQL and starts being operated on in memory.
My assumption is that as soon as the data is being selected into the new MembershipDto
it is no longer being conducted in SQL; therefore the subsequent OrderBy()
ThenBy()
and Distinct()
operations occur in memory.
However the OrderBy()
produces a collection of type IOrderedQueryable
rather than an IOrderedEnumerable
; which indicates to me that the query may still be executed in its entirety in SQL.
Is my assumption correct, or is the whole query converted into SQL and if so why is this the case?