Search code examples
c#linqentity-frameworkentity-framework-5

Entity Framework (.NET Full Framework, NOT EF Core) Ordering Includes


I am trying to get something like the following to work:

_dbmsParentSections = FactoryTools.Factory.PdfSections
                        .Include(x => x.Children.OrderBy(y => y.Order).ToList())
                        .Include(x => x.Hint).Include(x => x.Fields)
                        .Where(x => x.FormId == FormId && x.Parent == null)
                        .OrderBy(o => o.Order)
                        .ToList();

The part that causes the exception is:

.Include(x => x.Children.OrderBy(y => y.Order).ToList())

EDIT:

Upon further observation,

_dbmsParentSections.ForEach(x => x.Children = x.Children.OrderBy(y => y.Order).ToList());

did the job for me (after the initial Factory call and without the Children.OrderBy).

EDIT: This is different from the way that EF Core handles this, since EF Core allows this: https://stackoverflow.com/a/66176285/550975


Solution

  • It seems you cannot sort the children collection in your query. Either sort after the query or load the children in a second query.

    Similar question and answer here