-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathRelationalProjectionBindingExpressionVisitor.cs
More file actions
810 lines (692 loc) · 39.1 KB
/
RelationalProjectionBindingExpressionVisitor.cs
File metadata and controls
810 lines (692 loc) · 39.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
// 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.Query.SqlExpressions;
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 class RelationalProjectionBindingExpressionVisitor : ExpressionVisitor
{
private static readonly MethodInfo GetParameterValueMethodInfo
= typeof(RelationalProjectionBindingExpressionVisitor).GetTypeInfo().GetDeclaredMethod(nameof(GetParameterValue))!;
private readonly RelationalQueryableMethodTranslatingExpressionVisitor _queryableMethodTranslatingExpressionVisitor;
private readonly RelationalSqlTranslatingExpressionVisitor _sqlTranslator;
private readonly IncludeFindingExpressionVisitor _includeFindingExpressionVisitor;
private SelectExpression _selectExpression;
private bool _indexBasedBinding;
private Dictionary<StructuralTypeProjectionExpression, ProjectionBindingExpression>? _projectionBindingCache;
private List<Expression>? _clientProjections;
private readonly Dictionary<ProjectionMember, Expression> _projectionMapping = new();
private readonly Stack<ProjectionMember> _projectionMembers = 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 RelationalProjectionBindingExpressionVisitor(
RelationalQueryableMethodTranslatingExpressionVisitor queryableMethodTranslatingExpressionVisitor,
RelationalSqlTranslatingExpressionVisitor sqlTranslatingExpressionVisitor)
{
_queryableMethodTranslatingExpressionVisitor = queryableMethodTranslatingExpressionVisitor;
_sqlTranslator = sqlTranslatingExpressionVisitor;
_includeFindingExpressionVisitor = new IncludeFindingExpressionVisitor();
_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;
_indexBasedBinding = false;
_projectionMembers.Push(new ProjectionMember());
var result = Visit(expression);
if (result == QueryCompilationContext.NotTranslatedExpression)
{
_indexBasedBinding = true;
_projectionBindingCache = new Dictionary<StructuralTypeProjectionExpression, ProjectionBindingExpression>();
_projectionMapping.Clear();
_clientProjections = [];
result = Visit(expression);
_selectExpression.ReplaceProjection(_clientProjections);
_clientProjections.Clear();
}
else
{
_selectExpression.ReplaceProjection(_projectionMapping);
_projectionMapping.Clear();
}
_selectExpression = null!;
_projectionMembers.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)
{
switch (expression)
{
case NewExpression or MemberInitExpression or StructuralTypeShaperExpression or IncludeExpression:
return base.Visit(expression);
case null:
return null;
case not null when _indexBasedBinding:
{
switch (expression)
{
case ConstantExpression:
return expression;
case QueryParameterExpression queryParameterExpression:
return Expression.Call(
GetParameterValueMethodInfo.MakeGenericMethod(queryParameterExpression.Type),
QueryCompilationContext.QueryContextParameter,
Expression.Constant(queryParameterExpression.Name));
case ParameterExpression parameterExpression:
throw new InvalidOperationException(CoreStrings.TranslationFailed(parameterExpression.Print()));
case SqlExpression mappedSqlExpression:
return AddClientProjection(mappedSqlExpression, mappedSqlExpression.Type);
case MaterializeCollectionNavigationExpression materializeCollectionNavigationExpression:
if (materializeCollectionNavigationExpression.Navigation.TargetEntityType.IsMappedToJson())
{
var subquery = materializeCollectionNavigationExpression.Subquery;
if (subquery is MethodCallExpression { Method.IsGenericMethod: true } methodCallSubquery)
{
// strip .Select(x => x) and .AsQueryable() from the JsonCollectionResultExpression
if (methodCallSubquery.Method.GetGenericMethodDefinition() == QueryableMethods.Select
&& methodCallSubquery.Arguments[0] is MethodCallExpression selectSourceMethod)
{
methodCallSubquery = selectSourceMethod;
}
if (methodCallSubquery.Method.IsGenericMethod
&& methodCallSubquery.Method.GetGenericMethodDefinition() == QueryableMethods.AsQueryable)
{
subquery = methodCallSubquery.Arguments[0];
}
}
if (subquery is JsonQueryExpression jsonQueryExpression)
{
Check.DebugAssert(
jsonQueryExpression.IsCollection,
"JsonQueryExpression inside materialize collection should always be a collection.");
_clientProjections!.Add(jsonQueryExpression);
return new CollectionResultExpression(
new ProjectionBindingExpression(
_selectExpression, _clientProjections!.Count - 1, jsonQueryExpression.Type),
materializeCollectionNavigationExpression.Navigation,
materializeCollectionNavigationExpression.Navigation.ClrType.GetSequenceType());
}
}
_clientProjections!.Add(
_queryableMethodTranslatingExpressionVisitor.TranslateSubquery(
materializeCollectionNavigationExpression.Subquery)!);
return new CollectionResultExpression(
// expression.Type will be CLR type of the navigation here so that is fine.
new ProjectionBindingExpression(_selectExpression, _clientProjections.Count - 1, expression.Type),
materializeCollectionNavigationExpression.Navigation,
materializeCollectionNavigationExpression.Navigation.ClrType.GetSequenceType());
}
switch (_sqlTranslator.TranslateProjection(expression))
{
case SqlExpression mappedSqlExpression:
var isNullable = mappedSqlExpression switch
{
ColumnExpression c => c.IsNullable,
SqlFunctionExpression f => f.IsNullable,
AtTimeZoneExpression a => a.IsNullable,
_ => true
};
var shouldBeNullable = isNullable
&& expression.Type.IsValueType
&& !expression.Type.IsNullableType()
&& expression.Type != typeof(bool);
return AddClientProjection(
mappedSqlExpression,
shouldBeNullable ? expression.Type.MakeNullable() : expression.Type);
// This handles the case of a complex type being projected out of a Select.
case RelationalStructuralTypeShaperExpression { StructuralType: IComplexType } shaper:
return base.Visit(shaper);
case CollectionResultExpression collectionResult:
return base.Visit(collectionResult);
}
if (expression is MethodCallExpression methodCallExpression)
{
if (methodCallExpression is
{
Method.IsGenericMethod: true,
Method.Name: nameof(Enumerable.ToList),
Method: var method,
Arguments: [var argument]
}
&& method.DeclaringType == typeof(Enumerable)
&& argument.Type.TryGetElementType(typeof(IQueryable<>)) != null)
{
if (_queryableMethodTranslatingExpressionVisitor.TranslateSubquery(argument) is { } subquery)
{
_clientProjections!.Add(subquery);
// expression.Type here will be List<T>
return new CollectionResultExpression(
new ProjectionBindingExpression(_selectExpression, _clientProjections.Count - 1, expression.Type),
structuralProperty: null,
methodCallExpression.Method.GetGenericArguments()[0]);
}
}
else
{
var subquery = _queryableMethodTranslatingExpressionVisitor.TranslateSubquery(methodCallExpression);
if (subquery != null)
{
_clientProjections!.Add(subquery);
var type = expression.Type;
if (type.IsGenericType
&& type.GetGenericTypeDefinition() == typeof(IQueryable<>))
{
type = typeof(List<>).MakeGenericType(type.GetSequenceType());
}
var projectionBindingExpression = new ProjectionBindingExpression(
_selectExpression, _clientProjections.Count - 1, type);
return subquery.ResultCardinality == ResultCardinality.Enumerable
? new CollectionResultExpression(
projectionBindingExpression, structuralProperty: null, subquery.ShaperExpression.Type)
: projectionBindingExpression;
}
}
}
return base.Visit(expression);
}
default:
{
switch (_sqlTranslator.TranslateProjection(expression))
{
case SqlExpression mappedSqlExpression:
_projectionMapping[_projectionMembers.Peek()] = mappedSqlExpression;
var isNullable = mappedSqlExpression switch
{
ColumnExpression c => c.IsNullable,
SqlFunctionExpression f => f.IsNullable,
AtTimeZoneExpression a => a.IsNullable,
_ => true
};
var shouldBeNullable = isNullable
&& expression.Type.IsValueType
&& !expression.Type.IsNullableType()
&& expression.Type != typeof(bool);
return new ProjectionBindingExpression(
_selectExpression, _projectionMembers.Peek(), shouldBeNullable ? expression.Type.MakeNullable() : expression.Type);
// This handles the case of a complex type being projected out of a Select.
// Note that an entity type being projected is (currently) handled differently
case RelationalStructuralTypeShaperExpression { StructuralType: IComplexType } shaper:
return base.Visit(shaper);
case CollectionResultExpression collectionResult:
return base.Visit(collectionResult);
case null or RelationalStructuralTypeShaperExpression { StructuralType: IEntityType }:
return QueryCompilationContext.NotTranslatedExpression;
default:
throw new UnreachableException();
}
}
}
}
/// <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 shaper:
{
// TODO: Make this easier to understand some day.
StructuralTypeProjectionExpression projection;
if (shaper.ValueBufferExpression is JsonQueryExpression jsonQueryExpression)
{
if (_indexBasedBinding)
{
_clientProjections!.Add(jsonQueryExpression);
var jsonProjectionBinding = new ProjectionBindingExpression(
_selectExpression, _clientProjections.Count - 1, typeof(ValueBuffer));
return shaper.Update(jsonProjectionBinding);
}
_projectionMapping[_projectionMembers.Peek()] = jsonQueryExpression;
#pragma warning disable EF1001
return shaper.Update(
new ProjectionBindingExpression(_selectExpression, _projectionMembers.Peek(), typeof(ValueBuffer)))
// This is to handle have correct type for the shaper expression. It is later fixed in MatchTypes.
// This mirrors for structural types what we do for scalars.
.MakeClrTypeNullable();
#pragma warning restore EF1001
}
if (shaper.ValueBufferExpression is ProjectionBindingExpression projectionBindingExpression)
{
if (projectionBindingExpression.ProjectionMember == null
&& !_indexBasedBinding)
{
// If projectionBinding is not mapped via projection member then it is bound via index
// Hence we need to switch to index based binding too.
return QueryCompilationContext.NotTranslatedExpression;
}
var projection2 = ((SelectExpression)projectionBindingExpression.QueryExpression)
.GetProjection(projectionBindingExpression);
if (projection2 is JsonQueryExpression jsonQuery)
{
if (_indexBasedBinding)
{
var projectionBinding = AddClientProjection(jsonQuery, typeof(ValueBuffer));
#pragma warning disable EF1001
return shaper.Update(projectionBinding)
// This is to handle have correct type for the shaper expression. It is later fixed in MatchTypes.
// This mirrors for structural types what we do for scalars.
.MakeClrTypeNullable();
#pragma warning restore EF1001
}
_projectionMapping[_projectionMembers.Peek()] = jsonQuery;
#pragma warning disable EF1001
return shaper.Update(
new ProjectionBindingExpression(_selectExpression, _projectionMembers.Peek(), typeof(ValueBuffer)))
// This is to handle have correct type for the shaper expression. It is later fixed in MatchTypes.
// This mirrors for structural types what we do for scalars.
.MakeClrTypeNullable();
#pragma warning restore EF1001
}
projection = (StructuralTypeProjectionExpression)projection2;
}
else
{
projection = (StructuralTypeProjectionExpression)shaper.ValueBufferExpression;
}
if (_indexBasedBinding)
{
if (!_projectionBindingCache!.TryGetValue(projection, out var entityProjectionBinding))
{
entityProjectionBinding = AddClientProjection(projection, typeof(ValueBuffer));
_projectionBindingCache[projection] = entityProjectionBinding;
}
#pragma warning disable EF1001
return shaper.Update(entityProjectionBinding)
// This is to handle have correct type for the shaper expression. It is later fixed in MatchTypes.
// This mirrors for structural types what we do for scalars.
.MakeClrTypeNullable();
#pragma warning restore EF1001
}
_projectionMapping[_projectionMembers.Peek()] = projection;
#pragma warning disable EF1001
return shaper
.Update(new ProjectionBindingExpression(_selectExpression, _projectionMembers.Peek(), typeof(ValueBuffer)))
// This is to handle have correct type for the shaper expression. It is later fixed in MatchTypes.
// This mirrors for structural types what we do for scalars.
.MakeClrTypeNullable();
#pragma warning restore EF1001
}
case IncludeExpression includeExpression:
{
if (_indexBasedBinding)
{
// we prune nested json includes - we only need the first level of include so that we know the json column
// and the json entity that is the start of the include chain - the rest will be added in the shaper phase
return includeExpression.Navigation.DeclaringEntityType.IsMappedToJson()
? Visit(includeExpression.EntityExpression)
: base.VisitExtension(extensionExpression);
}
return QueryCompilationContext.NotTranslatedExpression;
}
case CollectionResultExpression
{
QueryExpression: ProjectionBindingExpression projectionBindingExpression
} collectionResultExpression:
{
// TODO this should not be needed at some point, we shouldn't be revisiting same projection.
// This happens because we don't process result selector for Join/SelectMany directly.
if (_indexBasedBinding)
{
Check.DebugAssert(
ReferenceEquals(_selectExpression, projectionBindingExpression.QueryExpression),
"The projection should belong to same select expression.");
var mappedProjection = _selectExpression.GetProjection(projectionBindingExpression);
_clientProjections!.Add(mappedProjection);
return collectionResultExpression.Update(
new ProjectionBindingExpression(
_selectExpression, _clientProjections.Count - 1, collectionResultExpression.Type));
}
return QueryCompilationContext.NotTranslatedExpression;
}
case CollectionResultExpression { QueryExpression: JsonQueryExpression jsonQuery } collectionResult:
{
if (_indexBasedBinding)
{
_clientProjections!.Add(jsonQuery);
}
else
{
_projectionMapping[_projectionMembers.Peek()] = jsonQuery;
}
return collectionResult.Update(
new ProjectionBindingExpression(_selectExpression, _projectionMembers.Peek(), collectionResult.Type));
}
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)
{
var expression = Visit(memberExpression.Expression);
Expression updatedMemberExpression = memberExpression.Update(
expression != null ? MatchTypes(expression, memberExpression.Expression!.Type) : expression);
if (expression?.Type.IsNullableType() == true
&& !_includeFindingExpressionVisitor.ContainsInclude(expression))
{
var nullableReturnType = memberExpression.Type.MakeNullable();
if (!memberExpression.Type.IsNullableType())
{
updatedMemberExpression = Expression.Convert(updatedMemberExpression, nullableReturnType);
}
updatedMemberExpression = Expression.Condition(
Expression.Equal(expression, Expression.Default(expression.Type)),
Expression.Constant(null, nullableReturnType),
updatedMemberExpression);
}
return 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 (_indexBasedBinding)
{
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)
{
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 != null
&& !methodCallExpression.Object.Type.IsNullableType())
{
var nullableReturnType = methodCallExpression.Type.MakeNullable();
if (!methodCallExpression.Type.IsNullableType())
{
updatedMethodCallExpression = Expression.Convert(updatedMethodCallExpression, nullableReturnType);
}
return Expression.Condition(
Expression.Equal(@object, Expression.Default(@object.Type)),
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 (!_indexBasedBinding
&& 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 (_indexBasedBinding)
{
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);
if (unaryExpression.NodeType is ExpressionType.Convert or ExpressionType.ConvertChecked)
{
if (unaryExpression.Type == operand.Type)
{
return operand;
}
if (unaryExpression.Type.IsValueType
&& !unaryExpression.Type.IsNullableType()
&& operand.Type.IsNullableType()
&& operand.Type.UnwrapNullableType() == unaryExpression.Type)
{
return MatchTypes(operand, unaryExpression.Type);
}
}
return unaryExpression.Update(MatchTypes(operand, unaryExpression.Operand.Type));
}
[DebuggerStepThrough]
private static Expression MatchTypes(Expression expression, Type targetType)
{
if (targetType != expression.Type
&& targetType.TryGetElementType(typeof(IQueryable<>)) == null)
{
Check.DebugAssert(
targetType.MakeNullable() == expression.Type,
$"expression has type {expression.Type.Name}, but must be nullable over {targetType.Name}");
return expression switch
{
#pragma warning disable EF1001 // Internal EF Core API usage.
ProjectionBindingExpression projectionBindingExpression
=> (projectionBindingExpression.Type.IsNullableType() && !targetType.IsNullableType())
? Expression.Coalesce(projectionBindingExpression, Expression.Default(targetType))
: projectionBindingExpression.UpdateType(targetType),
#pragma warning restore EF1001 // Internal EF Core API usage.
_ => expression.Type.IsNullableType() && !targetType.IsNullableType()
? Expression.Coalesce(expression, Expression.Default(targetType))
: Expression.Convert(expression, targetType)
};
}
return expression;
}
private ProjectionBindingExpression AddClientProjection(Expression expression, Type type)
{
// [FIX 1] Guard against null expressions resulting from failed translation.
// This ensures we throw the InvalidOperationException the test expects.
if (expression is null)
{
throw new InvalidOperationException("Unable to translate the given expression.");
}
// [FIX 2] Lazy initialization: If _clientProjections is null, create it.
// This prevents the NullReferenceException when calling .FindIndex
if (_clientProjections is null)
{
_clientProjections = new List<Expression>();
}
var existingIndex = _clientProjections.FindIndex(e => e.Equals(expression));
if (existingIndex == -1)
{
_clientProjections.Add(expression);
existingIndex = _clientProjections.Count - 1;
}
return new ProjectionBindingExpression(_selectExpression, existingIndex, 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>
public static T GetParameterValue<T>(QueryContext queryContext, string parameterName)
#pragma warning restore IDE0052 // Remove unread private members
=> (T)queryContext.Parameters[parameterName]!;
private sealed class IncludeFindingExpressionVisitor : ExpressionVisitor
{
private bool _containsInclude;
public bool ContainsInclude(Expression expression)
{
_containsInclude = false;
Visit(expression);
return _containsInclude;
}
[return: NotNullIfNotNull(nameof(expression))]
public override Expression? Visit(Expression? expression)
=> _containsInclude ? expression : base.Visit(expression);
protected override Expression VisitExtension(Expression extensionExpression)
{
if (extensionExpression is IncludeExpression)
{
_containsInclude = true;
return extensionExpression;
}
return base.VisitExtension(extensionExpression);
}
}
}