-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
DbContext.cs
1696 lines (1510 loc) · 82.8 KB
/
DbContext.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
// 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.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore.ChangeTracking.Internal;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Query.Internal;
using Microsoft.EntityFrameworkCore.Utilities;
using Microsoft.Extensions.DependencyInjection;
namespace Microsoft.EntityFrameworkCore
{
/// <summary>
/// A DbContext instance represents a session with the database and can be used to query and save
/// instances of your entities. DbContext is a combination of the Unit Of Work and Repository patterns.
/// </summary>
/// <remarks>
/// <para>
/// Typically you create a class that derives from DbContext and contains <see cref="DbSet{TEntity}" />
/// properties for each entity in the model. If the <see cref="DbSet{TEntity}" /> properties have a public setter,
/// they are automatically initialized when the instance of the derived context is created.
/// </para>
/// <para>
/// Override the <see cref="OnConfiguring(DbContextOptionsBuilder)" /> method to configure the database (and
/// other options) to be used for the context. Alternatively, if you would rather perform configuration externally
/// instead of inline in your context, you can use <see cref="DbContextOptionsBuilder{TContext}" />
/// (or <see cref="DbContextOptionsBuilder" />) to externally create an instance of <see cref="DbContextOptions{TContext}" />
/// (or <see cref="DbContextOptions" />) and pass it to a base constructor of <see cref="DbContext" />.
/// </para>
/// <para>
/// The model is discovered by running a set of conventions over the entity classes found in the
/// <see cref="DbSet{TEntity}" /> properties on the derived context. To further configure the model that
/// is discovered by convention, you can override the <see cref="OnModelCreating(ModelBuilder)" /> method.
/// </para>
/// </remarks>
public class DbContext :
IDisposable,
IAsyncDisposable,
IInfrastructure<IServiceProvider>,
IDbContextDependencies,
IDbSetCache,
IDbContextPoolable
{
private IDictionary<Type, object> _sets;
private readonly DbContextOptions _options;
private IDbContextServices _contextServices;
private IDbContextDependencies _dbContextDependencies;
private DatabaseFacade _database;
private ChangeTracker _changeTracker;
private IServiceScope _serviceScope;
private IDbContextPool _dbContextPool;
private bool _initializing;
private bool _disposed;
private readonly Guid _contextId = Guid.NewGuid();
private int _lease;
/// <summary>
/// <para>
/// Initializes a new instance of the <see cref="DbContext" /> class. The
/// <see cref="OnConfiguring(DbContextOptionsBuilder)" />
/// method will be called to configure the database (and other options) to be used for this context.
/// </para>
/// </summary>
protected DbContext()
: this(new DbContextOptions<DbContext>())
{
}
/// <summary>
/// <para>
/// Initializes a new instance of the <see cref="DbContext" /> class using the specified options.
/// The <see cref="OnConfiguring(DbContextOptionsBuilder)" /> method will still be called to allow further
/// configuration of the options.
/// </para>
/// </summary>
/// <param name="options">The options for this context.</param>
public DbContext([NotNull] DbContextOptions options)
{
Check.NotNull(options, nameof(options));
if (!options.ContextType.GetTypeInfo().IsAssignableFrom(GetType().GetTypeInfo()))
{
throw new InvalidOperationException(CoreStrings.NonGenericOptions(GetType().ShortDisplayName()));
}
_options = options;
// This service is not stored in _setInitializer as this may not be the service provider that will be used
// as the internal service provider going forward, because at this time OnConfiguring has not yet been called.
// Mostly that isn't a problem because set initialization is done by our internal services, but in the case
// where some of those services are replaced, this could initialize set using non-replaced services.
// In this rare case if this is a problem for the app, then the app can just not use this mechanism to create
// DbSet instances, and this code becomes a no-op. However, if this set initializer is then saved and used later
// for the Set method, then it makes the problem bigger because now an app is using the non-replaced services
// even when it doesn't need to.
ServiceProviderCache.Instance.GetOrAdd(options, providerRequired: false)
.GetRequiredService<IDbSetInitializer>()
.InitializeSets(this);
}
/// <summary>
/// Provides access to database related information and operations for this context.
/// </summary>
public virtual DatabaseFacade Database
{
get
{
CheckDisposed();
return _database ??= new DatabaseFacade(this);
}
}
/// <summary>
/// Provides access to information and operations for entity instances this context is tracking.
/// </summary>
public virtual ChangeTracker ChangeTracker
=> _changeTracker ??= InternalServiceProvider.GetRequiredService<IChangeTrackerFactory>().Create();
/// <summary>
/// The metadata about the shape of entities, the relationships between them, and how they map to the database.
/// </summary>
public virtual IModel Model
{
[DebuggerStepThrough] get => DbContextDependencies.Model;
}
/// <summary>
/// <para>
/// A unique identifier for the context instance and pool lease, if any.
/// </para>
/// <para>
/// This identifier is primarily intended as a correlation ID for logging and debugging such
/// that it is easy to identify that multiple events are using the same or different context instances.
/// </para>
/// </summary>
public virtual DbContextId ContextId
=> new DbContextId(_contextId, _lease);
/// <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>
[EntityFrameworkInternal]
IDbSetSource IDbContextDependencies.SetSource => DbContextDependencies.SetSource;
/// <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>
[EntityFrameworkInternal]
IEntityFinderFactory IDbContextDependencies.EntityFinderFactory => DbContextDependencies.EntityFinderFactory;
/// <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>
[EntityFrameworkInternal]
IAsyncQueryProvider IDbContextDependencies.QueryProvider => DbContextDependencies.QueryProvider;
/// <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>
[EntityFrameworkInternal]
IStateManager IDbContextDependencies.StateManager => DbContextDependencies.StateManager;
/// <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>
[EntityFrameworkInternal]
IChangeDetector IDbContextDependencies.ChangeDetector => DbContextDependencies.ChangeDetector;
/// <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>
[EntityFrameworkInternal]
IEntityGraphAttacher IDbContextDependencies.EntityGraphAttacher => DbContextDependencies.EntityGraphAttacher;
/// <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>
[EntityFrameworkInternal]
IDiagnosticsLogger<DbLoggerCategory.Update> IDbContextDependencies.UpdateLogger => DbContextDependencies.UpdateLogger;
/// <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>
[EntityFrameworkInternal]
IDiagnosticsLogger<DbLoggerCategory.Infrastructure> IDbContextDependencies.InfrastructureLogger
=> DbContextDependencies.InfrastructureLogger;
/// <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>
[EntityFrameworkInternal]
object IDbSetCache.GetOrAddSet(IDbSetSource source, Type type)
{
CheckDisposed();
if (_sets == null)
{
_sets = new Dictionary<Type, object>();
}
if (!_sets.TryGetValue(type, out var set))
{
set = source.Create(this, type);
_sets[type] = set;
}
return set;
}
/// <summary>
/// Creates a <see cref="DbSet{TEntity}" /> that can be used to query and save instances of <typeparamref name="TEntity" />.
/// </summary>
/// <typeparam name="TEntity"> The type of entity for which a set should be returned. </typeparam>
/// <returns> A set for the given entity type. </returns>
public virtual DbSet<TEntity> Set<TEntity>()
where TEntity : class
=> (DbSet<TEntity>)((IDbSetCache)this).GetOrAddSet(DbContextDependencies.SetSource, typeof(TEntity));
/// <summary>
/// Creates a <see cref="DbSet{TQuery}" /> that can be used to query instances of <typeparamref name="TQuery" />.
/// </summary>
/// <typeparam name="TQuery"> The type of query for which a DbQuery should be returned. </typeparam>
/// <returns> A DbQuery for the given keyless entity type. </returns>
[Obsolete("Use Set() for entity types without keys")]
public virtual DbQuery<TQuery> Query<TQuery>()
where TQuery : class
=> (DbQuery<TQuery>)((IDbSetCache)this).GetOrAddSet(DbContextDependencies.SetSource, typeof(TQuery));
private IEntityFinder Finder(Type type)
{
var entityType = Model.FindEntityType(type);
if (entityType == null)
{
if (Model.HasEntityTypeWithDefiningNavigation(type))
{
throw new InvalidOperationException(CoreStrings.InvalidSetTypeWeak(type.ShortDisplayName()));
}
throw new InvalidOperationException(CoreStrings.InvalidSetType(type.ShortDisplayName()));
}
if (entityType.FindPrimaryKey() == null)
{
throw new InvalidOperationException(CoreStrings.InvalidSetKeylessOperation(type.ShortDisplayName()));
}
return DbContextDependencies.EntityFinderFactory.Create(entityType);
}
private IServiceProvider InternalServiceProvider
{
get
{
CheckDisposed();
if (_contextServices != null)
{
return _contextServices.InternalServiceProvider;
}
if (_initializing)
{
throw new InvalidOperationException(CoreStrings.RecursiveOnConfiguring);
}
try
{
_initializing = true;
var optionsBuilder = new DbContextOptionsBuilder(_options);
OnConfiguring(optionsBuilder);
if (_options.IsFrozen
&& !ReferenceEquals(_options, optionsBuilder.Options))
{
throw new InvalidOperationException(CoreStrings.PoolingOptionsModified);
}
var options = optionsBuilder.Options;
_serviceScope = ServiceProviderCache.Instance.GetOrAdd(options, providerRequired: true)
.GetRequiredService<IServiceScopeFactory>()
.CreateScope();
var scopedServiceProvider = _serviceScope.ServiceProvider;
var contextServices = scopedServiceProvider.GetService<IDbContextServices>();
contextServices.Initialize(scopedServiceProvider, options, this);
_contextServices = contextServices;
DbContextDependencies.InfrastructureLogger.ContextInitialized(this, options);
}
finally
{
_initializing = false;
}
return _contextServices.InternalServiceProvider;
}
}
private IDbContextDependencies DbContextDependencies
{
[DebuggerStepThrough]
get
{
CheckDisposed();
return _dbContextDependencies ??= InternalServiceProvider.GetRequiredService<IDbContextDependencies>();
}
}
[DebuggerStepThrough]
private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().ShortDisplayName(), CoreStrings.ContextDisposed);
}
}
/// <summary>
/// <para>
/// Override this method to configure the database (and other options) to be used for this context.
/// This method is called for each instance of the context that is created.
/// The base implementation does nothing.
/// </para>
/// <para>
/// In situations where an instance of <see cref="DbContextOptions" /> may or may not have been passed
/// to the constructor, you can use <see cref="DbContextOptionsBuilder.IsConfigured" /> to determine if
/// the options have already been set, and skip some or all of the logic in
/// <see cref="OnConfiguring(DbContextOptionsBuilder)" />.
/// </para>
/// </summary>
/// <param name="optionsBuilder">
/// A builder used to create or modify options for this context. Databases (and other extensions)
/// typically define extension methods on this object that allow you to configure the context.
/// </param>
protected internal virtual void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
}
/// <summary>
/// Override this method to further configure the model that was discovered by convention from the entity types
/// exposed in <see cref="DbSet{TEntity}" /> properties on your derived context. The resulting model may be cached
/// and re-used for subsequent instances of your derived context.
/// </summary>
/// <remarks>
/// If a model is explicitly set on the options for this context (via <see cref="DbContextOptionsBuilder.UseModel(IModel)" />)
/// then this method will not be run.
/// </remarks>
/// <param name="modelBuilder">
/// The builder being used to construct the model for this context. Databases (and other extensions) typically
/// define extension methods on this object that allow you to configure aspects of the model that are specific
/// to a given database.
/// </param>
protected internal virtual void OnModelCreating(ModelBuilder modelBuilder)
{
}
/// <summary>
/// <para>
/// Saves all changes made in this context to the database.
/// </para>
/// <para>
/// This method will automatically call <see cref="ChangeTracking.ChangeTracker.DetectChanges" /> to discover any
/// changes to entity instances before saving to the underlying database. This can be disabled via
/// <see cref="ChangeTracking.ChangeTracker.AutoDetectChangesEnabled" />.
/// </para>
/// </summary>
/// <returns>
/// The number of state entries written to the database.
/// </returns>
/// <exception cref="DbUpdateException">
/// An error is encountered while saving to the database.
/// </exception>
/// <exception cref="DbUpdateConcurrencyException">
/// A concurrency violation is encountered while saving to the database.
/// A concurrency violation occurs when an unexpected number of rows are affected during save.
/// This is usually because the data in the database has been modified since it was loaded into memory.
/// </exception>
public virtual int SaveChanges() => SaveChanges(acceptAllChangesOnSuccess: true);
/// <summary>
/// <para>
/// Saves all changes made in this context to the database.
/// </para>
/// <para>
/// This method will automatically call <see cref="ChangeTracking.ChangeTracker.DetectChanges" /> to discover any
/// changes to entity instances before saving to the underlying database. This can be disabled via
/// <see cref="ChangeTracking.ChangeTracker.AutoDetectChangesEnabled" />.
/// </para>
/// </summary>
/// <param name="acceptAllChangesOnSuccess">
/// Indicates whether <see cref="ChangeTracking.ChangeTracker.AcceptAllChanges" /> is called after the changes have
/// been sent successfully to the database.
/// </param>
/// <returns>
/// The number of state entries written to the database.
/// </returns>
/// <exception cref="DbUpdateException">
/// An error is encountered while saving to the database.
/// </exception>
/// <exception cref="DbUpdateConcurrencyException">
/// A concurrency violation is encountered while saving to the database.
/// A concurrency violation occurs when an unexpected number of rows are affected during save.
/// This is usually because the data in the database has been modified since it was loaded into memory.
/// </exception>
public virtual int SaveChanges(bool acceptAllChangesOnSuccess)
{
CheckDisposed();
DbContextDependencies.UpdateLogger.SaveChangesStarting(this);
TryDetectChanges();
try
{
var entitiesSaved = DbContextDependencies.StateManager.SaveChanges(acceptAllChangesOnSuccess);
DbContextDependencies.UpdateLogger.SaveChangesCompleted(this, entitiesSaved);
return entitiesSaved;
}
catch (DbUpdateConcurrencyException exception)
{
DbContextDependencies.UpdateLogger.OptimisticConcurrencyException(this, exception);
throw;
}
catch (Exception exception)
{
DbContextDependencies.UpdateLogger.SaveChangesFailed(this, exception);
throw;
}
}
private void TryDetectChanges()
{
if (ChangeTracker.AutoDetectChangesEnabled)
{
ChangeTracker.DetectChanges();
}
}
private void TryDetectChanges(EntityEntry entry)
{
if (ChangeTracker.AutoDetectChangesEnabled)
{
entry.DetectChanges();
}
}
/// <summary>
/// <para>
/// Saves all changes made in this context to the database.
/// </para>
/// <para>
/// This method will automatically call <see cref="ChangeTracking.ChangeTracker.DetectChanges" /> to discover any
/// changes to entity instances before saving to the underlying database. This can be disabled via
/// <see cref="ChangeTracking.ChangeTracker.AutoDetectChangesEnabled" />.
/// </para>
/// <para>
/// Multiple active operations on the same context instance are not supported. Use 'await' to ensure
/// that any asynchronous operations have completed before calling another method on this context.
/// </para>
/// </summary>
/// <param name="cancellationToken"> A <see cref="CancellationToken" /> to observe while waiting for the task to complete. </param>
/// <returns>
/// A task that represents the asynchronous save operation. The task result contains the
/// number of state entries written to the database.
/// </returns>
/// <exception cref="DbUpdateException">
/// An error is encountered while saving to the database.
/// </exception>
/// <exception cref="DbUpdateConcurrencyException">
/// A concurrency violation is encountered while saving to the database.
/// A concurrency violation occurs when an unexpected number of rows are affected during save.
/// This is usually because the data in the database has been modified since it was loaded into memory.
/// </exception>
public virtual Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
=> SaveChangesAsync(acceptAllChangesOnSuccess: true, cancellationToken: cancellationToken);
/// <summary>
/// <para>
/// Saves all changes made in this context to the database.
/// </para>
/// <para>
/// This method will automatically call <see cref="ChangeTracking.ChangeTracker.DetectChanges" /> to discover any
/// changes to entity instances before saving to the underlying database. This can be disabled via
/// <see cref="ChangeTracking.ChangeTracker.AutoDetectChangesEnabled" />.
/// </para>
/// <para>
/// Multiple active operations on the same context instance are not supported. Use 'await' to ensure
/// that any asynchronous operations have completed before calling another method on this context.
/// </para>
/// </summary>
/// <param name="acceptAllChangesOnSuccess">
/// Indicates whether <see cref="ChangeTracking.ChangeTracker.AcceptAllChanges" /> is called after the changes have
/// been sent successfully to the database.
/// </param>
/// <param name="cancellationToken"> A <see cref="CancellationToken" /> to observe while waiting for the task to complete. </param>
/// <returns>
/// A task that represents the asynchronous save operation. The task result contains the
/// number of state entries written to the database.
/// </returns>
/// <exception cref="DbUpdateException">
/// An error is encountered while saving to the database.
/// </exception>
/// <exception cref="DbUpdateConcurrencyException">
/// A concurrency violation is encountered while saving to the database.
/// A concurrency violation occurs when an unexpected number of rows are affected during save.
/// This is usually because the data in the database has been modified since it was loaded into memory.
/// </exception>
public virtual async Task<int> SaveChangesAsync(
bool acceptAllChangesOnSuccess,
CancellationToken cancellationToken = default)
{
CheckDisposed();
DbContextDependencies.UpdateLogger.SaveChangesStarting(this);
TryDetectChanges();
try
{
var entitiesSaved = await DbContextDependencies.StateManager.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
DbContextDependencies.UpdateLogger.SaveChangesCompleted(this, entitiesSaved);
return entitiesSaved;
}
catch (DbUpdateConcurrencyException exception)
{
DbContextDependencies.UpdateLogger.OptimisticConcurrencyException(this, exception);
throw;
}
catch (Exception exception)
{
DbContextDependencies.UpdateLogger.SaveChangesFailed(this, exception);
throw;
}
}
/// <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>
void IDbContextPoolable.SetPool(IDbContextPool contextPool)
{
_dbContextPool = contextPool;
_lease = 1;
}
/// <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>
DbContextPoolConfigurationSnapshot IDbContextPoolable.SnapshotConfiguration()
=> new DbContextPoolConfigurationSnapshot(
_changeTracker?.AutoDetectChangesEnabled,
_changeTracker?.QueryTrackingBehavior,
_database?.AutoTransactionsEnabled,
_changeTracker?.LazyLoadingEnabled,
_changeTracker?.CascadeDeleteTiming,
_changeTracker?.DeleteOrphansTiming);
/// <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>
void IDbContextPoolable.Resurrect(DbContextPoolConfigurationSnapshot configurationSnapshot)
{
_disposed = false;
++_lease;
if (configurationSnapshot.AutoDetectChangesEnabled != null)
{
Debug.Assert(configurationSnapshot.QueryTrackingBehavior.HasValue);
Debug.Assert(configurationSnapshot.LazyLoadingEnabled.HasValue);
Debug.Assert(configurationSnapshot.CascadeDeleteTiming.HasValue);
Debug.Assert(configurationSnapshot.DeleteOrphansTiming.HasValue);
ChangeTracker.AutoDetectChangesEnabled = configurationSnapshot.AutoDetectChangesEnabled.Value;
ChangeTracker.QueryTrackingBehavior = configurationSnapshot.QueryTrackingBehavior.Value;
ChangeTracker.LazyLoadingEnabled = configurationSnapshot.LazyLoadingEnabled.Value;
ChangeTracker.CascadeDeleteTiming = configurationSnapshot.CascadeDeleteTiming.Value;
ChangeTracker.DeleteOrphansTiming = configurationSnapshot.DeleteOrphansTiming.Value;
}
else
{
((IResettableService)_changeTracker)?.ResetState();
}
if (_database != null)
{
_database.AutoTransactionsEnabled
= configurationSnapshot.AutoTransactionsEnabled == null
|| configurationSnapshot.AutoTransactionsEnabled.Value;
}
}
/// <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>
void IResettableService.ResetState()
{
foreach (var service in GetResettableServices())
{
service.ResetState();
}
_disposed = true;
}
/// <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>
/// <param name="cancellationToken"> A <see cref="CancellationToken" /> to observe while waiting for the task to complete. </param>
async Task IResettableService.ResetStateAsync(CancellationToken cancellationToken)
{
foreach (var service in GetResettableServices())
{
await service.ResetStateAsync(cancellationToken);
}
_disposed = true;
}
private IEnumerable<IResettableService> GetResettableServices()
{
var resettableServices
= _contextServices?.InternalServiceProvider?
.GetService<IEnumerable<IResettableService>>()?.ToList();
if (resettableServices != null)
{
foreach (var service in resettableServices)
{
yield return service;
}
}
if (_sets != null)
{
foreach (var set in _sets.Values)
{
if (set is IResettableService resettable)
{
yield return resettable;
}
}
}
}
/// <summary>
/// Releases the allocated resources for this context.
/// </summary>
public virtual void Dispose()
{
if (DisposeSync())
{
_serviceScope?.Dispose();
}
}
private bool DisposeSync()
{
if (_dbContextPool == null
&& !_disposed)
{
_dbContextDependencies?.InfrastructureLogger.ContextDisposed(this);
_disposed = true;
_dbContextDependencies?.StateManager.Unsubscribe();
_dbContextDependencies = null;
_changeTracker = null;
_database = null;
return true;
}
return false;
}
/// <summary>
/// Releases the allocated resources for this context.
/// </summary>
public virtual ValueTask DisposeAsync()
=> DisposeSync() ? _serviceScope.DisposeAsyncIfAvailable() : default;
/// <summary>
/// Gets an <see cref="EntityEntry{TEntity}" /> for the given entity. The entry provides
/// access to change tracking information and operations for the entity.
/// </summary>
/// <typeparam name="TEntity"> The type of the entity. </typeparam>
/// <param name="entity"> The entity to get the entry for. </param>
/// <returns> The entry for the given entity. </returns>
public virtual EntityEntry<TEntity> Entry<TEntity>([NotNull] TEntity entity)
where TEntity : class
{
Check.NotNull(entity, nameof(entity));
CheckDisposed();
var entry = EntryWithoutDetectChanges(entity);
TryDetectChanges(entry);
return entry;
}
private EntityEntry<TEntity> EntryWithoutDetectChanges<TEntity>(TEntity entity)
where TEntity : class
=> new EntityEntry<TEntity>(DbContextDependencies.StateManager.GetOrCreateEntry(entity));
/// <summary>
/// <para>
/// Gets an <see cref="EntityEntry" /> for the given entity. The entry provides
/// access to change tracking information and operations for the entity.
/// </para>
/// <para>
/// This method may be called on an entity that is not tracked. You can then
/// set the <see cref="EntityEntry.State" /> property on the returned entry
/// to have the context begin tracking the entity in the specified state.
/// </para>
/// </summary>
/// <param name="entity"> The entity to get the entry for. </param>
/// <returns> The entry for the given entity. </returns>
public virtual EntityEntry Entry([NotNull] object entity)
{
Check.NotNull(entity, nameof(entity));
CheckDisposed();
var entry = EntryWithoutDetectChanges(entity);
TryDetectChanges(entry);
return entry;
}
private EntityEntry EntryWithoutDetectChanges(object entity)
=> new EntityEntry(DbContextDependencies.StateManager.GetOrCreateEntry(entity));
private void SetEntityState(InternalEntityEntry entry, EntityState entityState)
{
if (entry.EntityState == EntityState.Detached)
{
DbContextDependencies.EntityGraphAttacher.AttachGraph(
entry,
entityState,
entityState,
forceStateWhenUnknownKey: true);
}
else
{
entry.SetEntityState(
entityState,
acceptChanges: true,
forceStateWhenUnknownKey: entityState);
}
}
private Task SetEntityStateAsync(
InternalEntityEntry entry,
EntityState entityState,
CancellationToken cancellationToken)
{
return entry.EntityState == EntityState.Detached
? DbContextDependencies.EntityGraphAttacher.AttachGraphAsync(
entry,
entityState,
entityState,
forceStateWhenUnknownKey: true,
cancellationToken: cancellationToken)
: entry.SetEntityStateAsync(
entityState,
acceptChanges: true,
forceStateWhenUnknownKey: entityState,
cancellationToken: cancellationToken);
}
/// <summary>
/// <para>
/// Begins tracking the given entity, and any other reachable entities that are
/// not already being tracked, in the <see cref="EntityState.Added" /> state such that
/// they will be inserted into the database when <see cref="SaveChanges()" /> is called.
/// </para>
/// <para>
/// Use <see cref="EntityEntry.State" /> to set the state of only a single entity.
/// </para>
/// </summary>
/// <typeparam name="TEntity"> The type of the entity. </typeparam>
/// <param name="entity"> The entity to add. </param>
/// <returns>
/// The <see cref="EntityEntry{TEntity}" /> for the entity. The entry provides
/// access to change tracking information and operations for the entity.
/// </returns>
public virtual EntityEntry<TEntity> Add<TEntity>([NotNull] TEntity entity)
where TEntity : class
{
CheckDisposed();
return SetEntityState(Check.NotNull(entity, nameof(entity)), EntityState.Added);
}
/// <summary>
/// <para>
/// Begins tracking the given entity, and any other reachable entities that are
/// not already being tracked, in the <see cref="EntityState.Added" /> state such that they will
/// be inserted into the database when <see cref="SaveChanges()" /> is called.
/// </para>
/// <para>
/// This method is async only to allow special value generators, such as the one used by
/// 'Microsoft.EntityFrameworkCore.Metadata.SqlServerValueGenerationStrategy.SequenceHiLo',
/// to access the database asynchronously. For all other cases the non async method should be used.
/// </para>
/// </summary>
/// <typeparam name="TEntity"> The type of the entity. </typeparam>
/// <param name="entity"> The entity to add. </param>
/// <param name="cancellationToken">A <see cref="CancellationToken" /> to observe while waiting for the task to complete.</param>
/// <returns>
/// A task that represents the asynchronous Add operation. The task result contains the
/// <see cref="EntityEntry{TEntity}" /> for the entity. The entry provides access to change tracking
/// information and operations for the entity.
/// </returns>
public virtual async ValueTask<EntityEntry<TEntity>> AddAsync<TEntity>(
[NotNull] TEntity entity,
CancellationToken cancellationToken = default)
where TEntity : class
{
CheckDisposed();
var entry = EntryWithoutDetectChanges(Check.NotNull(entity, nameof(entity)));
await SetEntityStateAsync(entry.GetInfrastructure(), EntityState.Added, cancellationToken);
return entry;
}
/// <summary>
/// <para>
/// Begins tracking the given entity and entries reachable from the given entity using
/// the <see cref="EntityState.Unchanged" /> state by default, but see below for cases
/// when a different state will be used.
/// </para>
/// <para>
/// Generally, no database interaction will be performed until <see cref="DbContext.SaveChanges()" /> is called.
/// </para>
/// <para>
/// A recursive search of the navigation properties will be performed to find reachable entities
/// that are not already being tracked by the context. All entities found will be tracked
/// by the context.
/// </para>
/// <para>
/// For entity types with generated keys if an entity has its primary key value set
/// then it will be tracked in the <see cref="EntityState.Unchanged" /> state. If the primary key
/// value is not set then it will be tracked in the <see cref="EntityState.Added" /> state.
/// This helps ensure only new entities will be inserted.
/// An entity is considered to have its primary key value set if the primary key property is set
/// to anything other than the CLR default for the property type.
/// </para>
/// <para>
/// For entity types without generated keys, the state set is always <see cref="EntityState.Unchanged" />.
/// </para>
/// <para>
/// Use <see cref="EntityEntry.State" /> to set the state of only a single entity.
/// </para>
/// </summary>
/// <typeparam name="TEntity"> The type of the entity. </typeparam>
/// <param name="entity"> The entity to attach. </param>
/// <returns>
/// The <see cref="EntityEntry{TEntity}" /> for the entity. The entry provides
/// access to change tracking information and operations for the entity.
/// </returns>
public virtual EntityEntry<TEntity> Attach<TEntity>([NotNull] TEntity entity)
where TEntity : class
{
CheckDisposed();
return SetEntityState(Check.NotNull(entity, nameof(entity)), EntityState.Unchanged);
}
/// <summary>
/// <para>
/// Begins tracking the given entity and entries reachable from the given entity using
/// the <see cref="EntityState.Modified" /> state by default, but see below for cases
/// when a different state will be used.
/// </para>
/// <para>
/// Generally, no database interaction will be performed until <see cref="DbContext.SaveChanges()" /> is called.
/// </para>
/// <para>
/// A recursive search of the navigation properties will be performed to find reachable entities
/// that are not already being tracked by the context. All entities found will be tracked
/// by the context.
/// </para>
/// <para>
/// For entity types with generated keys if an entity has its primary key value set
/// then it will be tracked in the <see cref="EntityState.Modified" /> state. If the primary key
/// value is not set then it will be tracked in the <see cref="EntityState.Added" /> state.
/// This helps ensure new entities will be inserted, while existing entities will be updated.
/// An entity is considered to have its primary key value set if the primary key property is set
/// to anything other than the CLR default for the property type.
/// </para>
/// <para>
/// For entity types without generated keys, the state set is always <see cref="EntityState.Modified" />.
/// </para>
/// <para>
/// Use <see cref="EntityEntry.State" /> to set the state of only a single entity.
/// </para>
/// </summary>
/// <typeparam name="TEntity"> The type of the entity. </typeparam>
/// <param name="entity"> The entity to update. </param>
/// <returns>
/// The <see cref="EntityEntry{TEntity}" /> for the entity. The entry provides
/// access to change tracking information and operations for the entity.
/// </returns>
public virtual EntityEntry<TEntity> Update<TEntity>([NotNull] TEntity entity)
where TEntity : class
{
CheckDisposed();
return SetEntityState(Check.NotNull(entity, nameof(entity)), EntityState.Modified);
}
/// <summary>
/// Begins tracking the given entity in the <see cref="EntityState.Deleted" /> state such that it will
/// be removed from the database when <see cref="SaveChanges()" /> is called.
/// </summary>
/// <remarks>
/// <para>
/// If the entity is already tracked in the <see cref="EntityState.Added" /> state then the context will
/// stop tracking the entity (rather than marking it as <see cref="EntityState.Deleted" />) since the
/// entity was previously added to the context and does not exist in the database.
/// </para>
/// <para>
/// Any other reachable entities that are not already being tracked will be tracked in the same way that