eugenekgn
eugenekgn

Reputation: 1722

Entity Framework sorting nested collection

How would I sort (orderby) property of a nested collection (collection within a collection)

if (query.Sort.ProjectA == SortOperation.Desc)
{
    entities = entities
               .OrderByDescending(r => r.ProjectCollection.Select(p => p.JobNumber));
}
else
{
    entities = entities.OrderBy(r => r.ProjectCollection.Select(p =>p.JobNumber));
}

I get the following error for the code above

DbSortClause expressions must have a type that is order comparable.
Parameter name: key

Upvotes: 1

Views: 2696

Answers (1)

Servy
Servy

Reputation: 203804

Reverse your use of Select and OrderBy. Don't order by a selected collection, select out an ordered collection:

var query = entities.Select(r => r.ProjectACollection.OrderBy(p => p.JobNumber));

If you want other fields as well, select out a new entity or some other type with all of the other fields that you want included as well.

Upvotes: 2

Related Questions