Efcore: Query: ArgumentOutOfRangeException when doing multiple ordering on same property in collection include

Created on 19 Jul 2018  路  4Comments  路  Source: dotnet/efcore

From @victorioberra

I am still encountering this issue. What am I doing wrong?

Error:

Unhandled Exception: System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
at Microsoft.EntityFrameworkCore.Query.Expressions.SelectExpression.BindSubqueryProjectionIndex(Int32 projectionIndex, IQuerySource querySource)
at Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.SqlTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)

Working code example with sqlite

  1. clone
  2. dotnet restore
  3. dotnet run

The issue is caused by two thing that I can see:

  • OrderBy + ThenBy using the same column.
  • The inner projection with the .ToList()
var results = context.Cat
   .OrderBy(x => x.MeowLoudness)
   .ThenBy(x => x.MeowLoudness)

   .Select(x => new CatViewModel()
   {
       Id = x.Id,
       Name = x.Name,
       Breed = new CatBreedViewModel() {
           Id = x.Breed.Id,
           BreedName = x.Breed.BreedName,
           Cats = x.Breed.Cats.Select(y => new CatViewModel()
           {
               Id = y.Id,
               MeowLoudness = y.MeowLoudness,
               Name = y.Name,
               TailLength = y.TailLength
           }).ToList()
       },
       MeowLoudness = x.MeowLoudness,
       TailLength = x.TailLength
   })
   .ToList();
closed-fixed type-bug

All 4 comments

We could fix it in query model optimizer by ignoring first OrderBy if its followed by ThenBy on the same column.

I am not sure that would work. That example is a simplification of more advanced scenarios. IE:

   .OrderBy(x => x.MeowLoudness)
   .ThenByDescending(x => x.TailLength)
   .ThenBy(x => x.MeowLoudness)

You may end up with a different order than when you started with that code.

This code also errors.

@maumar - Instead of ignoring client ordering, we need to de-dupe them while adding to AnonymousObject in collection query and then still having ordering repeated in outer QM. Essentially, whatever maps to same thing in SQL should be same in AnonymousObject.

fixed in f053431cd078eb68a5ae6dd0d57cc5e278c9ec4e

Was this page helpful?
0 / 5 - 0 ratings