EF Core AsSplitQuery not respecting OrderBy

Viewed 554

I am using EF Core to query my DB. As I have some includes i get this warning

Compiling a query which loads related collections for more than one collection navigation either via 'Include' or through projection but no 'QuerySplittingBehavior' has been configured. By default Entity Framework will use 'QuerySplittingBehavior.SingleQuery' which can potentially result in slow query performance. See https://go.microsoft.com/fwlink/?linkid=2134277 for more information. To identify the query that's triggering this warning call 'ConfigureWarnings(w => w.Throw(RelationalEventId.MultipleCollectionIncludeWarning))'

so when i add AsSplitQuery()

public async Task<Board> GetBoardAsync (Guid id) {
            return await _context.Boards.Include (x => x.Lists.OrderBy(x => x.Order))
                  .ThenInclude (x => x.Items.OrderBy(x => x.Order))
                  .AsSplitQuery()
                  .FirstOrDefaultAsync (x => x.Id == id);
        }

OrderBy is not respected when returning data.

How to overcome this warning and respect OrderBy

thanks

1 Answers

Try this:-

public async Task<Board> GetBoardAsync (Guid id) {
            return await _context.Boards.Include (x => x.Lists.OrderBy(x => x.Order))
                  .ThenInclude (x => x.Items.OrderBy(x => x.Order))
                  .Where(x => x.Id == id)
                  .AsSplitQuery().FirstOrDefaultAsync();
        }

Also, you can use AsNoTracking() for queries to better performance.hope it will resolve your issue.

UPDATE

Use ThenBy instead of OrderBy because ThenBy works for several sorting criteria.

Related