From @victorioberra
I am still encountering this issue. What am I doing wrong?
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)
The issue is caused by two thing that I can see:
OrderBy + ThenBy using the same column.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();
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