-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
NavigationExpandingExpressionVisitor.cs
2312 lines (1963 loc) · 106 KB
/
NavigationExpandingExpressionVisitor.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics.CodeAnalysis;
using Microsoft.EntityFrameworkCore.Internal;
using ExpressionExtensions = Microsoft.EntityFrameworkCore.Infrastructure.ExpressionExtensions;
namespace Microsoft.EntityFrameworkCore.Query.Internal;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public partial class NavigationExpandingExpressionVisitor : ExpressionVisitor
{
private static readonly PropertyInfo QueryContextContextPropertyInfo
= typeof(QueryContext).GetTypeInfo().GetDeclaredProperty(nameof(QueryContext.Context))!;
private static readonly Dictionary<MethodInfo, MethodInfo> PredicateLessMethodInfo = new()
{
{ QueryableMethods.FirstWithPredicate, QueryableMethods.FirstWithoutPredicate },
{ QueryableMethods.FirstOrDefaultWithPredicate, QueryableMethods.FirstOrDefaultWithoutPredicate },
{ QueryableMethods.SingleWithPredicate, QueryableMethods.SingleWithoutPredicate },
{ QueryableMethods.SingleOrDefaultWithPredicate, QueryableMethods.SingleOrDefaultWithoutPredicate },
{ QueryableMethods.LastWithPredicate, QueryableMethods.LastWithoutPredicate },
{ QueryableMethods.LastOrDefaultWithPredicate, QueryableMethods.LastOrDefaultWithoutPredicate }
};
private static readonly List<MethodInfo> SupportedFilteredIncludeOperations =
[
QueryableMethods.Where,
QueryableMethods.OrderBy,
QueryableMethods.OrderByDescending,
QueryableMethods.ThenBy,
QueryableMethods.ThenByDescending,
QueryableMethods.Skip,
QueryableMethods.Take,
QueryableMethods.AsQueryable
];
private readonly QueryTranslationPreprocessor _queryTranslationPreprocessor;
private readonly QueryCompilationContext _queryCompilationContext;
private readonly PendingSelectorExpandingExpressionVisitor _pendingSelectorExpandingExpressionVisitor;
private readonly SubqueryMemberPushdownExpressionVisitor _subqueryMemberPushdownExpressionVisitor;
private readonly NullCheckRemovingExpressionVisitor _nullCheckRemovingExpressionVisitor;
private readonly ReducingExpressionVisitor _reducingExpressionVisitor;
private readonly EntityReferenceOptionalMarkingExpressionVisitor _entityReferenceOptionalMarkingExpressionVisitor;
private readonly RemoveRedundantNavigationComparisonExpressionVisitor _removeRedundantNavigationComparisonExpressionVisitor;
private readonly HashSet<string> _parameterNames = [];
private readonly ExpressionTreeFuncletizer _funcletizer;
private readonly INavigationExpansionExtensibilityHelper _extensibilityHelper;
private readonly HashSet<IEntityType> _nonCyclicAutoIncludeEntityTypes;
private readonly Dictionary<IEntityType, LambdaExpression> _parameterizedQueryFilterPredicateCache
= new();
private readonly Parameters _parameters = new();
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public NavigationExpandingExpressionVisitor(
QueryTranslationPreprocessor queryTranslationPreprocessor,
QueryCompilationContext queryCompilationContext,
IEvaluatableExpressionFilter evaluatableExpressionFilter,
INavigationExpansionExtensibilityHelper extensibilityHelper)
{
_queryTranslationPreprocessor = queryTranslationPreprocessor;
_queryCompilationContext = queryCompilationContext;
_extensibilityHelper = extensibilityHelper;
_pendingSelectorExpandingExpressionVisitor = new PendingSelectorExpandingExpressionVisitor(this, extensibilityHelper);
_subqueryMemberPushdownExpressionVisitor = new SubqueryMemberPushdownExpressionVisitor(queryCompilationContext.Model);
_nullCheckRemovingExpressionVisitor = new NullCheckRemovingExpressionVisitor();
_reducingExpressionVisitor = new ReducingExpressionVisitor();
_entityReferenceOptionalMarkingExpressionVisitor = new EntityReferenceOptionalMarkingExpressionVisitor();
_removeRedundantNavigationComparisonExpressionVisitor = new RemoveRedundantNavigationComparisonExpressionVisitor(
queryCompilationContext.Logger);
_funcletizer = new ExpressionTreeFuncletizer(
_queryCompilationContext.Model,
evaluatableExpressionFilter,
_queryCompilationContext.ContextType,
generateContextAccessors: true,
_queryCompilationContext.Logger);
_nonCyclicAutoIncludeEntityTypes = !_queryCompilationContext.IgnoreAutoIncludes ? [] : null!;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual Expression Expand(Expression query)
{
var result = Visit(query);
if (result is GroupByNavigationExpansionExpression groupByNavigationExpansionExpression)
{
if (!(groupByNavigationExpansionExpression.Source is MethodCallExpression { Method.IsGenericMethod: true } methodCallExpression
&& methodCallExpression.Method.GetGenericMethodDefinition() == QueryableMethods.GroupByWithKeySelector))
{
// If the final operator is not GroupBy in source then GroupBy is not final operator. We throw exception.
throw new InvalidOperationException(CoreStrings.TranslationFailed(query.Print()));
}
var groupingQueryable = groupByNavigationExpansionExpression.GroupingEnumerable.Source;
var innerEnumerable = new PendingSelectorExpandingExpressionVisitor(this, _extensibilityHelper, applyIncludes: true).Visit(
groupByNavigationExpansionExpression.GroupingEnumerable);
innerEnumerable = Reduce(innerEnumerable);
if (innerEnumerable is MethodCallExpression { Method.IsGenericMethod: true } selectMethodCall
&& selectMethodCall.Method.GetGenericMethodDefinition() == QueryableMethods.Select)
{
var elementSelector = selectMethodCall.Arguments[1];
var elementSelectorLambda = elementSelector.UnwrapLambdaFromQuote();
// We do have element selector to inject which may have potentially expanded navigations
var oldKeySelectorLambda = methodCallExpression.Arguments[1].UnwrapLambdaFromQuote();
var newSource = ReplacingExpressionVisitor.Replace(
groupingQueryable, methodCallExpression.Arguments[0], selectMethodCall.Arguments[0]);
var oldKeySelectorParameterType = oldKeySelectorLambda.Parameters[0].Type;
var keySelectorParameter = Expression.Parameter(elementSelectorLambda.Parameters[0].Type);
var keySelectorMemberAccess = (Expression)keySelectorParameter;
while (keySelectorMemberAccess.Type != oldKeySelectorParameterType)
{
keySelectorMemberAccess = Expression.MakeMemberAccess(
keySelectorMemberAccess,
keySelectorMemberAccess.Type.GetTypeInfo().GetDeclaredField("Outer")!);
}
var keySelectorLambda = Expression.Lambda(
ReplacingExpressionVisitor.Replace(
oldKeySelectorLambda.Parameters[0], keySelectorMemberAccess, oldKeySelectorLambda.Body),
keySelectorParameter);
result = Expression.Call(
QueryableMethods.GroupByWithKeyElementSelector.MakeGenericMethod(
newSource.Type.GetSequenceType(),
keySelectorLambda.ReturnType,
elementSelectorLambda.ReturnType),
newSource,
Expression.Quote(keySelectorLambda),
elementSelector);
}
else
{
// Pending selector was identity so nothing to apply, we can return source as-is.
result = groupByNavigationExpansionExpression.Source;
}
}
else
{
result = new PendingSelectorExpandingExpressionVisitor(this, _extensibilityHelper, applyIncludes: true).Visit(result);
result = Reduce(result);
}
var dbContextOnQueryContextPropertyAccess =
Expression.Convert(
Expression.Property(
QueryCompilationContext.QueryContextParameter,
QueryContextContextPropertyInfo),
_queryCompilationContext.ContextType);
foreach (var (key, value) in _parameters.ParameterValues)
{
var lambda = (LambdaExpression)value!;
var remappedLambdaBody = ReplacingExpressionVisitor.Replace(
lambda.Parameters[0],
dbContextOnQueryContextPropertyAccess,
lambda.Body);
_queryCompilationContext.RegisterRuntimeParameter(
key,
Expression.Lambda(
remappedLambdaBody.Type.IsValueType
? Expression.Convert(remappedLambdaBody, typeof(object))
: remappedLambdaBody,
QueryCompilationContext.QueryContextParameter));
}
return result;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitExtension(Expression extensionExpression)
{
switch (extensionExpression)
{
case EntityQueryRootExpression entityQueryRootExpression:
var entityType = entityQueryRootExpression.EntityType;
#pragma warning disable CS0618 // Type or member is obsolete
var definingQuery = entityType.GetDefiningQuery();
#pragma warning restore CS0618 // Type or member is obsolete
NavigationExpansionExpression navigationExpansionExpression;
if (definingQuery != null
// Apply defining query only when it is not custom query root
&& entityQueryRootExpression.GetType() == typeof(EntityQueryRootExpression))
{
// TODO: #33509: merge NRT information (nonNullableReferenceTypeParameters) for parameters introduced by the query
// TODO: filter into the QueryCompilationContext.NonNullableReferenceTypeParameters
var processedDefiningQueryBody = _funcletizer.ExtractParameters(
definingQuery.Body, _parameters, parameterize: false, clearParameterizedValues: false,
_queryCompilationContext.IsPrecompiling);
processedDefiningQueryBody = _queryTranslationPreprocessor.NormalizeQueryableMethod(processedDefiningQueryBody);
processedDefiningQueryBody = _nullCheckRemovingExpressionVisitor.Visit(processedDefiningQueryBody);
processedDefiningQueryBody =
new SelfReferenceEntityQueryableRewritingExpressionVisitor(this, entityType).Visit(processedDefiningQueryBody);
processedDefiningQueryBody = Visit(processedDefiningQueryBody);
processedDefiningQueryBody = _pendingSelectorExpandingExpressionVisitor.Visit(processedDefiningQueryBody);
processedDefiningQueryBody = Reduce(processedDefiningQueryBody);
navigationExpansionExpression = CreateNavigationExpansionExpression(processedDefiningQueryBody, entityType);
}
else
{
navigationExpansionExpression = CreateNavigationExpansionExpression(
base.VisitExtension(entityQueryRootExpression), entityType);
}
return ApplyQueryFilter(entityType, navigationExpansionExpression);
// Inline query roots can contain arbitrary expressions, including subqueries with navigations; visit inside to process those.
case InlineQueryRootExpression inlineQueryRootExpression:
{
var visited = inlineQueryRootExpression.Update(this.VisitAndConvert(inlineQueryRootExpression.Values));
var currentTree = new NavigationTreeExpression(Expression.Default(inlineQueryRootExpression.ElementType));
var parameterName = GetParameterName("e");
return new NavigationExpansionExpression(visited, currentTree, currentTree, parameterName);
}
case QueryRootExpression queryRootExpression:
{
var currentTree = new NavigationTreeExpression(Expression.Default(queryRootExpression.ElementType));
var parameterName = GetParameterName("e");
return new NavigationExpansionExpression(queryRootExpression, currentTree, currentTree, parameterName);
}
case NavigationExpansionExpression:
case OwnedNavigationReference:
return extensionExpression;
default:
return base.VisitExtension(extensionExpression);
}
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitMember(MemberExpression memberExpression)
{
var innerExpression = Visit(memberExpression.Expression);
// Convert ICollection<T>.Count to Count<T>()
if (memberExpression.Expression != null
&& innerExpression != null
&& memberExpression.Member.Name == nameof(ICollection<int>.Count)
&& memberExpression.Expression.Type.GetInterfaces().Append(memberExpression.Expression.Type)
.Any(
e => e.IsGenericType
&& (e.GetGenericTypeDefinition() is Type genericTypeDefinition
&& (genericTypeDefinition == typeof(ICollection<>)
|| genericTypeDefinition == typeof(IReadOnlyCollection<>)))))
{
var innerQueryable = UnwrapCollectionMaterialization(innerExpression);
if (innerQueryable.Type.TryGetElementType(typeof(IQueryable<>)) != null)
{
return Visit(
Expression.Call(
QueryableMethods.CountWithoutPredicate.MakeGenericMethod(innerQueryable.Type.GetSequenceType()),
innerQueryable));
}
}
var updatedExpression = (Expression)memberExpression.Update(innerExpression);
if (innerExpression is NavigationExpansionExpression navigationExpansionExpression
&& navigationExpansionExpression.CardinalityReducingGenericMethodInfo != null)
{
// This is FirstOrDefault.Member
// due to SubqueryMemberPushdown, this may be collection navigation which was not pushed down
navigationExpansionExpression =
(NavigationExpansionExpression)_pendingSelectorExpandingExpressionVisitor.Visit(navigationExpansionExpression);
var expandedExpression =
new ExpandingExpressionVisitor(this, navigationExpansionExpression, _extensibilityHelper).Visit(updatedExpression);
if (expandedExpression != updatedExpression)
{
updatedExpression = Visit(expandedExpression);
}
}
return updatedExpression;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitMethodCall(MethodCallExpression methodCallExpression)
{
var method = methodCallExpression.Method;
if (method.DeclaringType == typeof(Queryable)
|| method.DeclaringType == typeof(QueryableExtensions)
|| method.DeclaringType == typeof(EntityFrameworkQueryableExtensions))
{
var genericMethod = method.IsGenericMethod ? method.GetGenericMethodDefinition() : null;
// First argument is source
var firstArgument = Visit(methodCallExpression.Arguments[0]);
if (firstArgument is NavigationExpansionExpression source)
{
if (source.PendingOrderings.Any()
&& genericMethod != QueryableMethods.ThenBy
&& genericMethod != QueryableMethods.ThenByDescending)
{
ApplyPendingOrderings(source);
}
switch (method.Name)
{
case nameof(Queryable.AsQueryable)
when genericMethod == QueryableMethods.AsQueryable:
return source;
case nameof(Queryable.Any)
when genericMethod == QueryableMethods.AnyWithoutPredicate:
case nameof(Queryable.Count)
when genericMethod == QueryableMethods.CountWithoutPredicate:
case nameof(Queryable.LongCount)
when genericMethod == QueryableMethods.LongCountWithoutPredicate:
return ProcessAllAnyCountLongCount(
source,
genericMethod,
predicate: null);
case nameof(Queryable.All)
when genericMethod == QueryableMethods.All:
case nameof(Queryable.Any)
when genericMethod == QueryableMethods.AnyWithPredicate:
case nameof(Queryable.Count)
when genericMethod == QueryableMethods.CountWithPredicate:
case nameof(Queryable.LongCount)
when genericMethod == QueryableMethods.LongCountWithPredicate:
return ProcessAllAnyCountLongCount(
source,
genericMethod,
methodCallExpression.Arguments[1].UnwrapLambdaFromQuote());
case nameof(Queryable.Average)
when QueryableMethods.IsAverageWithoutSelector(method):
case nameof(Queryable.Max)
when genericMethod == QueryableMethods.MaxWithoutSelector:
case nameof(Queryable.Min)
when genericMethod == QueryableMethods.MinWithoutSelector:
case nameof(Queryable.Sum)
when QueryableMethods.IsSumWithoutSelector(method):
return ProcessAverageMaxMinSum(
source,
genericMethod ?? method,
selector: null);
case nameof(Queryable.Average)
when QueryableMethods.IsAverageWithSelector(method):
case nameof(Queryable.Sum)
when QueryableMethods.IsSumWithSelector(method):
case nameof(Queryable.Max)
when genericMethod == QueryableMethods.MaxWithSelector:
case nameof(Queryable.Min)
when genericMethod == QueryableMethods.MinWithSelector:
return ProcessAverageMaxMinSum(
source,
genericMethod ?? method,
methodCallExpression.Arguments[1].UnwrapLambdaFromQuote());
case nameof(Queryable.Distinct)
when genericMethod == QueryableMethods.Distinct:
return ProcessDistinct(source, genericMethod);
case nameof(Queryable.Skip)
when genericMethod == QueryableMethods.Skip:
case nameof(Queryable.Take)
when genericMethod == QueryableMethods.Take:
return ProcessSkipTake(
source,
genericMethod,
methodCallExpression.Arguments[1]);
case nameof(Queryable.Contains)
when genericMethod == QueryableMethods.Contains:
return ProcessContains(
source,
methodCallExpression.Arguments[1]);
case nameof(Queryable.First)
when genericMethod == QueryableMethods.FirstWithoutPredicate:
case nameof(Queryable.FirstOrDefault)
when genericMethod == QueryableMethods.FirstOrDefaultWithoutPredicate:
case nameof(Queryable.Single)
when genericMethod == QueryableMethods.SingleWithoutPredicate:
case nameof(Queryable.SingleOrDefault)
when genericMethod == QueryableMethods.SingleOrDefaultWithoutPredicate:
case nameof(Queryable.Last)
when genericMethod == QueryableMethods.LastWithoutPredicate:
case nameof(Queryable.LastOrDefault)
when genericMethod == QueryableMethods.LastOrDefaultWithoutPredicate:
return ProcessFirstSingleLastOrDefault(
source,
genericMethod,
predicate: null,
methodCallExpression.Type);
case nameof(Queryable.First)
when genericMethod == QueryableMethods.FirstWithPredicate:
case nameof(Queryable.FirstOrDefault)
when genericMethod == QueryableMethods.FirstOrDefaultWithPredicate:
case nameof(Queryable.Single)
when genericMethod == QueryableMethods.SingleWithPredicate:
case nameof(Queryable.SingleOrDefault)
when genericMethod == QueryableMethods.SingleOrDefaultWithPredicate:
case nameof(Queryable.Last)
when genericMethod == QueryableMethods.LastWithPredicate:
case nameof(Queryable.LastOrDefault)
when genericMethod == QueryableMethods.LastOrDefaultWithPredicate:
return ProcessFirstSingleLastOrDefault(
source,
genericMethod,
methodCallExpression.Arguments[1].UnwrapLambdaFromQuote(),
methodCallExpression.Type);
case nameof(Queryable.ElementAt)
when genericMethod == QueryableMethods.ElementAt:
case nameof(Queryable.ElementAtOrDefault)
when genericMethod == QueryableMethods.ElementAtOrDefault:
return ProcessElementAt(
source,
genericMethod,
methodCallExpression.Arguments[1],
methodCallExpression.Type);
case nameof(Queryable.Join)
when genericMethod == QueryableMethods.Join:
{
var secondArgument = Visit(methodCallExpression.Arguments[1]);
secondArgument = UnwrapCollectionMaterialization(secondArgument);
if (secondArgument is NavigationExpansionExpression innerSource)
{
return ProcessJoin(
source,
innerSource,
methodCallExpression.Arguments[2].UnwrapLambdaFromQuote(),
methodCallExpression.Arguments[3].UnwrapLambdaFromQuote(),
methodCallExpression.Arguments[4].UnwrapLambdaFromQuote());
}
goto default;
}
case nameof(QueryableExtensions.LeftJoin)
when genericMethod == QueryableExtensions.LeftJoinMethodInfo:
{
var secondArgument = Visit(methodCallExpression.Arguments[1]);
secondArgument = UnwrapCollectionMaterialization(secondArgument);
if (secondArgument is NavigationExpansionExpression innerSource)
{
return ProcessLeftJoin(
source,
innerSource,
methodCallExpression.Arguments[2].UnwrapLambdaFromQuote(),
methodCallExpression.Arguments[3].UnwrapLambdaFromQuote(),
methodCallExpression.Arguments[4].UnwrapLambdaFromQuote());
}
goto default;
}
case nameof(Queryable.SelectMany)
when genericMethod == QueryableMethods.SelectManyWithoutCollectionSelector:
return ProcessSelectMany(
source,
methodCallExpression.Arguments[1].UnwrapLambdaFromQuote(),
null);
case nameof(Queryable.SelectMany)
when genericMethod == QueryableMethods.SelectManyWithCollectionSelector:
return ProcessSelectMany(
source,
methodCallExpression.Arguments[1].UnwrapLambdaFromQuote(),
methodCallExpression.Arguments[2].UnwrapLambdaFromQuote());
case nameof(Queryable.Concat)
when genericMethod == QueryableMethods.Concat:
case nameof(Queryable.Except)
when genericMethod == QueryableMethods.Except:
case nameof(Queryable.Intersect)
when genericMethod == QueryableMethods.Intersect:
case nameof(Queryable.Union)
when genericMethod == QueryableMethods.Union:
{
var secondArgument = Visit(methodCallExpression.Arguments[1]);
secondArgument = UnwrapCollectionMaterialization(secondArgument);
if (secondArgument is NavigationExpansionExpression innerSource)
{
return ProcessSetOperation(source, genericMethod, innerSource);
}
goto default;
}
case nameof(Queryable.Cast)
when genericMethod == QueryableMethods.Cast:
case nameof(Queryable.OfType)
when genericMethod == QueryableMethods.OfType:
return ProcessCastOfType(
source,
genericMethod,
methodCallExpression.Type.GetSequenceType());
case nameof(EntityFrameworkQueryableExtensions.Include):
return ProcessInclude(
source,
methodCallExpression.Arguments[1],
thenInclude: false,
setLoaded: true);
case nameof(EntityFrameworkQueryableExtensions.ThenInclude):
return ProcessInclude(
source,
methodCallExpression.Arguments[1],
thenInclude: true,
setLoaded: true);
case nameof(EntityFrameworkQueryableExtensions.NotQuiteInclude):
return ProcessInclude(
source,
methodCallExpression.Arguments[1],
thenInclude: false,
setLoaded: false);
// Handled by relational/provider even though method is on `EntityFrameworkQueryableExtensions`
case nameof(EntityFrameworkQueryableExtensions.ExecuteDelete):
case nameof(EntityFrameworkQueryableExtensions.ExecuteDeleteAsync):
case nameof(EntityFrameworkQueryableExtensions.ExecuteUpdate):
case nameof(EntityFrameworkQueryableExtensions.ExecuteUpdateAsync):
return ProcessUnknownMethod(methodCallExpression);
case nameof(Queryable.GroupBy)
when genericMethod == QueryableMethods.GroupByWithKeySelector:
return ProcessGroupBy(
source,
methodCallExpression.Arguments[1].UnwrapLambdaFromQuote(),
null,
null);
case nameof(Queryable.GroupBy)
when genericMethod == QueryableMethods.GroupByWithKeyElementSelector:
return ProcessGroupBy(
source,
methodCallExpression.Arguments[1].UnwrapLambdaFromQuote(),
methodCallExpression.Arguments[2].UnwrapLambdaFromQuote(),
null);
case nameof(Queryable.GroupBy)
when genericMethod == QueryableMethods.GroupByWithKeyElementResultSelector:
return ProcessGroupBy(
source,
methodCallExpression.Arguments[1].UnwrapLambdaFromQuote(),
methodCallExpression.Arguments[2].UnwrapLambdaFromQuote(),
methodCallExpression.Arguments[3].UnwrapLambdaFromQuote());
case nameof(Queryable.GroupBy)
when genericMethod == QueryableMethods.GroupByWithKeyResultSelector:
return ProcessGroupBy(
source,
methodCallExpression.Arguments[1].UnwrapLambdaFromQuote(),
null,
methodCallExpression.Arguments[2].UnwrapLambdaFromQuote());
case nameof(Queryable.OrderBy)
when genericMethod == QueryableMethods.OrderBy:
case nameof(Queryable.OrderByDescending)
when genericMethod == QueryableMethods.OrderByDescending:
return ProcessOrderByThenBy(
source,
genericMethod,
methodCallExpression.Arguments[1].UnwrapLambdaFromQuote(),
thenBy: false);
case nameof(Queryable.ThenBy)
when genericMethod == QueryableMethods.ThenBy:
case nameof(Queryable.ThenByDescending)
when genericMethod == QueryableMethods.ThenByDescending:
return ProcessOrderByThenBy(
source,
genericMethod,
methodCallExpression.Arguments[1].UnwrapLambdaFromQuote(),
thenBy: true);
case nameof(Queryable.Reverse)
when genericMethod == QueryableMethods.Reverse:
return ProcessReverse(source);
case nameof(Queryable.Select)
when genericMethod == QueryableMethods.Select:
return ProcessSelect(
source,
methodCallExpression.Arguments[1].UnwrapLambdaFromQuote());
case nameof(Queryable.Where)
when genericMethod == QueryableMethods.Where:
return ProcessWhere(
source,
methodCallExpression.Arguments[1].UnwrapLambdaFromQuote());
case nameof(Queryable.DefaultIfEmpty)
when genericMethod == QueryableMethods.DefaultIfEmptyWithoutArgument:
return ProcessDefaultIfEmpty(source);
default:
// Aggregate overloads
// GroupJoin overloads
// Zip
// SequenceEqual overloads
// ElementAt
// ElementAtOrDefault
// SkipWhile
// TakeWhile
// DefaultIfEmpty with argument
// Index based lambda overloads of Where, SkipWhile, TakeWhile, Select, SelectMany
// IEqualityComparer overloads of Distinct, Contains, Join, Except, Intersect, Union, OrderBy, ThenBy, OrderByDescending, ThenByDescending, GroupBy
throw new InvalidOperationException(
CoreStrings.TranslationFailed(
_reducingExpressionVisitor.Visit(methodCallExpression).Print()));
}
}
if (firstArgument is GroupByNavigationExpansionExpression groupBySource)
{
switch (method.Name)
{
case nameof(Queryable.AsQueryable)
when genericMethod == QueryableMethods.AsQueryable:
return groupBySource;
case nameof(Queryable.Any)
when genericMethod == QueryableMethods.AnyWithoutPredicate:
case nameof(Queryable.Count)
when genericMethod == QueryableMethods.CountWithoutPredicate:
case nameof(Queryable.LongCount)
when genericMethod == QueryableMethods.LongCountWithoutPredicate:
return ProcessAllAnyCountLongCount(
groupBySource,
genericMethod,
predicate: null);
case nameof(Queryable.All)
when genericMethod == QueryableMethods.All:
case nameof(Queryable.Any)
when genericMethod == QueryableMethods.AnyWithPredicate:
case nameof(Queryable.Count)
when genericMethod == QueryableMethods.CountWithPredicate:
case nameof(Queryable.LongCount)
when genericMethod == QueryableMethods.LongCountWithPredicate:
return ProcessAllAnyCountLongCount(
groupBySource,
genericMethod,
methodCallExpression.Arguments[1].UnwrapLambdaFromQuote());
// case nameof(Queryable.Average)
// when QueryableMethods.IsAverageWithoutSelector(method):
// case nameof(Queryable.Max)
// when genericMethod == QueryableMethods.MaxWithoutSelector:
// case nameof(Queryable.Min)
// when genericMethod == QueryableMethods.MinWithoutSelector:
// case nameof(Queryable.Sum)
// when QueryableMethods.IsSumWithoutSelector(method):
// return ProcessAverageMaxMinSum(
// groupBySource,
// genericMethod ?? method,
// selector: null);
// case nameof(Queryable.Average)
// when QueryableMethods.IsAverageWithSelector(method):
// case nameof(Queryable.Sum)
// when QueryableMethods.IsSumWithSelector(method):
// case nameof(Queryable.Max)
// when genericMethod == QueryableMethods.MaxWithSelector:
// case nameof(Queryable.Min)
// when genericMethod == QueryableMethods.MinWithSelector:
// return ProcessAverageMaxMinSum(
// groupBySource,
// genericMethod ?? method,
// methodCallExpression.Arguments[1].UnwrapLambdaFromQuote());
case nameof(Queryable.OrderBy)
when genericMethod == QueryableMethods.OrderBy:
case nameof(Queryable.OrderByDescending)
when genericMethod == QueryableMethods.OrderByDescending:
return ProcessOrderByThenBy(
groupBySource,
genericMethod,
methodCallExpression.Arguments[1].UnwrapLambdaFromQuote());
case nameof(Queryable.ThenBy)
when genericMethod == QueryableMethods.ThenBy:
case nameof(Queryable.ThenByDescending)
when genericMethod == QueryableMethods.ThenByDescending:
return ProcessOrderByThenBy(
groupBySource,
genericMethod,
methodCallExpression.Arguments[1].UnwrapLambdaFromQuote());
case nameof(Queryable.Select)
when genericMethod == QueryableMethods.Select:
var result = ProcessSelect(
groupBySource,
methodCallExpression.Arguments[1].UnwrapLambdaFromQuote());
if (result == null)
{
throw new InvalidOperationException(
CoreStrings.TranslationFailedWithDetails(
_reducingExpressionVisitor.Visit(methodCallExpression).Print(),
CoreStrings.QuerySelectContainsGrouping));
}
return result;
case nameof(Queryable.Skip)
when genericMethod == QueryableMethods.Skip:
case nameof(Queryable.Take)
when genericMethod == QueryableMethods.Take:
return ProcessSkipTake(
groupBySource,
genericMethod,
methodCallExpression.Arguments[1]);
case nameof(Queryable.Where)
when genericMethod == QueryableMethods.Where:
return ProcessWhere(
groupBySource,
methodCallExpression.Arguments[1].UnwrapLambdaFromQuote());
default:
// Average/Max/Min/Sum
// Distinct
// Contains
// First/Single/Last(OrDefault)
// Join, LeftJoin, GroupJoin
// SelectMany
// Concat/Except/Intersect/Union
// Cast/OfType
// Include/ThenInclude/NotQuiteInclude
// GroupBy
// Reverse
// DefaultIfEmpty
throw new InvalidOperationException(
CoreStrings.TranslationFailed(
_reducingExpressionVisitor.Visit(methodCallExpression).Print()));
}
}
if (genericMethod == QueryableMethods.AsQueryable)
{
if (firstArgument is NavigationTreeExpression { Type.IsGenericType: true } navigationTreeExpression
&& navigationTreeExpression.Type.GetGenericTypeDefinition() == typeof(IGrouping<,>))
{
// This is groupingElement.AsQueryable so we preserve it
return Expression.Call(
QueryableMethods.AsQueryable.MakeGenericMethod(navigationTreeExpression.Type.GetSequenceType()),
navigationTreeExpression);
}
return UnwrapCollectionMaterialization(firstArgument);
}
if (firstArgument.Type.TryGetElementType(typeof(IQueryable<>)) == null)
{
// firstArgument was not an queryable
var visitedArguments = new[] { firstArgument }
.Concat(methodCallExpression.Arguments.Skip(1).Select(e => Visit(e)));
return ConvertToEnumerable(method, visitedArguments);
}
throw new InvalidOperationException(CoreStrings.TranslationFailed(methodCallExpression.Print()));
}
// Remove MaterializeCollectionNavigationExpression when applying ToList/ToArray
if (method.IsGenericMethod
&& (method.GetGenericMethodDefinition() == EnumerableMethods.ToList
|| method.GetGenericMethodDefinition() == EnumerableMethods.ToArray))
{
return methodCallExpression.Update(
null, new[] { UnwrapCollectionMaterialization(Visit(methodCallExpression.Arguments[0])) });
}
return ProcessUnknownMethod(methodCallExpression);
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitUnary(UnaryExpression unaryExpression)
{
var operand = Visit(unaryExpression.Operand);
// Convert Array.Length to Count()
if (unaryExpression.Operand.Type.IsArray
&& unaryExpression.NodeType == ExpressionType.ArrayLength)
{
var innerQueryable = UnwrapCollectionMaterialization(operand);
// Only if inner is queryable as array properties could also have Length access
if (innerQueryable.Type.TryGetElementType(typeof(IQueryable<>)) is Type elementType)
{
return Visit(Expression.Call(QueryableMethods.CountWithoutPredicate.MakeGenericMethod(elementType), innerQueryable));
}
}
return unaryExpression.Update(operand);
}
private Expression ProcessAllAnyCountLongCount(
NavigationExpansionExpression source,
MethodInfo genericMethod,
LambdaExpression? predicate)
{
if (predicate != null)
{
predicate = ProcessLambdaExpression(source, predicate);
return Expression.Call(
genericMethod.MakeGenericMethod(source.SourceElementType), source.Source, Expression.Quote(predicate));
}
return Expression.Call(genericMethod.MakeGenericMethod(source.SourceElementType), source.Source);
}
private Expression ProcessAverageMaxMinSum(NavigationExpansionExpression source, MethodInfo method, LambdaExpression? selector)
{
if (selector != null)
{
source = ProcessSelect(source, selector);
source = (NavigationExpansionExpression)_pendingSelectorExpandingExpressionVisitor.Visit(source);
var selectorLambda = GenerateLambda(source.PendingSelector, source.CurrentParameter);
method = method.GetGenericArguments().Length == 2
? method.MakeGenericMethod(source.SourceElementType, selectorLambda.ReturnType)
: method.MakeGenericMethod(source.SourceElementType);
return Expression.Call(method, source.Source, selectorLambda);
}
source = (NavigationExpansionExpression)_pendingSelectorExpandingExpressionVisitor.Visit(source);
var queryable = Reduce(source);
if (method.GetGenericArguments().Length == 1)
{
// Min/Max without selector has 1 generic parameters
method = method.MakeGenericMethod(queryable.Type.GetSequenceType());
}
return Expression.Call(method, queryable);
}
private NavigationExpansionExpression ProcessCastOfType(
NavigationExpansionExpression source,
MethodInfo genericMethod,
Type castType)
{
if (castType.IsAssignableFrom(source.PendingSelector.Type)
|| castType == typeof(object))
{
// Casting to base/implementing interface is redundant
return source;
}
source = (NavigationExpansionExpression)_pendingSelectorExpandingExpressionVisitor.Visit(source);
var newStructure = SnapshotExpression(source.PendingSelector);
var queryable = Reduce(source);
var result = Expression.Call(genericMethod.MakeGenericMethod(castType), queryable);
if (newStructure is EntityReference entityReference
&& entityReference.EntityType.GetAllBaseTypes().Concat(entityReference.EntityType.GetDerivedTypesInclusive())
.FirstOrDefault(et => et.ClrType == castType) is IEntityType castEntityType)
{
var newEntityReference = new EntityReference(castEntityType, entityReference.EntityQueryRootExpression);
if (entityReference.IsOptional)
{
newEntityReference.MarkAsOptional();
}
newEntityReference.IncludePaths.Merge(entityReference.IncludePaths);
// Prune includes for sibling types
var siblingNavigations = newEntityReference.IncludePaths.Keys
.Where(
n => !castEntityType.IsAssignableFrom(n.DeclaringEntityType)
&& !n.DeclaringEntityType.IsAssignableFrom(castEntityType));
foreach (var navigation in siblingNavigations)
{
newEntityReference.IncludePaths.Remove(navigation);
}
newStructure = newEntityReference;
}
else
{
newStructure = Expression.Default(castType);
}
var navigationTree = new NavigationTreeExpression(newStructure);
var parameterName = GetParameterName("e");
return new NavigationExpansionExpression(result, navigationTree, navigationTree, parameterName);
}
private Expression ProcessContains(NavigationExpansionExpression source, Expression item)
{
source = (NavigationExpansionExpression)_pendingSelectorExpandingExpressionVisitor.Visit(source);
var queryable = Reduce(source);
item = Visit(item);
return Expression.Call(QueryableMethods.Contains.MakeGenericMethod(queryable.Type.GetSequenceType()), queryable, item);
}
private NavigationExpansionExpression ProcessDefaultIfEmpty(NavigationExpansionExpression source)
{
source.UpdateSource(
Expression.Call(
QueryableMethods.DefaultIfEmptyWithoutArgument.MakeGenericMethod(source.SourceElementType),
source.Source));
var pendingSelector = source.PendingSelector;
_entityReferenceOptionalMarkingExpressionVisitor.Visit(pendingSelector);
if (!pendingSelector.Type.IsNullableType())
{
pendingSelector = Expression.Coalesce(
Expression.Convert(pendingSelector, pendingSelector.Type.MakeNullable()),
pendingSelector.Type.GetDefaultValueConstant());
}
source.ApplySelector(pendingSelector);
return source;
}
private NavigationExpansionExpression ProcessDistinct(NavigationExpansionExpression source, MethodInfo genericMethod)
{
source = (NavigationExpansionExpression)_pendingSelectorExpandingExpressionVisitor.Visit(source);
var newStructure = SnapshotExpression(source.PendingSelector);
var queryable = Reduce(source);
var result = Expression.Call(genericMethod.MakeGenericMethod(queryable.Type.GetSequenceType()), queryable);
var navigationTree = new NavigationTreeExpression(newStructure);
var parameterName = GetParameterName("e");
return new NavigationExpansionExpression(result, navigationTree, navigationTree, parameterName);
}
private NavigationExpansionExpression ProcessSkipTake(
NavigationExpansionExpression source,
MethodInfo genericMethod,
Expression count)
{
count = Visit(count);
source.UpdateSource(Expression.Call(genericMethod.MakeGenericMethod(source.SourceElementType), source.Source, count));
return source;
}
private NavigationExpansionExpression ProcessFirstSingleLastOrDefault(
NavigationExpansionExpression source,
MethodInfo genericMethod,
LambdaExpression? predicate,
Type returnType)