-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
CommandBatchPreparer.cs
770 lines (681 loc) · 33.9 KB
/
CommandBatchPreparer.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
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Utilities;
using Microsoft.Extensions.DependencyInjection;
namespace Microsoft.EntityFrameworkCore.Update.Internal
{
/// <summary>
/// <para>
/// 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.
/// </para>
/// <para>
/// The service lifetime is <see cref="ServiceLifetime.Scoped" />. This means that each
/// <see cref="DbContext" /> instance will use its own instance of this service.
/// The implementation may depend on other services registered with any lifetime.
/// The implementation does not need to be thread-safe.
/// </para>
/// </summary>
public class CommandBatchPreparer : ICommandBatchPreparer
{
private readonly IModificationCommandBatchFactory _modificationCommandBatchFactory;
private readonly IParameterNameGeneratorFactory _parameterNameGeneratorFactory;
private readonly IComparer<ModificationCommand> _modificationCommandComparer;
private readonly IKeyValueIndexFactorySource _keyValueIndexFactorySource;
private readonly int _minBatchSize;
private readonly bool _sensitiveLoggingEnabled;
/// <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 CommandBatchPreparer(CommandBatchPreparerDependencies dependencies)
{
_modificationCommandBatchFactory = dependencies.ModificationCommandBatchFactory;
_parameterNameGeneratorFactory = dependencies.ParameterNameGeneratorFactory;
_modificationCommandComparer = dependencies.ModificationCommandComparer;
_keyValueIndexFactorySource = dependencies.KeyValueIndexFactorySource;
_minBatchSize =
dependencies.Options.Extensions.OfType<RelationalOptionsExtension>().FirstOrDefault()?.MinBatchSize
?? 4;
Dependencies = dependencies;
if (dependencies.LoggingOptions.IsSensitiveDataLoggingEnabled)
{
_sensitiveLoggingEnabled = true;
}
}
private CommandBatchPreparerDependencies Dependencies { get; }
/// <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 IEnumerable<ModificationCommandBatch> BatchCommands(
IList<IUpdateEntry> entries,
IUpdateAdapter updateAdapter)
{
var parameterNameGenerator = _parameterNameGeneratorFactory.Create();
var commands = CreateModificationCommands(entries, updateAdapter, parameterNameGenerator.GenerateNext);
var sortedCommandSets = TopologicalSort(commands);
foreach (var independentCommandSet in sortedCommandSets)
{
independentCommandSet.Sort(_modificationCommandComparer);
var batch = _modificationCommandBatchFactory.Create();
foreach (var modificationCommand in independentCommandSet)
{
modificationCommand.AssertColumnsNotInitialized();
if (modificationCommand.EntityState == EntityState.Modified
&& !modificationCommand.ColumnModifications.Any(m => m.IsWrite))
{
continue;
}
if (!batch.AddCommand(modificationCommand))
{
if (batch.ModificationCommands.Count == 1
|| batch.ModificationCommands.Count >= _minBatchSize)
{
if (batch.ModificationCommands.Count > 1)
{
Dependencies.UpdateLogger.BatchReadyForExecution(
batch.ModificationCommands.SelectMany(c => c.Entries), batch.ModificationCommands.Count);
}
yield return batch;
}
else
{
Dependencies.UpdateLogger.BatchSmallerThanMinBatchSize(
batch.ModificationCommands.SelectMany(c => c.Entries), batch.ModificationCommands.Count, _minBatchSize);
foreach (var command in batch.ModificationCommands)
{
yield return StartNewBatch(parameterNameGenerator, command);
}
}
batch = StartNewBatch(parameterNameGenerator, modificationCommand);
}
}
if (batch.ModificationCommands.Count == 1
|| batch.ModificationCommands.Count >= _minBatchSize)
{
if (batch.ModificationCommands.Count > 1)
{
Dependencies.UpdateLogger.BatchReadyForExecution(
batch.ModificationCommands.SelectMany(c => c.Entries), batch.ModificationCommands.Count);
}
yield return batch;
}
else
{
Dependencies.UpdateLogger.BatchSmallerThanMinBatchSize(
batch.ModificationCommands.SelectMany(c => c.Entries), batch.ModificationCommands.Count, _minBatchSize);
foreach (var command in batch.ModificationCommands)
{
yield return StartNewBatch(parameterNameGenerator, command);
}
}
}
}
private ModificationCommandBatch StartNewBatch(
ParameterNameGenerator parameterNameGenerator,
ModificationCommand modificationCommand)
{
parameterNameGenerator.Reset();
var batch = _modificationCommandBatchFactory.Create();
batch.AddCommand(modificationCommand);
return batch;
}
/// <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 virtual IEnumerable<ModificationCommand> CreateModificationCommands(
IList<IUpdateEntry> entries,
IUpdateAdapter updateAdapter,
Func<string> generateParameterName)
{
var commands = new List<ModificationCommand>();
Dictionary<(string Name, string? Schema), SharedTableEntryMap<ModificationCommand>>? sharedTablesCommandsMap =
null;
foreach (var entry in entries)
{
if (entry.SharedIdentityEntry != null
&& entry.EntityState == EntityState.Deleted)
{
continue;
}
var mappings = (IReadOnlyCollection<ITableMapping>)entry.EntityType.GetTableMappings();
var mappingCount = mappings.Count;
ModificationCommand? firstCommand = null;
foreach (var mapping in mappings)
{
var table = mapping.Table;
var tableKey = (table.Name, table.Schema);
ModificationCommand command;
var isMainEntry = true;
if (table.IsShared)
{
if (sharedTablesCommandsMap == null)
{
sharedTablesCommandsMap = new Dictionary<(string, string?), SharedTableEntryMap<ModificationCommand>>();
}
if (!sharedTablesCommandsMap.TryGetValue(tableKey, out var sharedCommandsMap))
{
sharedCommandsMap = new SharedTableEntryMap<ModificationCommand>(table, updateAdapter);
sharedTablesCommandsMap.Add(tableKey, sharedCommandsMap);
}
command = sharedCommandsMap.GetOrAddValue(
entry,
(n, s, c) => new ModificationCommand(n, s, generateParameterName, _sensitiveLoggingEnabled, c));
isMainEntry = sharedCommandsMap.IsMainEntry(entry);
}
else
{
command = new ModificationCommand(
table.Name, table.Schema, generateParameterName, _sensitiveLoggingEnabled, comparer: null);
}
command.AddEntry(entry, isMainEntry);
commands.Add(command);
if (firstCommand == null)
{
Check.DebugAssert(firstCommand == null, "firstCommand == null");
firstCommand = command;
}
}
if (firstCommand == null)
{
throw new InvalidOperationException(RelationalStrings.ReadonlyEntitySaved(entry.EntityType.DisplayName()));
}
}
if (sharedTablesCommandsMap != null)
{
AddUnchangedSharingEntries(sharedTablesCommandsMap.Values, entries);
}
return commands;
}
private void AddUnchangedSharingEntries(
IEnumerable<SharedTableEntryMap<ModificationCommand>> sharedTablesCommands,
IList<IUpdateEntry> entries)
{
foreach (var sharedCommandsMap in sharedTablesCommands)
{
foreach (var command in sharedCommandsMap.Values)
{
if (command.EntityState != EntityState.Modified)
{
continue;
}
foreach (var entry in sharedCommandsMap.GetAllEntries(command.Entries[0]))
{
if (entry.EntityState != EntityState.Unchanged)
{
continue;
}
entry.EntityState = EntityState.Modified;
command.AddEntry(entry, sharedCommandsMap.IsMainEntry(entry));
entries.Add(entry);
}
}
}
}
// To avoid violating store constraints the modification commands must be sorted
// according to these rules:
//
// 1. Commands adding rows or modifying the candidate key values (when supported) must precede
// commands adding or modifying rows that will be referencing the former
// 2. Commands deleting rows or modifying the foreign key values must precede
// commands deleting rows or modifying the candidate key values (when supported) of rows
// that are currently being referenced by the former
// 3. Commands deleting rows or modifying unique constraint values must precede
// commands adding or modifying unique constraint values to the same values
/// <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 virtual IReadOnlyList<List<ModificationCommand>> TopologicalSort(IEnumerable<ModificationCommand> commands)
{
var modificationCommandGraph = new Multigraph<ModificationCommand, IAnnotatable>();
modificationCommandGraph.AddVertices(commands);
// The predecessors map allows to populate the graph in linear time
var predecessorsMap = CreateKeyValuePredecessorMap(modificationCommandGraph);
AddForeignKeyEdges(modificationCommandGraph, predecessorsMap);
AddUniqueValueEdges(modificationCommandGraph);
return modificationCommandGraph.BatchingTopologicalSort(FormatCycle);
}
private string FormatCycle(IReadOnlyList<Tuple<ModificationCommand, ModificationCommand, IEnumerable<IAnnotatable>>> data)
{
var builder = new StringBuilder();
for (var i = 0; i < data.Count; i++)
{
var edge = data[i];
Format(edge.Item1, builder);
switch (edge.Item3.First())
{
case IForeignKey foreignKey:
Format(foreignKey, edge.Item1, edge.Item2, builder);
break;
case IIndex index:
Format(index, edge.Item1, edge.Item2, builder);
break;
}
if (i == data.Count - 1)
{
Format(edge.Item2, builder);
}
}
if (!_sensitiveLoggingEnabled)
{
builder.Append(CoreStrings.SensitiveDataDisabled);
}
return builder.ToString();
}
private void Format(ModificationCommand command, StringBuilder builder)
{
var entry = command.Entries.First();
var entityType = entry.EntityType;
builder.Append(entityType.DisplayName());
if (_sensitiveLoggingEnabled)
{
builder.Append(" { ");
var properties = entityType.FindPrimaryKey()!.Properties;
for (var i = 0; i < properties.Count; i++)
{
var keyProperty = properties[i];
builder.Append("'");
builder.Append(keyProperty.Name);
builder.Append("': ");
builder.Append(entry.GetCurrentValue(keyProperty));
if (i != properties.Count - 1)
{
builder.Append(", ");
}
}
builder.Append(" } ");
}
else
{
builder.Append(" ");
}
builder.Append("[");
builder.Append(entry.EntityState);
builder.Append("]");
}
private void Format(IForeignKey foreignKey, ModificationCommand source, ModificationCommand target, StringBuilder builder)
{
var reverseDependency = !source.Entries.Any(e => foreignKey.DeclaringEntityType.IsAssignableFrom(e.EntityType));
if (reverseDependency)
{
builder.AppendLine(" <-");
}
else
{
builder.Append(" ");
}
if (foreignKey.DependentToPrincipal != null
|| foreignKey.PrincipalToDependent != null)
{
if (!reverseDependency
&& foreignKey.DependentToPrincipal != null)
{
builder.Append(foreignKey.DependentToPrincipal.Name);
builder.Append(" ");
}
if (foreignKey.PrincipalToDependent != null)
{
builder.Append(foreignKey.PrincipalToDependent.Name);
builder.Append(" ");
}
if (reverseDependency
&& foreignKey.DependentToPrincipal != null)
{
builder.Append(foreignKey.DependentToPrincipal.Name);
builder.Append(" ");
}
}
else
{
builder.Append("ForeignKey ");
}
var dependentCommand = reverseDependency ? target : source;
var dependentEntry = dependentCommand.Entries.First(e => foreignKey.DeclaringEntityType.IsAssignableFrom(e.EntityType));
builder.Append("{ ");
for (var i = 0; i < foreignKey.Properties.Count; i++)
{
var property = foreignKey.Properties[i];
builder.Append("'");
builder.Append(property.Name);
builder.Append("'");
if (_sensitiveLoggingEnabled)
{
builder.Append(": ");
builder.Append(dependentEntry.GetCurrentValue(property));
}
if (i != foreignKey.Properties.Count - 1)
{
builder.Append(", ");
}
}
builder.Append(" } ");
if (!reverseDependency)
{
builder.AppendLine("<-");
}
}
private void Format(IIndex index, ModificationCommand source, ModificationCommand target, StringBuilder builder)
{
var reverseDependency = source.EntityState != EntityState.Deleted;
if (reverseDependency)
{
builder.AppendLine(" <-");
}
else
{
builder.Append(" ");
}
builder.Append("Index ");
var dependentCommand = reverseDependency ? target : source;
var dependentEntry = dependentCommand.Entries.First(e => index.DeclaringEntityType.IsAssignableFrom(e.EntityType));
builder.Append("{ ");
for (var i = 0; i < index.Properties.Count; i++)
{
var property = index.Properties[i];
builder.Append("'");
builder.Append(property.Name);
builder.Append("'");
if (_sensitiveLoggingEnabled)
{
builder.Append(": ");
builder.Append(dependentEntry.GetCurrentValue(property));
}
if (i != index.Properties.Count - 1)
{
builder.Append(", ");
}
}
builder.Append(" } ");
if (!reverseDependency)
{
builder.AppendLine("<-");
}
}
// Builds a map from foreign key values to list of modification commands, with an entry for every command
// that may need to precede some other command involving that foreign key value.
private Dictionary<IKeyValueIndex, List<ModificationCommand>> CreateKeyValuePredecessorMap(
Multigraph<ModificationCommand, IAnnotatable> commandGraph)
{
var predecessorsMap = new Dictionary<IKeyValueIndex, List<ModificationCommand>>();
foreach (var command in commandGraph.Vertices)
{
if (command.EntityState == EntityState.Modified
|| command.EntityState == EntityState.Added)
{
// ReSharper disable once ForCanBeConvertedToForeach
for (var i = 0; i < command.Entries.Count; i++)
{
var entry = command.Entries[i];
foreach (var foreignKey in entry.EntityType.GetReferencingForeignKeys())
{
var constraints = foreignKey.GetMappedConstraints()
.Where(c => c.PrincipalTable.Name == command.TableName && c.PrincipalTable.Schema == command.Schema);
if (!constraints.Any()
|| (entry.EntityState == EntityState.Modified
&& !foreignKey.PrincipalKey.Properties.Any(p => entry.IsModified(p))))
{
continue;
}
var principalKeyValue = _keyValueIndexFactorySource
.GetKeyValueIndexFactory(foreignKey.PrincipalKey)
.CreatePrincipalKeyValue(entry, foreignKey);
if (principalKeyValue != null)
{
if (!predecessorsMap.TryGetValue(principalKeyValue, out var predecessorCommands))
{
predecessorCommands = new List<ModificationCommand>();
predecessorsMap.Add(principalKeyValue, predecessorCommands);
}
predecessorCommands.Add(command);
}
}
}
}
if (command.EntityState == EntityState.Modified
|| command.EntityState == EntityState.Deleted)
{
foreach (var entry in command.Entries)
{
foreach (var foreignKey in entry.EntityType.GetForeignKeys())
{
var constraints = foreignKey.GetMappedConstraints()
.Where(c => c.Table.Name == command.TableName && c.Table.Schema == command.Schema);
if (!constraints.Any()
|| (entry.EntityState == EntityState.Modified
&& !foreignKey.Properties.Any(p => entry.IsModified(p))))
{
continue;
}
var dependentKeyValue = _keyValueIndexFactorySource
.GetKeyValueIndexFactory(foreignKey.PrincipalKey)
.CreateDependentKeyValueFromOriginalValues(entry, foreignKey);
if (dependentKeyValue != null)
{
if (!predecessorsMap.TryGetValue(dependentKeyValue, out var predecessorCommands))
{
predecessorCommands = new List<ModificationCommand>();
predecessorsMap.Add(dependentKeyValue, predecessorCommands);
}
predecessorCommands.Add(command);
}
}
}
}
}
return predecessorsMap;
}
private void AddForeignKeyEdges(
Multigraph<ModificationCommand, IAnnotatable> commandGraph,
Dictionary<IKeyValueIndex, List<ModificationCommand>> predecessorsMap)
{
foreach (var command in commandGraph.Vertices)
{
switch (command.EntityState)
{
case EntityState.Modified:
case EntityState.Added:
// ReSharper disable once ForCanBeConvertedToForeach
for (var entryIndex = 0; entryIndex < command.Entries.Count; entryIndex++)
{
var entry = command.Entries[entryIndex];
foreach (var foreignKey in entry.EntityType.GetForeignKeys())
{
if (!foreignKey.GetMappedConstraints()
.Any(c => c.Table.Name == command.TableName && c.Table.Schema == command.Schema)
|| (entry.EntityState == EntityState.Modified
&& !foreignKey.Properties.Any(p => entry.IsModified(p))))
{
continue;
}
var dependentKeyValue = _keyValueIndexFactorySource
.GetKeyValueIndexFactory(foreignKey.PrincipalKey)
.CreateDependentKeyValue(entry, foreignKey);
if (dependentKeyValue == null)
{
continue;
}
AddMatchingPredecessorEdge(
predecessorsMap, dependentKeyValue, commandGraph, command, foreignKey);
}
}
break;
case EntityState.Deleted:
// ReSharper disable once ForCanBeConvertedToForeach
for (var entryIndex = 0; entryIndex < command.Entries.Count; entryIndex++)
{
var entry = command.Entries[entryIndex];
foreach (var foreignKey in entry.EntityType.GetReferencingForeignKeys())
{
var constraints = foreignKey.GetMappedConstraints()
.Where(c => c.PrincipalTable.Name == command.TableName && c.PrincipalTable.Schema == command.Schema);
if (!constraints.Any())
{
continue;
}
var principalKeyValue = _keyValueIndexFactorySource
.GetKeyValueIndexFactory(foreignKey.PrincipalKey)
.CreatePrincipalKeyValueFromOriginalValues(entry, foreignKey);
if (principalKeyValue != null)
{
AddMatchingPredecessorEdge(
predecessorsMap, principalKeyValue, commandGraph, command, foreignKey);
}
}
}
break;
}
}
}
private static void AddMatchingPredecessorEdge<T>(
Dictionary<T, List<ModificationCommand>> predecessorsMap,
T keyValue,
Multigraph<ModificationCommand, IAnnotatable> commandGraph,
ModificationCommand command,
IAnnotatable edge)
where T: notnull
{
if (predecessorsMap.TryGetValue(keyValue, out var predecessorCommands))
{
foreach (var predecessor in predecessorCommands)
{
if (predecessor != command)
{
commandGraph.AddEdge(predecessor, command, edge);
}
}
}
}
private void AddUniqueValueEdges(Multigraph<ModificationCommand, IAnnotatable> commandGraph)
{
Dictionary<IIndex, Dictionary<object[], ModificationCommand>>? indexPredecessorsMap = null;
var keyPredecessorsMap = new Dictionary<(IKey, IKeyValueIndex), List<ModificationCommand>>();
foreach (var command in commandGraph.Vertices)
{
if (command.EntityState != EntityState.Modified
&& command.EntityState != EntityState.Deleted)
{
continue;
}
for (var entryIndex = 0; entryIndex < command.Entries.Count; entryIndex++)
{
var entry = command.Entries[entryIndex];
foreach (var index in entry.EntityType.GetIndexes().Where(i => i.IsUnique && i.GetMappedTableIndexes().Any()))
{
if (entry.EntityState == EntityState.Modified
&& !index.Properties.Any(p => entry.IsModified(p)))
{
continue;
}
var valueFactory = index.GetNullableValueFactory<object[]>();
if (valueFactory.TryCreateFromOriginalValues(entry, out var indexValue))
{
indexPredecessorsMap ??= new Dictionary<IIndex, Dictionary<object[], ModificationCommand>>();
if (!indexPredecessorsMap.TryGetValue(index, out var predecessorCommands))
{
predecessorCommands = new Dictionary<object[], ModificationCommand>(valueFactory.EqualityComparer);
indexPredecessorsMap.Add(index, predecessorCommands);
}
if (!predecessorCommands.ContainsKey(indexValue))
{
predecessorCommands.Add(indexValue, command);
}
}
}
if (command.EntityState != EntityState.Deleted)
{
continue;
}
foreach (var key in entry.EntityType.GetKeys().Where(k => k.GetMappedConstraints().Any()))
{
var principalKeyValue = _keyValueIndexFactorySource
.GetKeyValueIndexFactory(key)
.CreatePrincipalKeyValue(entry, null);
if (principalKeyValue != null)
{
if (!keyPredecessorsMap.TryGetValue((key, principalKeyValue), out var predecessorCommands))
{
predecessorCommands = new List<ModificationCommand>();
keyPredecessorsMap.Add((key, principalKeyValue), predecessorCommands);
}
predecessorCommands.Add(command);
}
}
}
}
if (indexPredecessorsMap != null)
{
foreach (var command in commandGraph.Vertices)
{
if (command.EntityState == EntityState.Deleted)
{
continue;
}
foreach (var entry in command.Entries)
{
foreach (var index in entry.EntityType.GetIndexes().Where(i => i.IsUnique && i.GetMappedTableIndexes().Any()))
{
if (entry.EntityState == EntityState.Modified
&& !index.Properties.Any(p => entry.IsModified(p)))
{
continue;
}
var valueFactory = index.GetNullableValueFactory<object[]>();
if (valueFactory.TryCreateFromCurrentValues(entry, out var indexValue)
&& indexPredecessorsMap.TryGetValue(index, out var predecessorCommands)
&& predecessorCommands.TryGetValue(indexValue, out var predecessor)
&& predecessor != command)
{
commandGraph.AddEdge(predecessor, command, index);
}
}
}
}
}
if (keyPredecessorsMap != null)
{
foreach (var command in commandGraph.Vertices)
{
if (command.EntityState != EntityState.Added)
{
continue;
}
foreach (var entry in command.Entries)
{
foreach (var key in entry.EntityType.GetKeys().Where(k => k.GetMappedConstraints().Any()))
{
var principalKeyValue = _keyValueIndexFactorySource
.GetKeyValueIndexFactory(key)
.CreatePrincipalKeyValue(entry, null);
if (principalKeyValue != null)
{
AddMatchingPredecessorEdge(
keyPredecessorsMap, (key, principalKeyValue), commandGraph, command, key);
}
}
}
}
}
}
}
}