-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
Copy pathModificationCommand.cs
1204 lines (1049 loc) · 49.9 KB
/
ModificationCommand.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.Collections;
using System.Data;
using System.Text;
using System.Text.Json;
using Microsoft.EntityFrameworkCore.ChangeTracking.Internal;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using IColumnMapping = Microsoft.EntityFrameworkCore.Metadata.IColumnMapping;
using ITableMapping = Microsoft.EntityFrameworkCore.Metadata.ITableMapping;
namespace Microsoft.EntityFrameworkCore.Update;
/// <summary>
/// <para>
/// Represents a conceptual command to the database to insert/update/delete a row.
/// </para>
/// <para>
/// This type is typically used by database providers; it is generally not used in application code.
/// </para>
/// </summary>
/// <remarks>
/// See <see href="https://aka.ms/efcore-docs-providers">Implementation of database providers and extensions</see>
/// for more information and examples.
/// </remarks>
public class ModificationCommand : IModificationCommand, INonTrackedModificationCommand
{
private readonly Func<string>? _generateParameterName;
private readonly bool _sensitiveLoggingEnabled;
private readonly bool _detailedErrorsEnabled;
private readonly IComparer<IUpdateEntry>? _comparer;
private readonly List<IUpdateEntry> _entries = [];
private List<IColumnModification>? _columnModifications;
private bool _mainEntryAdded;
private EntityState _entityState;
private readonly IDiagnosticsLogger<DbLoggerCategory.Update>? _logger;
/// <summary>
/// Initializes a new <see cref="ModificationCommand" /> instance.
/// </summary>
/// <param name="modificationCommandParameters">Creation parameters.</param>
public ModificationCommand(in ModificationCommandParameters modificationCommandParameters)
{
Table = modificationCommandParameters.Table;
TableName = modificationCommandParameters.TableName;
Schema = modificationCommandParameters.Schema;
StoreStoredProcedure = modificationCommandParameters.StoreStoredProcedure;
_generateParameterName = modificationCommandParameters.GenerateParameterName;
_sensitiveLoggingEnabled = modificationCommandParameters.SensitiveLoggingEnabled;
_detailedErrorsEnabled = modificationCommandParameters.DetailedErrorsEnabled;
_comparer = modificationCommandParameters.Comparer;
_logger = modificationCommandParameters.Logger;
EntityState = EntityState.Modified;
}
/// <summary>
/// Initializes a new <see cref="ModificationCommand" /> instance.
/// </summary>
/// <param name="modificationCommandParameters">Creation parameters.</param>
public ModificationCommand(in NonTrackedModificationCommandParameters modificationCommandParameters)
{
Table = modificationCommandParameters.Table;
TableName = modificationCommandParameters.TableName;
Schema = modificationCommandParameters.Schema;
_sensitiveLoggingEnabled = modificationCommandParameters.SensitiveLoggingEnabled;
EntityState = EntityState.Modified;
}
/// <inheritdoc />
public virtual ITable? Table { get; }
/// <inheritdoc />
public virtual IStoreStoredProcedure? StoreStoredProcedure { get; }
/// <inheritdoc />
public virtual string TableName { get; }
/// <inheritdoc />
public virtual string? Schema { get; }
/// <inheritdoc />
public virtual IReadOnlyList<IUpdateEntry> Entries
=> _entries;
/// <inheritdoc />
public virtual EntityState EntityState
{
get => _entityState;
set => _entityState = value;
}
/// <inheritdoc />
public virtual IColumnBase? RowsAffectedColumn { get; private set; }
/// <summary>
/// The list of <see cref="IColumnModification" /> needed to perform the insert, update, or delete.
/// </summary>
public virtual IReadOnlyList<IColumnModification> ColumnModifications
=> NonCapturingLazyInitializer.EnsureInitialized(
ref _columnModifications, this, static command => command.GenerateColumnModifications());
/// <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>
[Conditional("DEBUG")]
[EntityFrameworkInternal]
public virtual void AssertColumnsNotInitialized()
{
if (_columnModifications != null
&& !Debugger.IsAttached)
{
throw new Exception("_columnModifications have been initialized prematurely");
}
}
/// <inheritdoc />
public virtual void AddEntry(IUpdateEntry entry, bool mainEntry)
{
AssertColumnsNotInitialized();
switch (entry.EntityState)
{
case EntityState.Deleted:
case EntityState.Modified:
case EntityState.Added:
break;
default:
if (_sensitiveLoggingEnabled)
{
throw new InvalidOperationException(
RelationalStrings.ModificationCommandInvalidEntityStateSensitive(
entry.EntityType.DisplayName(),
entry.BuildCurrentValuesString(entry.EntityType.FindPrimaryKey()!.Properties),
entry.EntityState));
}
throw new InvalidOperationException(
RelationalStrings.ModificationCommandInvalidEntityState(
entry.EntityType.DisplayName(),
entry.EntityState));
}
if (mainEntry)
{
Check.DebugAssert(!_mainEntryAdded, "Only expected a single main entry");
for (var i = 0; i < _entries.Count; i++)
{
ValidateState(entry, _entries[i]);
}
_mainEntryAdded = true;
_entries.Insert(0, entry);
_entityState = entry.SharedIdentityEntry == null
? entry.EntityState
: entry.SharedIdentityEntry.EntityType == entry.EntityType
|| entry.SharedIdentityEntry.EntityType.GetTableMappings()
.Any(m => m.Table.Name == TableName && m.Table.Schema == Schema)
? EntityState.Modified
: entry.EntityState;
}
else
{
if (_mainEntryAdded)
{
ValidateState(_entries[0], entry);
}
_entries.Add(entry);
}
}
private void ValidateState(IUpdateEntry mainEntry, IUpdateEntry entry)
{
var mainEntryState = mainEntry.SharedIdentityEntry == null
? mainEntry.EntityState
: EntityState.Modified;
if (mainEntryState == EntityState.Modified)
{
return;
}
var entryState = entry.SharedIdentityEntry == null
? entry.EntityState
: EntityState.Modified;
if (mainEntryState != entryState)
{
if (_sensitiveLoggingEnabled)
{
throw new InvalidOperationException(
RelationalStrings.ConflictingRowUpdateTypesSensitive(
entry.EntityType.DisplayName(),
entry.BuildCurrentValuesString(entry.EntityType.FindPrimaryKey()!.Properties),
entryState,
mainEntry.EntityType.DisplayName(),
mainEntry.BuildCurrentValuesString(mainEntry.EntityType.FindPrimaryKey()!.Properties),
mainEntryState));
}
throw new InvalidOperationException(
RelationalStrings.ConflictingRowUpdateTypes(
entry.EntityType.DisplayName(),
entryState,
mainEntry.EntityType.DisplayName(),
mainEntryState));
}
}
/// <summary>
/// Creates a new <see cref="IColumnModification" /> and add it to this command.
/// </summary>
/// <param name="columnModificationParameters">Creation parameters.</param>
/// <returns>The new <see cref="IColumnModification" /> instance.</returns>
public virtual IColumnModification AddColumnModification(in ColumnModificationParameters columnModificationParameters)
{
var modification = CreateColumnModification(columnModificationParameters);
_columnModifications ??= [];
_columnModifications.Add(modification);
return modification;
}
/// <summary>
/// Creates a new instance that implements <see cref="IColumnModification" /> interface.
/// </summary>
/// <param name="columnModificationParameters">Creation parameters.</param>
/// <returns>The new instance that implements <see cref="IColumnModification" /> interface.</returns>
protected virtual IColumnModification CreateColumnModification(in ColumnModificationParameters columnModificationParameters)
=> new ColumnModification(columnModificationParameters);
private sealed class JsonPartialUpdateInfo
{
public List<JsonPartialUpdatePathEntry> Path { get; } = [];
public IProperty? Property { get; set; }
public object? PropertyValue { get; set; }
}
private record struct JsonPartialUpdatePathEntry(string PropertyName, int? Ordinal, IUpdateEntry ParentEntry, INavigation Navigation);
private List<IColumnModification> GenerateColumnModifications()
{
var state = EntityState;
var adding = state == EntityState.Added;
var updating = state == EntityState.Modified;
var deleting = state == EntityState.Deleted;
var columnModifications = new List<IColumnModification>();
Dictionary<string, ColumnValuePropagator>? sharedTableColumnMap = null;
var jsonEntry = false;
if (_entries.Count > 1
|| _entries is [var singleEntry]
&& (singleEntry.SharedIdentityEntry is not null
|| singleEntry.EntityType.GetComplexProperties().Any()
|| singleEntry.EntityType.GetNavigations().Any(e => e.IsCollection && e.TargetEntityType.IsMappedToJson())))
{
Check.DebugAssert(StoreStoredProcedure is null, "Multiple entries/shared identity not supported with stored procedures");
sharedTableColumnMap = new Dictionary<string, ColumnValuePropagator>();
if (_comparer != null
&& _entries.Count > 1)
{
_entries.Sort(_comparer);
}
foreach (var entry in _entries)
{
var tableMapping = GetTableMapping(entry.EntityType);
if (tableMapping == null)
{
continue;
}
if (entry.SharedIdentityEntry != null)
{
var sharedTableMapping = entry.EntityType != entry.SharedIdentityEntry.EntityType
? GetTableMapping(entry.SharedIdentityEntry.EntityType)
: tableMapping;
if (sharedTableMapping != null)
{
HandleSharedColumns(
entry.SharedIdentityEntry.EntityType, entry.SharedIdentityEntry, sharedTableMapping, deleting,
sharedTableColumnMap);
}
}
HandleSharedColumns(entry.EntityType, entry, tableMapping, deleting, sharedTableColumnMap);
if (!jsonEntry)
{
if (entry.EntityType.IsMappedToJson()
|| entry.EntityType.GetNavigations().Any(e => e.IsCollection && e.TargetEntityType.IsMappedToJson()))
{
jsonEntry = true;
}
}
}
}
if (jsonEntry)
{
HandleJson(columnModifications);
}
foreach (var entry in _entries.Where(x => !x.EntityType.IsMappedToJson()))
{
var nonMainEntry = !_mainEntryAdded || entry != _entries[0];
var optionalDependentWithAllNull = false;
if (StoreStoredProcedure is null)
{
var tableMapping = GetTableMapping(entry.EntityType);
if (tableMapping is null)
{
continue;
}
optionalDependentWithAllNull =
entry.EntityState is EntityState.Modified or EntityState.Added
&& tableMapping.Table.IsOptional(entry.EntityType)
&& tableMapping.Table.GetRowInternalForeignKeys(entry.EntityType).Any();
HandleNonJson(entry.EntityType, tableMapping);
}
else // Stored procedure mapping case
{
var storedProcedureMapping = GetStoredProcedureMapping(entry.EntityType, EntityState);
Check.DebugAssert(storedProcedureMapping is not null, "No sproc mapping but StoredProcedure is not null");
var storedProcedure = storedProcedureMapping.StoredProcedure;
// Stored procedures may have an additional rows affected result column or return value, which does not have a
// property/column mapping but still needs to have be represented via a column modification.
// Note that for rows affected parameters/result columns, we add column modifications below along with regular parameters/
// result columns; for return value we do that here.
if (storedProcedure.FindRowsAffectedParameter() is { } rowsAffectedParameter)
{
RowsAffectedColumn = rowsAffectedParameter.StoreParameter;
}
else if (storedProcedure.FindRowsAffectedResultColumn() is { } rowsAffectedResultColumn)
{
RowsAffectedColumn = rowsAffectedResultColumn.StoreResultColumn;
}
else if (storedProcedureMapping.StoreStoredProcedure.ReturnValue is { } rowsAffectedReturnValue)
{
RowsAffectedColumn = rowsAffectedReturnValue;
columnModifications.Add(
CreateColumnModification(
new ColumnModificationParameters(
entry: null,
property: null,
rowsAffectedReturnValue,
_generateParameterName!,
rowsAffectedReturnValue.StoreTypeMapping,
valueIsRead: true,
valueIsWrite: false,
columnIsKey: false,
columnIsCondition: false,
_sensitiveLoggingEnabled)));
}
// In TPH, the sproc has parameters for all entity types in the hierarchy; we must generate null column modifications
// for parameters for unrelated entity types.
// Enumerate over the sproc parameters in order, trying to match a corresponding parameter mapping.
// Note that we produce the column modifications in the same order as their sproc parameters; this is important and assumed
// later in the pipeline.
foreach (var parameter in StoreStoredProcedure.Parameters)
{
if (parameter.FindParameterMapping(entry.EntityType) is { } parameterMapping)
{
HandleColumn(parameterMapping);
continue;
}
// The parameter has no corresponding mapping; this is either a sibling property in a TPH hierarchy or a rows affected
// output parameter. Note that we set IsRead to false since we don't propagate the output parameter.
columnModifications.Add(
CreateColumnModification(
new ColumnModificationParameters(
entry: null,
property: null,
parameter,
_generateParameterName!,
parameter.StoreTypeMapping,
valueIsRead: false,
valueIsWrite: parameter.Direction.HasFlag(ParameterDirection.Input),
columnIsKey: false,
columnIsCondition: false,
_sensitiveLoggingEnabled)));
}
foreach (var resultColumn in StoreStoredProcedure.ResultColumns)
{
if (resultColumn.FindColumnMapping(entry.EntityType) is { } resultColumnMapping)
{
HandleColumn(resultColumnMapping);
continue;
}
// The result column has no corresponding mapping; this is either a sibling property in a TPH hierarchy or a rows
// affected result column. Note that we set IsRead to false since we don't propagate the result column.
columnModifications.Add(
CreateColumnModification(
new ColumnModificationParameters(
entry: null,
property: null,
resultColumn,
_generateParameterName!,
resultColumn.StoreTypeMapping,
valueIsRead: false,
valueIsWrite: false,
columnIsKey: false,
columnIsCondition: false,
_sensitiveLoggingEnabled)));
}
}
if (optionalDependentWithAllNull && _logger != null)
{
if (_sensitiveLoggingEnabled)
{
_logger.OptionalDependentWithAllNullPropertiesWarningSensitive(entry);
}
else
{
_logger.OptionalDependentWithAllNullPropertiesWarning(entry);
}
}
void HandleNonJson(ITypeBase structuralType, ITableMapping tableMapping)
{
foreach (var columnMapping in tableMapping.ColumnMappings)
{
HandleColumn(columnMapping);
}
foreach (var complexProperty in structuralType.GetComplexProperties())
{
var complexTableMapping = GetTableMapping(complexProperty.ComplexType);
if (complexTableMapping != null)
{
HandleNonJson(complexProperty.ComplexType, complexTableMapping);
}
}
}
void HandleColumn(IColumnMappingBase columnMapping)
{
var property = columnMapping.Property;
var column = columnMapping.Column;
var storedProcedureParameter = columnMapping is IStoredProcedureParameterMapping parameterMapping
? parameterMapping.Parameter
: null;
var isKey = property.IsPrimaryKey();
var isCondition = !adding
&& (isKey
|| storedProcedureParameter is { ForOriginalValue: true }
|| (property.IsConcurrencyToken && storedProcedureParameter is null));
// Store-generated properties generally need to be read back (unless we're deleting).
// One exception is if the property is mapped to a non-output parameter.
var readValue = state != EntityState.Deleted
&& ColumnModification.IsStoreGenerated(entry, property)
&& (storedProcedureParameter is null || storedProcedureParameter.Direction.HasFlag(ParameterDirection.Output));
ColumnValuePropagator? columnPropagator = null;
sharedTableColumnMap?.TryGetValue(column.Name, out columnPropagator);
var writeValue = false;
if (!readValue)
{
if (adding)
{
writeValue = property.GetBeforeSaveBehavior() == PropertySaveBehavior.Save
|| entry.HasStoreGeneratedValue(property);
columnPropagator?.TryPropagate(columnMapping, entry);
}
else if (storedProcedureParameter is not { ForOriginalValue: true }
&& !deleting
&& ((updating && property.GetAfterSaveBehavior() == PropertySaveBehavior.Save)
|| (!isKey && nonMainEntry)
|| entry.SharedIdentityEntry != null))
{
// Note that for stored procedures we always need to send all parameters, regardless of whether the property
// actually changed.
writeValue = columnPropagator?.TryPropagate(columnMapping, entry)
?? (entry.EntityState == EntityState.Added
|| entry.EntityState == EntityState.Deleted
|| ColumnModification.IsModified(entry, property)
|| StoreStoredProcedure is not null);
}
}
if (readValue
|| writeValue
|| isCondition)
{
var columnModificationParameters = new ColumnModificationParameters(
entry,
property,
column,
_generateParameterName!,
columnMapping.TypeMapping,
readValue,
writeValue,
isKey,
isCondition,
_sensitiveLoggingEnabled);
var columnModification = CreateColumnModification(columnModificationParameters);
if (columnPropagator != null
&& column.PropertyMappings.Count != 1)
{
if (columnPropagator.ColumnModification != null)
{
columnPropagator.ColumnModification.AddSharedColumnModification(columnModification);
return;
}
columnPropagator.ColumnModification = columnModification;
}
columnModifications.Add(columnModification);
if (optionalDependentWithAllNull
&& (columnModification.IsWrite
|| (columnModification.IsCondition && !isKey))
&& columnModification.Value is not null)
{
optionalDependentWithAllNull = false;
}
}
else if (optionalDependentWithAllNull
&& state == EntityState.Modified
&& property.DeclaringType == entry.EntityType
&& entry.GetCurrentValue(property) is not null)
{
optionalDependentWithAllNull = false;
}
}
}
return columnModifications;
void HandleSharedColumns(
ITypeBase structuralType,
IUpdateEntry entry,
ITableMapping tableMapping,
bool deleting,
Dictionary<string, ColumnValuePropagator> sharedTableColumnMap)
{
InitializeSharedColumns(entry, tableMapping, deleting, sharedTableColumnMap);
foreach (var complexProperty in structuralType.GetComplexProperties())
{
var complexTableMapping = GetTableMapping(complexProperty.ComplexType);
if (complexTableMapping != null)
{
HandleSharedColumns(
complexProperty.ComplexType, entry, complexTableMapping, deleting, sharedTableColumnMap);
}
}
}
static JsonPartialUpdateInfo? FindJsonPartialUpdateInfo(IUpdateEntry entry, List<IUpdateEntry> processedEntries)
{
var result = new JsonPartialUpdateInfo();
var currentEntry = entry;
var currentOwnership = currentEntry.EntityType.FindOwnership()!;
while (currentEntry.EntityType.IsMappedToJson())
{
var jsonPropertyName = currentEntry.EntityType.GetJsonPropertyName()!;
currentOwnership = currentEntry.EntityType.FindOwnership()!;
var previousEntry = currentEntry;
#pragma warning disable EF1001 // Internal EF Core API usage.
currentEntry = ((InternalEntityEntry)currentEntry).StateManager.FindPrincipal(
(InternalEntityEntry)currentEntry, currentOwnership)!;
#pragma warning restore EF1001 // Internal EF Core API usage.
if (processedEntries.Contains(currentEntry))
{
return null;
}
var ordinal = default(int?);
if (!currentOwnership.IsUnique
&& previousEntry.EntityState != EntityState.Added
&& previousEntry.EntityState != EntityState.Deleted)
{
var ordinalProperty = previousEntry.EntityType.FindPrimaryKey()!.Properties.Last();
ordinal = (int)previousEntry.GetCurrentProviderValue(ordinalProperty)! - 1;
}
var pathEntry = new JsonPartialUpdatePathEntry(
currentOwnership.PrincipalEntityType.IsMappedToJson() ? jsonPropertyName : "$",
ordinal,
currentEntry,
currentOwnership.GetNavigation(pointsToPrincipal: false)!);
result.Path.Insert(0, pathEntry);
}
var modifiedMembers = entry.EntityType.GetFlattenedProperties().Where(entry.IsModified).ToList();
if (modifiedMembers.Count == 1)
{
result.Property = modifiedMembers[0];
result.PropertyValue = entry.GetCurrentValue(result.Property);
}
else
{
// only add to processed entries list if we are planning to update the entire entity
// (rather than just a single property on that entity)
processedEntries.Add(entry);
}
// parent entity got deleted, no need to do any json-specific processing
if (currentEntry.EntityState == EntityState.Deleted)
{
return null;
}
return result;
}
static JsonPartialUpdateInfo FindCommonJsonPartialUpdateInfo(
JsonPartialUpdateInfo first,
JsonPartialUpdateInfo second)
{
var result = new JsonPartialUpdateInfo();
for (var i = 0; i < Math.Min(first.Path.Count, second.Path.Count); i++)
{
if (first.Path[i].PropertyName == second.Path[i].PropertyName)
{
if (first.Path[i].Ordinal == second.Path[i].Ordinal)
{
result.Path.Add(first.Path[i]);
continue;
}
var common = new JsonPartialUpdatePathEntry(
first.Path[i].PropertyName,
null,
first.Path[i].ParentEntry,
first.Path[i].Navigation);
result.Path.Add(common);
break;
}
}
Check.DebugAssert(result.Path.Count > 0, "Common denominator should always have at least one node - the root.");
return result;
}
void HandleJson(List<IColumnModification> columnModifications)
{
var jsonColumnsUpdateMap = new Dictionary<IColumn, JsonPartialUpdateInfo>();
var processedEntries = new List<IUpdateEntry>();
foreach (var entry in _entries.Where(e => e.EntityType.IsMappedToJson()))
{
var jsonColumn = GetTableMapping(entry.EntityType)!.Table.FindColumn(entry.EntityType.GetContainerColumnName()!);
if (jsonColumn == null)
{
continue;
}
var jsonPartialUpdateInfo = FindJsonPartialUpdateInfo(entry, processedEntries);
if (jsonPartialUpdateInfo == null)
{
continue;
}
if (jsonColumnsUpdateMap.TryGetValue(jsonColumn, out var currentJsonPartialUpdateInfo))
{
jsonPartialUpdateInfo = FindCommonJsonPartialUpdateInfo(
currentJsonPartialUpdateInfo,
jsonPartialUpdateInfo);
}
jsonColumnsUpdateMap[jsonColumn] = jsonPartialUpdateInfo;
}
foreach (var entry in _entries.Where(e => !e.EntityType.IsMappedToJson()))
{
foreach (var jsonCollectionNavigation in entry.EntityType.GetNavigations()
.Where(
n => n.IsCollection
&& n.TargetEntityType.IsMappedToJson()
&& (entry.GetCurrentValue(n) as IEnumerable)?.Any() == false))
{
var jsonCollectionEntityType = jsonCollectionNavigation.TargetEntityType;
var jsonCollectionColumn =
GetTableMapping(jsonCollectionEntityType)!.Table.FindColumn(
jsonCollectionEntityType.GetContainerColumnName()!)!;
if (!jsonColumnsUpdateMap.ContainsKey(jsonCollectionColumn))
{
var jsonPartialUpdateInfo = new JsonPartialUpdateInfo();
jsonPartialUpdateInfo.Path.Insert(0, new JsonPartialUpdatePathEntry("$", null, entry, jsonCollectionNavigation));
jsonPartialUpdateInfo.PropertyValue = entry.GetCurrentValue(jsonCollectionNavigation);
jsonColumnsUpdateMap[jsonCollectionColumn] = jsonPartialUpdateInfo;
}
}
}
foreach (var (jsonColumn, updateInfo) in jsonColumnsUpdateMap)
{
var finalUpdatePathElement = updateInfo.Path.Last();
var navigation = finalUpdatePathElement.Navigation;
var jsonColumnTypeMapping = jsonColumn.StoreTypeMapping;
var navigationValue = finalUpdatePathElement.ParentEntry.GetCurrentValue(navigation);
var jsonPathString = string.Join(
".", updateInfo.Path.Select(x => x.PropertyName + (x.Ordinal != null ? "[" + x.Ordinal + "]" : "")));
if (updateInfo.Property is IProperty property)
{
var columnModificationParameters = new ColumnModificationParameters(
jsonColumn.Name,
value: updateInfo.PropertyValue,
property: property,
columnType: jsonColumnTypeMapping.StoreType,
jsonColumnTypeMapping,
jsonPath: jsonPathString + "." + updateInfo.Property.GetJsonPropertyName(),
read: false,
write: true,
key: false,
condition: false,
_sensitiveLoggingEnabled) { GenerateParameterName = _generateParameterName };
ProcessSinglePropertyJsonUpdate(ref columnModificationParameters);
columnModifications.Add(new ColumnModification(columnModificationParameters));
}
else
{
var stream = new MemoryStream();
var writer = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = false });
if (finalUpdatePathElement.Ordinal != null && navigationValue != null)
{
var i = 0;
foreach (var navigationValueElement in (IEnumerable)navigationValue)
{
if (i == finalUpdatePathElement.Ordinal)
{
WriteJson(
writer,
navigationValueElement,
finalUpdatePathElement.ParentEntry,
navigation.TargetEntityType,
ordinal: null,
isCollection: false,
isTopLevel: true);
break;
}
i++;
}
}
else
{
WriteJson(
writer,
navigationValue,
finalUpdatePathElement.ParentEntry,
navigation.TargetEntityType,
ordinal: null,
isCollection: navigation.IsCollection,
isTopLevel: true);
}
writer.Flush();
var value = writer.BytesCommitted > 0
? Encoding.UTF8.GetString(stream.ToArray())
: null;
columnModifications.Add(
new ColumnModification(
new ColumnModificationParameters(
jsonColumn.Name,
value: value,
property: updateInfo.Property,
columnType: jsonColumnTypeMapping.StoreType,
jsonColumnTypeMapping,
jsonPath: jsonPathString,
read: false,
write: true,
key: false,
condition: false,
_sensitiveLoggingEnabled) { GenerateParameterName = _generateParameterName }));
}
}
}
}
/// <summary>
/// Performs processing specifically needed for column modifications that correspond to single-property JSON updates.
/// </summary>
/// <remarks>
/// By default, strings, numeric types and bool and sent as a regular relational parameter, since database functions responsible for
/// patching JSON documents support this. Other types get converted to JSON via the normal means and sent as a string parameter.
/// </remarks>
protected virtual void ProcessSinglePropertyJsonUpdate(ref ColumnModificationParameters parameters)
{
var property = parameters.Property!;
var mapping = property.GetRelationalTypeMapping();
var propertyProviderClrType = (mapping.Converter?.ProviderClrType ?? property.ClrType).UnwrapNullableType();
var value = parameters.Value;
// On most databases, the function which patches a JSON document (e.g. SQL Server JSON_MODIFY) accepts relational string, numeric
// and bool types directly, without serializing it to a JSON string. So by default, for those cases simply return the value as-is,
// with the property's type mapping which will take care of sending the parameter with the relational value.
// Note that we haven't yet applied a value converter if one is configured, in order to allow for it to get applied later with
// the regular parameter flow.
if (value == null
|| propertyProviderClrType == typeof(string)
|| propertyProviderClrType == typeof(bool)
|| propertyProviderClrType.IsNumeric())
{
parameters = parameters with { Value = value, TypeMapping = mapping };
}
else
{
var jsonValueReaderWriter = mapping.JsonValueReaderWriter;
value = jsonValueReaderWriter?.ToJsonString(value)[1..^1] // The JSON string contains enclosing quotes, remove these.
?? (mapping.Converter == null ? value : mapping.Converter.ConvertToProvider(value));
parameters = parameters with { Value = value };
}
}
private void WriteJson(
Utf8JsonWriter writer,
object? navigationValue,
IUpdateEntry parentEntry,
IEntityType entityType,
int? ordinal,
bool isCollection,
bool isTopLevel)
{
if (navigationValue == null)
{
if (!isTopLevel)
{
writer.WriteNullValue();
}
return;
}
if (isCollection)
{
var i = 1;
writer.WriteStartArray();
foreach (var collectionElement in (IEnumerable)navigationValue)
{
WriteJson(
writer,
collectionElement,
parentEntry,
entityType,
i++,
isCollection: false,
isTopLevel: false);
}
writer.WriteEndArray();
return;
}
#pragma warning disable EF1001 // Internal EF Core API usage.
var entry = (IUpdateEntry)((InternalEntityEntry)parentEntry).StateManager.TryGetEntry(navigationValue, entityType)!;
#pragma warning restore EF1001 // Internal EF Core API usage.
writer.WriteStartObject();
foreach (var property in entityType.GetFlattenedProperties())
{
if (property.IsKey())
{
if (property.IsOrdinalKeyProperty() && ordinal != null)
{
entry.SetStoreGeneratedValue(property, ordinal.Value, setModified: false);
}
continue;
}
// jsonPropertyName can only be null for key properties
var jsonPropertyName = property.GetJsonPropertyName()!;
var value = entry.GetCurrentValue(property);
writer.WritePropertyName(jsonPropertyName);
if (value is not null)
{
var jsonValueReaderWriter = property.GetJsonValueReaderWriter() ?? property.GetTypeMapping().JsonValueReaderWriter;
Check.DebugAssert(jsonValueReaderWriter is not null, "Missing JsonValueReaderWriter on JSON property");
jsonValueReaderWriter.ToJson(writer, value);
}
else
{
writer.WriteNullValue();
}
}
foreach (var navigation in entityType.GetNavigations())
{
// skip back-references to the parent
if (navigation.IsOnDependent)
{
continue;
}
var jsonPropertyName = navigation.TargetEntityType.GetJsonPropertyName()!;
var ownedNavigationValue = entry.GetCurrentValue(navigation)!;
writer.WritePropertyName(jsonPropertyName);
WriteJson(
writer,
ownedNavigationValue,
entry,
navigation.TargetEntityType,
ordinal: null,
isCollection: navigation.IsCollection,
isTopLevel: false);
}
writer.WriteEndObject();
}
private ITableMapping? GetTableMapping(ITypeBase structuralType)
{
foreach (var mapping in structuralType.GetTableMappings())
{
var table = mapping.Table;
if (table.Name == TableName
&& table.Schema == Schema)
{
return mapping;
}
}
return null;
}
private IStoredProcedureMapping? GetStoredProcedureMapping(IEntityType entityType, EntityState entityState)
{
var sprocMappings = entityState switch
{
EntityState.Added => entityType.GetInsertStoredProcedureMappings(),
EntityState.Modified => entityType.GetUpdateStoredProcedureMappings(),
EntityState.Deleted => entityType.GetDeleteStoredProcedureMappings(),
_ => throw new ArgumentOutOfRangeException(nameof(entityState), entityState, "Invalid EntityState value")
};
foreach (var mapping in sprocMappings)
{
if (mapping.StoreStoredProcedure == StoreStoredProcedure)
{
return mapping;
}
}
return null;
}
private static void InitializeSharedColumns(
IUpdateEntry entry,
ITableMapping tableMapping,
bool deleting,
Dictionary<string, ColumnValuePropagator> columnMap)
{
foreach (var columnMapping in tableMapping.ColumnMappings)
{
if (columnMapping.Property.DeclaringType.IsMappedToJson())
{
continue;
}
if (columnMapping.Column.PropertyMappings.Select(p => p.Property).Distinct().Count() == 1
&& entry.SharedIdentityEntry == null)
{
continue;