Skuami
Skuami

Reputation: 1624

C# EF Order by included table

I am trying to sort by a field on a child table of a one-to-many relation with C# and EF.

That's what I am trying to achieve:

SELECT * FROM Parent AS P
INNER JOIN Child AS C ON P.Id = C.PartentId
ORDER BY C.CreateDate

I guess the code should look something like this:

_context.Parent.Include(x => x.Child).OrderBy(x => x.Child.CreateDate)

This doesnt work since x.Child is a list of child objects. Is there a way to sort by children on the SQL server. I found many solutions but they order the list in the application.

Upvotes: 0

Views: 74

Answers (1)

Guru Stron
Guru Stron

Reputation: 142833

use Join or just Select like this:

_context.Child
  .Select(c => new {c.Parent, Child = c})
  .OrderBy(x => x.Child.CreateDate)

Upvotes: 4

Related Questions