Skip to content

Commit b6a0d9b

Browse files
authored
Fix logic for indexer when parameter-type differs (#569)
1 parent 7334e67 commit b6a0d9b

File tree

3 files changed

+41
-1
lines changed

3 files changed

+41
-1
lines changed

NuGet.txt

+6
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,9 @@
1+
Open Command Prompt
2+
13
System.Linq.Dynamic.Core\src>
24

5+
del /S *.nupkg
6+
7+
VS rebuild
8+
39
dotnet nuget push **\*.nupkg --source https://api.nuget.org/v3/index.json --api-key x

src/System.Linq.Dynamic.Core/Parser/ExpressionParser.cs

+10-1
Original file line numberDiff line numberDiff line change
@@ -1965,7 +1965,16 @@ Expression ParseElementAccess(Expression expr)
19651965
throw ParseError(errorPos, Res.NoApplicableIndexer,
19661966
TypeHelper.GetTypeName(expr.Type));
19671967
case 1:
1968-
return Expression.Call(expr, (MethodInfo)mb, args);
1968+
var indexMethod = (MethodInfo)mb;
1969+
var indexParameterType = indexMethod.GetParameters().First().ParameterType;
1970+
1971+
var indexArgumentExpression = args[0]; // Indexer only has 1 parameter, so we can use args[0] here
1972+
if (indexParameterType != indexArgumentExpression.Type)
1973+
{
1974+
indexArgumentExpression = Expression.Convert(indexArgumentExpression, indexParameterType);
1975+
}
1976+
1977+
return Expression.Call(expr, indexMethod, indexArgumentExpression);
19691978

19701979
default:
19711980
throw ParseError(errorPos, Res.AmbiguousIndexerInvocation, TypeHelper.GetTypeName(expr.Type));

test/System.Linq.Dynamic.Core.Tests/QueryableTests.Select.cs

+25
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,12 @@
22
using System.Collections.Generic;
33
using System.Linq.Dynamic.Core.Exceptions;
44
using System.Linq.Dynamic.Core.Tests.Helpers.Models;
5+
using FluentAssertions;
56
using Linq.PropertyTranslator.Core;
67
using QueryInterceptor.Core;
78
using Xunit;
89
using NFluent;
10+
using Newtonsoft.Json.Linq;
911
#if EFCORE
1012
using Microsoft.AspNetCore.Identity;
1113
#else
@@ -348,6 +350,29 @@ public void Select_Dynamic_RenameParameterExpression_Is_True()
348350
Check.That(result).Equals("System.Int32[].Select(it => (it * it))");
349351
}
350352

353+
[Fact]
354+
public void Select_Dynamic_JObject_With_Array_Should_Use_Correct_Indexer()
355+
{
356+
// Arrange
357+
var j = new JObject
358+
{
359+
{"I", new JValue(9)},
360+
{"A", new JArray(new[] {1,2,3}) } ,
361+
{"L", new JValue(5)}
362+
};
363+
var queryable = new[] { j }.AsQueryable();
364+
365+
// Act
366+
var result = queryable.Select("new (long(I) as I, (new [] { long(A[0]), long(A[1]), long(A[2])}) as A, long(L) as L)").ToDynamicArray().First();
367+
368+
// Assert
369+
Assert.Equal(9, result.I);
370+
Assert.Equal(5, result.L);
371+
Assert.Equal(1, result.A[0]);
372+
Assert.Equal(2, result.A[1]);
373+
Assert.Equal(3, result.A[2]);
374+
}
375+
351376
[Fact]
352377
public void Select_Dynamic_ReservedKeyword()
353378
{

0 commit comments

Comments
 (0)