-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathCosmosProjectionBindingExpressionVisitor.cs
More file actions
815 lines (686 loc) · 37.1 KB
/
CosmosProjectionBindingExpressionVisitor.cs
File metadata and controls
815 lines (686 loc) · 37.1 KB
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Diagnostics.CodeAnalysis;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Cosmos.Internal;
using Microsoft.EntityFrameworkCore.Cosmos.Metadata.Internal;
using Microsoft.EntityFrameworkCore.Cosmos.Storage.Internal;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Query.Internal;
namespace Microsoft.EntityFrameworkCore.Cosmos.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 class CosmosProjectionBindingExpressionVisitor : ExpressionVisitor
{
private static readonly MethodInfo GetParameterValueMethodInfo
= typeof(CosmosProjectionBindingExpressionVisitor)
.GetTypeInfo().GetDeclaredMethod(nameof(GetParameterValue))!;
private readonly CosmosQueryableMethodTranslatingExpressionVisitor _queryableMethodTranslatingExpressionVisitor;
private readonly CosmosSqlTranslatingExpressionVisitor _sqlTranslator;
private readonly ITypeMappingSource _typeMappingSource;
private readonly IModel _model;
private SelectExpression _selectExpression;
private bool _clientEval;
private readonly Dictionary<ProjectionMember, Expression> _projectionMapping = new();
private readonly Stack<ProjectionMember> _projectionMembers = new();
private readonly Dictionary<ParameterExpression, CollectionShaperExpression> _collectionShaperMapping = new();
private readonly Stack<INavigation> _includedNavigations = 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 CosmosProjectionBindingExpressionVisitor(
IModel model,
CosmosQueryableMethodTranslatingExpressionVisitor queryableMethodTranslatingExpressionVisitor,
CosmosSqlTranslatingExpressionVisitor sqlTranslator,
ITypeMappingSource typeMappingSource)
{
_model = model;
_queryableMethodTranslatingExpressionVisitor = queryableMethodTranslatingExpressionVisitor;
_sqlTranslator = sqlTranslator;
_typeMappingSource = typeMappingSource;
_selectExpression = 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 Translate(SelectExpression selectExpression, Expression expression)
{
_selectExpression = selectExpression;
_clientEval = false;
_projectionMembers.Push(new ProjectionMember());
var result = Visit(expression);
if (result == QueryCompilationContext.NotTranslatedExpression)
{
_clientEval = true;
result = Visit(expression);
_projectionMapping.Clear();
}
_selectExpression.ReplaceProjectionMapping(_projectionMapping);
_selectExpression = null!;
_projectionMembers.Clear();
_projectionMapping.Clear();
result = MatchTypes(result, expression.Type);
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>
[return: NotNullIfNotNull(nameof(expression))]
public override Expression? Visit(Expression? expression)
{
if (expression == null)
{
return null;
}
if (expression is NewExpression or MemberInitExpression or StructuralTypeShaperExpression)
{
return base.Visit(expression);
}
if (_clientEval)
{
switch (expression)
{
case ConstantExpression:
return expression;
case QueryParameterExpression queryParameter:
return Expression.Call(
GetParameterValueMethodInfo.MakeGenericMethod(queryParameter.Type),
QueryCompilationContext.QueryContextParameter,
Expression.Constant(queryParameter.Name));
case ParameterExpression parameterExpression:
return _collectionShaperMapping.ContainsKey(parameterExpression)
? parameterExpression
: throw new InvalidOperationException(CoreStrings.TranslationFailed(parameterExpression.Print()));
case MaterializeCollectionNavigationExpression:
return base.Visit(expression);
}
var translation = _sqlTranslator.Translate(expression);
if (translation == null)
{
return base.Visit(expression);
}
return new ProjectionBindingExpression(
_selectExpression, _selectExpression.AddToProjection(translation), translation.Type);
}
else
{
var translation = _sqlTranslator.Translate(expression);
if (translation == null)
{
return QueryCompilationContext.NotTranslatedExpression;
}
_projectionMapping[_projectionMembers.Peek()] = translation;
return new ProjectionBindingExpression(_selectExpression, _projectionMembers.Peek(), translation.Type);
}
}
/// <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 VisitBinary(BinaryExpression binaryExpression)
{
var left = MatchTypes(Visit(binaryExpression.Left), binaryExpression.Left.Type);
var right = MatchTypes(Visit(binaryExpression.Right), binaryExpression.Right.Type);
return binaryExpression.Update(left, VisitAndConvert(binaryExpression.Conversion, "VisitBinary"), right);
}
/// <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 VisitConditional(ConditionalExpression conditionalExpression)
{
var test = Visit(conditionalExpression.Test);
var ifTrue = Visit(conditionalExpression.IfTrue);
var ifFalse = Visit(conditionalExpression.IfFalse);
if (test.Type == typeof(bool?))
{
test = Expression.Equal(test, Expression.Constant(true, typeof(bool?)));
}
ifTrue = MatchTypes(ifTrue, conditionalExpression.IfTrue.Type);
ifFalse = MatchTypes(ifFalse, conditionalExpression.IfFalse.Type);
return conditionalExpression.Update(test, ifTrue, ifFalse);
}
/// <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 StructuralTypeShaperExpression entityShaperExpression:
{
var projectionBindingExpression = (ProjectionBindingExpression)entityShaperExpression.ValueBufferExpression;
VerifySelectExpression(projectionBindingExpression);
if (projectionBindingExpression.ProjectionMember is null)
{
return QueryCompilationContext.NotTranslatedExpression;
}
var projection = _selectExpression.GetMappedProjection(projectionBindingExpression.ProjectionMember);
if (_clientEval)
{
var entityProjection = (EntityProjectionExpression)projection;
return entityShaperExpression.Update(
new ProjectionBindingExpression(
_selectExpression, _selectExpression.AddToProjection(entityProjection), typeof(ValueBuffer)));
}
_projectionMapping[_projectionMembers.Peek()] = projection;
return entityShaperExpression.Update(
new ProjectionBindingExpression(_selectExpression, _projectionMembers.Peek(), typeof(ValueBuffer)));
}
case MaterializeCollectionNavigationExpression materializeCollectionNavigationExpression:
return materializeCollectionNavigationExpression.Navigation is INavigation embeddableNavigation
&& embeddableNavigation.IsEmbedded()
? base.Visit(materializeCollectionNavigationExpression.Subquery)
: base.VisitExtension(materializeCollectionNavigationExpression);
case IncludeExpression includeExpression:
if (!_clientEval)
{
return QueryCompilationContext.NotTranslatedExpression;
}
if (includeExpression.Navigation is not INavigation includableNavigation || !includableNavigation.IsEmbedded())
{
throw new InvalidOperationException(
CosmosStrings.NonEmbeddedIncludeNotSupported(includeExpression.Navigation));
}
_includedNavigations.Push(includableNavigation);
var newIncludeExpression = base.VisitExtension(includeExpression);
_includedNavigations.Pop();
return newIncludeExpression;
default:
throw new InvalidOperationException(CoreStrings.TranslationFailed(extensionExpression.Print()));
}
}
/// <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 ElementInit VisitElementInit(ElementInit elementInit)
=> elementInit.Update(elementInit.Arguments.Select(e => MatchTypes(Visit(e), e.Type)));
/// <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)
{
if (!_clientEval)
{
return QueryCompilationContext.NotTranslatedExpression;
}
var innerExpression = Visit(memberExpression.Expression);
StructuralTypeShaperExpression? shaperExpression;
switch (innerExpression)
{
case StructuralTypeShaperExpression shaper:
shaperExpression = shaper;
break;
case UnaryExpression unaryExpression:
shaperExpression = unaryExpression.Operand as StructuralTypeShaperExpression;
if (shaperExpression == null
|| unaryExpression.NodeType != ExpressionType.Convert)
{
return NullSafeUpdate(innerExpression);
}
break;
default:
return NullSafeUpdate(innerExpression);
}
var innerEntityProjection = shaperExpression.ValueBufferExpression switch
{
ProjectionBindingExpression innerProjectionBindingExpression
=> (EntityProjectionExpression)_selectExpression.Projection[innerProjectionBindingExpression.Index!.Value].Expression,
// Unwrap EntityProjectionExpression when the root entity is not projected
UnaryExpression unaryExpression
=> (EntityProjectionExpression)((UnaryExpression)unaryExpression.Operand).Operand,
_ => throw new InvalidOperationException(CoreStrings.TranslationFailed(memberExpression.Print()))
};
var navigationProjection = innerEntityProjection.BindMember(
memberExpression.Member, innerExpression.Type, clientEval: true, out var propertyBase);
if (propertyBase is not INavigation navigation
|| !navigation.IsEmbedded())
{
return NullSafeUpdate(innerExpression);
}
switch (navigationProjection)
{
case EntityProjectionExpression entityProjection:
return new StructuralTypeShaperExpression(
navigation.TargetEntityType,
Expression.Convert(Expression.Convert(entityProjection, typeof(object)), typeof(ValueBuffer)),
nullable: true);
case ObjectArrayAccessExpression objectArrayProjectionExpression:
{
var innerShaperExpression = new StructuralTypeShaperExpression(
navigation.TargetEntityType,
Expression.Convert(
Expression.Convert(objectArrayProjectionExpression.InnerProjection, typeof(object)), typeof(ValueBuffer)),
nullable: true);
return new CollectionShaperExpression(
objectArrayProjectionExpression,
innerShaperExpression,
navigation,
innerShaperExpression.StructuralType.ClrType);
}
default:
throw new InvalidOperationException(CoreStrings.TranslationFailed(memberExpression.Print()));
}
Expression NullSafeUpdate(Expression? innerExpression)
{
if (innerExpression is null)
{
return memberExpression.Update(innerExpression);
}
var expressionValue = Expression.Parameter(innerExpression.Type);
var assignment = Expression.Assign(expressionValue, innerExpression);
// Special case for when query is projecting 'nullable.Value' where 'nullable' is of type Nullable<T>
// In this case we return default(T) when 'nullable' is null
var member = memberExpression.Member;
if (innerExpression.Type.IsNullableType()
&& !memberExpression.Type.IsNullableType()
&& member is { Name: nameof(Nullable<>.Value), DeclaringType.IsGenericType: true }
&& member.DeclaringType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
// Use HasValue property instead of equality comparison
// to avoid issues with value types that don't define the == operator
var nullCheck = Expression.Not(
Expression.Property(expressionValue, nameof(Nullable<>.HasValue)));
var conditionalExpression = Expression.Condition(
nullCheck,
Expression.Default(memberExpression.Type),
Expression.Property(expressionValue, nameof(Nullable<>.Value)));
return Expression.Block(
[expressionValue],
assignment,
conditionalExpression);
}
Expression updatedMemberExpression = memberExpression.Update(MatchTypes(expressionValue, memberExpression.Expression!.Type));
if (innerExpression.Type.IsNullableType())
{
var nullableReturnType = memberExpression.Type.MakeNullable();
if (!updatedMemberExpression.Type.IsNullableType())
{
updatedMemberExpression = Expression.Convert(updatedMemberExpression, nullableReturnType);
}
Expression nullCheck;
if (innerExpression.Type.IsNullableValueType())
{
// For Nullable<T>, use HasValue property instead of equality comparison
// to avoid issues with value types that don't define the == operator
nullCheck = Expression.Not(
Expression.Property(expressionValue, nameof(Nullable<>.HasValue)));
}
else
{
nullCheck = Expression.Equal(expressionValue, Expression.Default(innerExpression.Type));
}
updatedMemberExpression = Expression.Condition(
nullCheck,
Expression.Default(nullableReturnType),
updatedMemberExpression);
}
return Expression.Block(
[expressionValue],
assignment,
updatedMemberExpression);
}
}
/// <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 MemberAssignment VisitMemberAssignment(MemberAssignment memberAssignment)
{
var expression = memberAssignment.Expression;
Expression visitedExpression;
if (_clientEval)
{
visitedExpression = Visit(memberAssignment.Expression);
}
else
{
var projectionMember = _projectionMembers.Peek().Append(memberAssignment.Member);
_projectionMembers.Push(projectionMember);
visitedExpression = Visit(memberAssignment.Expression);
if (visitedExpression == QueryCompilationContext.NotTranslatedExpression)
{
return memberAssignment.Update(Expression.Convert(visitedExpression, expression.Type));
}
_projectionMembers.Pop();
}
visitedExpression = MatchTypes(visitedExpression, expression.Type);
return memberAssignment.Update(visitedExpression);
}
/// <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 VisitMemberInit(MemberInitExpression memberInitExpression)
{
var newExpression = Visit(memberInitExpression.NewExpression);
if (newExpression == QueryCompilationContext.NotTranslatedExpression)
{
return QueryCompilationContext.NotTranslatedExpression;
}
var newBindings = new MemberBinding[memberInitExpression.Bindings.Count];
for (var i = 0; i < newBindings.Length; i++)
{
if (memberInitExpression.Bindings[i].BindingType != MemberBindingType.Assignment)
{
return QueryCompilationContext.NotTranslatedExpression;
}
newBindings[i] = VisitMemberBinding(memberInitExpression.Bindings[i]);
if (newBindings[i] is MemberAssignment { Expression: UnaryExpression { NodeType: ExpressionType.Convert } unaryExpression }
&& unaryExpression.Operand == QueryCompilationContext.NotTranslatedExpression)
{
return QueryCompilationContext.NotTranslatedExpression;
}
}
return memberInitExpression.Update((NewExpression)newExpression, newBindings);
}
/// <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)
{
if (methodCallExpression.TryGetEFPropertyArguments(out var source, out var memberName)
|| methodCallExpression.TryGetIndexerArguments(_model, out source, out memberName))
{
if (!_clientEval)
{
return QueryCompilationContext.NotTranslatedExpression;
}
var visitedSource = Visit(source);
StructuralTypeShaperExpression? shaperExpression;
switch (visitedSource)
{
case StructuralTypeShaperExpression s:
shaperExpression = s;
break;
case UnaryExpression { NodeType: ExpressionType.Convert, Operand: StructuralTypeShaperExpression s }:
shaperExpression = s;
break;
case ParameterExpression parameterExpression
when _collectionShaperMapping.TryGetValue(parameterExpression, out var collectionShaper):
shaperExpression = (StructuralTypeShaperExpression)collectionShaper.InnerShaper;
break;
default:
return QueryCompilationContext.NotTranslatedExpression;
}
var innerEntityProjection = shaperExpression.ValueBufferExpression switch
{
EntityProjectionExpression entityProjection
=> entityProjection,
ProjectionBindingExpression innerProjectionBindingExpression
=> (EntityProjectionExpression)_selectExpression.Projection[innerProjectionBindingExpression.Index!.Value].Expression,
UnaryExpression unaryExpression
=> (EntityProjectionExpression)((UnaryExpression)unaryExpression.Operand).Operand,
_ => throw new InvalidOperationException(CoreStrings.TranslationFailed(methodCallExpression.Print()))
};
Expression? navigationProjection;
var navigation = _includedNavigations.FirstOrDefault(n => n.Name == memberName);
if (navigation == null)
{
navigationProjection = innerEntityProjection.BindMember(
memberName, visitedSource.Type, clientEval: true, out var propertyBase);
if (propertyBase is not INavigation projectedNavigation || !projectedNavigation.IsEmbedded())
{
return QueryCompilationContext.NotTranslatedExpression;
}
navigation = projectedNavigation;
}
else
{
navigationProjection = innerEntityProjection.BindNavigation(navigation, clientEval: true);
}
switch (navigationProjection)
{
case StructuralTypeShaperExpression shaper when navigation.IsCollection:
var objectArrayAccessExpression = shaper.ValueBufferExpression as ObjectArrayAccessExpression;
Check.DebugAssert(objectArrayAccessExpression is not null, "Expected ObjectArrayAccessExpression");
var innerShaperExpression = new StructuralTypeShaperExpression(
navigation.TargetEntityType,
Expression.Convert(
Expression.Convert(objectArrayAccessExpression.InnerProjection, typeof(object)), typeof(ValueBuffer)),
nullable: true);
return new CollectionShaperExpression(
objectArrayAccessExpression,
innerShaperExpression,
navigation,
innerShaperExpression.StructuralType.ClrType);
case StructuralTypeShaperExpression shaper:
return new StructuralTypeShaperExpression(
shaper.StructuralType,
Expression.Convert(Expression.Convert(shaper.ValueBufferExpression, typeof(object)), typeof(ValueBuffer)),
shaper.IsNullable);
default:
throw new InvalidOperationException(CoreStrings.TranslationFailed(methodCallExpression.Print()));
}
}
if (_clientEval)
{
var method = methodCallExpression.Method;
if (method.DeclaringType == typeof(Queryable))
{
var genericMethod = method.IsGenericMethod ? method.GetGenericMethodDefinition() : null;
var visitedSource = Visit(methodCallExpression.Arguments[0]);
switch (method.Name)
{
case nameof(Queryable.AsQueryable)
when genericMethod == QueryableMethods.AsQueryable:
// Unwrap AsQueryable
return visitedSource;
case nameof(Queryable.Select)
when genericMethod == QueryableMethods.Select:
if (visitedSource is not CollectionShaperExpression shaper)
{
return QueryCompilationContext.NotTranslatedExpression;
}
var lambda = methodCallExpression.Arguments[1].UnwrapLambdaFromQuote();
_collectionShaperMapping.Add(lambda.Parameters.Single(), shaper);
lambda = Expression.Lambda(Visit(lambda.Body), lambda.Parameters);
return Expression.Call(
EnumerableMethods.Select.MakeGenericMethod(method.GetGenericArguments()),
shaper,
lambda);
}
}
else if (method is { Name: nameof(Enumerable.ToList), IsGenericMethod: true }
&& method.DeclaringType == typeof(Enumerable)
&& methodCallExpression.Arguments is [var argument]
&& argument.Type.TryGetElementType(typeof(IQueryable<>)) != null)
{
if (_queryableMethodTranslatingExpressionVisitor.TranslateSubquery(argument) is not { } subquery
|| !subquery.TryConvertToArray(_typeMappingSource, out var array))
{
throw new InvalidOperationException(CoreStrings.TranslationFailed(methodCallExpression.Print()));
}
// If ToList() was composed over a subquery with operators, the result here is an ArrayExpression (ARRAY(SELECT ...)), whose
// CLR Type is IEnumerable<T>. This can be directly used in the resulting ProjectingBindingExpression - the shaper will
// simply read the JSON results out successfully.
// But if ToList() is composed directly over an array property, that property could have type e.g. T[], which will be read
// in the shaper, and then the cast from T[] to List<T> will fail. As a result, wrap the array in an additional
// "reprojection" subquery, effectively to change the CLR type.
if (array is SqlExpression scalarArray
&& !(array.Type.IsGenericType && array.Type.GetGenericTypeDefinition() == typeof(IEnumerable<>)))
{
Check.DebugAssert(
array is not ScalarArrayExpression and not ObjectArrayExpression, "ArrayExpression should be IEnumerable");
if (scalarArray is not { TypeMapping.ElementTypeMapping: CosmosTypeMapping elementTypeMapping })
{
throw new UnreachableException("Scalar array with no element type mapping");
}
// TODO: Proper alias management (#33894).
var arrayReprojectionSubquery = SelectExpression.CreateForCollection(
array, "i", new ScalarReferenceExpression("i", elementTypeMapping.ClrType, elementTypeMapping));
arrayReprojectionSubquery.ApplyProjection();
array = new ScalarArrayExpression(
arrayReprojectionSubquery,
methodCallExpression.Type, // List<>
_typeMappingSource.FindMapping(methodCallExpression.Type, _model, elementTypeMapping));
}
return new ProjectionBindingExpression(
_selectExpression,
_selectExpression.AddToProjection(array),
methodCallExpression.Type);
}
}
var @object = Visit(methodCallExpression.Object);
var arguments = new Expression[methodCallExpression.Arguments.Count];
for (var i = 0; i < methodCallExpression.Arguments.Count; i++)
{
var argument = methodCallExpression.Arguments[i];
arguments[i] = MatchTypes(Visit(argument), argument.Type);
}
Expression updatedMethodCallExpression = methodCallExpression.Update(
@object != null ? MatchTypes(@object, methodCallExpression.Object!.Type) : @object,
arguments);
if (@object?.Type.IsNullableType() == true
&& !methodCallExpression.Object!.Type.IsNullableType())
{
var nullableReturnType = methodCallExpression.Type.MakeNullable();
if (!methodCallExpression.Type.IsNullableType())
{
updatedMethodCallExpression = Expression.Convert(updatedMethodCallExpression, nullableReturnType);
}
Expression nullCheck;
if (@object.Type.IsNullableValueType())
{
// For Nullable<T>, use HasValue property instead of equality comparison
// to avoid issues with value types that don't define the == operator
nullCheck = Expression.Not(
Expression.Property(@object, nameof(Nullable<>.HasValue)));
}
else
{
nullCheck = Expression.Equal(@object, Expression.Constant(null, @object.Type));
}
return Expression.Condition(
nullCheck,
Expression.Constant(null, nullableReturnType),
updatedMethodCallExpression);
}
return updatedMethodCallExpression;
}
/// <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 VisitNew(NewExpression newExpression)
{
if (newExpression.Arguments.Count == 0)
{
return newExpression;
}
if (!_clientEval
&& newExpression.Members == null)
{
return QueryCompilationContext.NotTranslatedExpression;
}
var newArguments = new Expression[newExpression.Arguments.Count];
for (var i = 0; i < newArguments.Length; i++)
{
var argument = newExpression.Arguments[i];
Expression visitedArgument;
if (_clientEval)
{
visitedArgument = Visit(argument);
}
else
{
var projectionMember = _projectionMembers.Peek().Append(newExpression.Members![i]);
_projectionMembers.Push(projectionMember);
visitedArgument = Visit(argument);
if (visitedArgument == QueryCompilationContext.NotTranslatedExpression)
{
return QueryCompilationContext.NotTranslatedExpression;
}
_projectionMembers.Pop();
}
newArguments[i] = MatchTypes(visitedArgument, argument.Type);
}
return newExpression.Update(newArguments);
}
/// <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 VisitNewArray(NewArrayExpression newArrayExpression)
=> newArrayExpression.Update(newArrayExpression.Expressions.Select(e => MatchTypes(Visit(e), e.Type)));
/// <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);
return (unaryExpression.NodeType == ExpressionType.Convert
|| unaryExpression.NodeType == ExpressionType.ConvertChecked)
&& unaryExpression.Type == operand.Type
? operand
: unaryExpression.Update(MatchTypes(operand, unaryExpression.Operand.Type));
}
// TODO: Debugging
private void VerifySelectExpression(ProjectionBindingExpression projectionBindingExpression)
{
if (projectionBindingExpression.QueryExpression != _selectExpression)
{
throw new InvalidOperationException(CoreStrings.TranslationFailed(projectionBindingExpression.Print()));
}
}
private static Expression MatchTypes(Expression expression, Type targetType)
{
if (targetType != expression.Type
&& targetType.TryGetSequenceType() == null)
{
if (expression is ProjectionBindingExpression projectionBindingExpression)
{
return projectionBindingExpression.UpdateType(targetType);
}
if (targetType.MakeNullable() == expression.Type)
{
expression = Expression.Convert(expression, targetType);
}
}
return expression;
}
[UsedImplicitly]
private static T GetParameterValue<T>(QueryContext queryContext, string parameterName)
=> (T)queryContext.Parameters[parameterName]!;
}