-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
DbContext.cs
2176 lines (1954 loc) · 111 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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
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.Metadata.Internal;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.EntityFrameworkCore.Utilities;
using Microsoft.Extensions.DependencyInjection;
namespace Microsoft.EntityFrameworkCore
{
/// <summary>
/// <para>
/// 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.
/// </para>
/// <para>
/// Entity Framework Core does not support multiple parallel operations being run on the same DbContext instance. This
/// includes both parallel execution of async queries and any explicit concurrent use from multiple threads.
/// Therefore, always await async calls immediately, or use separate DbContext instances for operations that execute
/// in parallel. See <see href="https://aka.ms/efcore-docs-threading">Avoiding DbContext threading issues</see> for more information.
/// </para>
/// </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>
/// <para>
/// See <see href="https://aka.ms/efcore-docs-dbcontext">DbContext lifetime, configuration, and initialization</see>,
/// <see href="https://aka.ms/efcore-docs-query">Querying data with EF Core</see>,
/// <see href="https://aka.ms/efcore-docs-change-tracking">Changing tracking</see>, and
/// <see href="https://aka.ms/efcore-docs-saving-data">Saving data with EF Core</see> for more information.
/// </para>
/// </remarks>
public class DbContext :
IInfrastructure<IServiceProvider>,
IDbContextDependencies,
IDbSetCache,
IDbContextPoolable
{
private readonly DbContextOptions _options;
private IDictionary<(Type Type, string? Name), object>? _sets;
private IDbContextServices? _contextServices;
private IDbContextDependencies? _dbContextDependencies;
private DatabaseFacade? _database;
private ChangeTracker? _changeTracker;
private IServiceScope? _serviceScope;
private DbContextLease _lease = DbContextLease.InactiveLease;
private DbContextPoolConfigurationSnapshot? _configurationSnapshot;
private List<IResettableService>? _cachedResettableServices;
private bool _initializing;
private bool _disposed;
private readonly Guid _contextId = Guid.NewGuid();
private int _leaseCount;
/// <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>
/// <remarks>
/// See <see href="https://aka.ms/efcore-docs-dbcontext">DbContext lifetime, configuration, and initialization</see>
/// for more information.
/// </remarks>
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>
/// <remarks>
/// See <see href="https://aka.ms/efcore-docs-dbcontext">DbContext lifetime, configuration, and initialization</see> and
/// <see href="https://aka.ms/efcore-docs-dbcontext-options">Using DbContextOptions</see> for more information.
/// </remarks>
/// <param name="options">The options for this context.</param>
public DbContext(DbContextOptions options)
{
Check.NotNull(options, nameof(options));
if (!options.ContextType.IsAssignableFrom(GetType()))
{
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);
EntityFrameworkEventSource.Log.DbContextInitializing();
}
/// <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>
/// <remarks>
/// See <see href="https://aka.ms/efcore-docs-change-tracking">EF Core change tracking</see> for more information.
/// </remarks>
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.
/// May not include all the information necessary to initialize the database.
/// </summary>
/// <remarks>
/// See <see href="https://aka.ms/efcore-docs-modeling">Modeling entity types and relationships</see> for more information.
/// </remarks>
public virtual IModel Model
{
[DebuggerStepThrough]
get => ContextServices.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(_contextId, _leaseCount);
/// <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();
_sets ??= new Dictionary<(Type Type, string? Name), object>();
if (!_sets.TryGetValue((type, null), out var set))
{
set = source.Create(this, type);
_sets[(type, null)] = set;
_cachedResettableServices = null;
}
return set;
}
/// <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, string entityTypeName, Type type)
{
CheckDisposed();
_sets ??= new Dictionary<(Type Type, string? Name), object>();
if (!_sets.TryGetValue((type, entityTypeName), out var set))
{
set = source.Create(this, entityTypeName, type);
_sets[(type, entityTypeName)] = set;
_cachedResettableServices = null;
}
return set;
}
/// <summary>
/// <para>
/// Creates a <see cref="DbSet{TEntity}" /> that can be used to query and save instances of <typeparamref name="TEntity" />.
/// </para>
/// <para>
/// Entity Framework Core does not support multiple parallel operations being run on the same DbContext instance. This
/// includes both parallel execution of async queries and any explicit concurrent use from multiple threads.
/// Therefore, always await async calls immediately, or use separate DbContext instances for operations that execute
/// in parallel. See <see href="https://aka.ms/efcore-docs-threading">Avoiding DbContext threading issues</see> for more information.
/// </para>
/// </summary>
/// <remarks>
/// See <see href="https://aka.ms/efcore-docs-query">Querying data with EF Core</see> and
/// <see href="https://aka.ms/efcore-docs-change-tracking">Changing tracking</see> for more information.
/// </remarks>
/// <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>
/// <para>
/// Creates a <see cref="DbSet{TEntity}" /> for a shared-type entity type that can be used to query and save
/// instances of <typeparamref name="TEntity" />.
/// </para>
/// <para>
/// Shared-type entity types are typically used for the join entity in many-to-many relationships.
/// </para>
/// </summary>
/// <remarks>
/// See <see href="https://aka.ms/efcore-docs-query">Querying data with EF Core</see>,
/// <see href="https://aka.ms/efcore-docs-change-tracking">Changing tracking</see>, and
/// <see href="https://aka.ms/efcore-docs-shared-types">Shared entity types</see> for more information.
/// </remarks>
/// <param name="name">The name for the shared-type entity type to use.</param>
/// <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>(string name)
where TEntity : class
=> (DbSet<TEntity>)((IDbSetCache)this).GetOrAddSet(DbContextDependencies.SetSource, name, typeof(TEntity));
private IEntityFinder Finder(Type type)
{
var entityType = Model.FindEntityType(type);
if (entityType == null)
{
if (Model.IsShared(type))
{
throw new InvalidOperationException(CoreStrings.InvalidSetSharedType(type.ShortDisplayName()));
}
var findSameTypeName = Model.FindSameTypeNameWithDifferentNamespace(type);
//if the same name exists in your entity types we will show you the full namespace of the type
if (!string.IsNullOrEmpty(findSameTypeName))
{
throw new InvalidOperationException(
CoreStrings.InvalidSetSameTypeWithDifferentNamespace(type.DisplayName(), findSameTypeName));
}
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
=> ContextServices.InternalServiceProvider;
private IDbContextServices ContextServices
{
get
{
CheckDisposed();
if (_contextServices != null)
{
return _contextServices;
}
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.GetRequiredService<IDbContextServices>();
contextServices.Initialize(scopedServiceProvider, options, this);
_contextServices = contextServices;
DbContextDependencies.InfrastructureLogger.ContextInitialized(this, options);
}
finally
{
_initializing = false;
}
return _contextServices;
}
}
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>
/// <remarks>
/// See <see href="https://aka.ms/efcore-docs-dbcontext">DbContext lifetime, configuration, and initialization</see>
/// for more information.
/// </remarks>
/// <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 set defaults and configure conventions before they run. This method is invoked before
/// <see cref="OnModelCreating" />.
/// </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>
/// <remarks>
/// See <see href="https://aka.ms/efcore-docs-pre-convention">Pre-convention model building in EF Core</see> for more information.
/// </remarks>
/// <param name="configurationBuilder">
/// The builder being used to set defaults and configure conventions that will be used to build the model for this context.
/// </param>
protected internal virtual void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
{
}
/// <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>
/// <para>
/// 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.
/// </para>
/// <para>
/// See <see href="https://aka.ms/efcore-docs-modeling">Modeling entity types and relationships</see> for more information.
/// </para>
/// </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="ChangeTracker.DetectChanges" /> to discover any
/// changes to entity instances before saving to the underlying database. This can be disabled via
/// <see cref="ChangeTracker.AutoDetectChangesEnabled" />.
/// </para>
/// <para>
/// Entity Framework Core does not support multiple parallel operations being run on the same DbContext instance. This
/// includes both parallel execution of async queries and any explicit concurrent use from multiple threads.
/// Therefore, always await async calls immediately, or use separate DbContext instances for operations that execute
/// in parallel. See <see href="https://aka.ms/efcore-docs-threading">Avoiding DbContext threading issues</see> for more information.
/// </para>
/// </summary>
/// <remarks>
/// See <see href="https://aka.ms/efcore-docs-saving-data">Saving data in EF Core</see> for more information.
/// </remarks>
/// <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="ChangeTracker.DetectChanges" /> to discover any
/// changes to entity instances before saving to the underlying database. This can be disabled via
/// <see cref="ChangeTracker.AutoDetectChangesEnabled" />.
/// </para>
/// <para>
/// Entity Framework Core does not support multiple parallel operations being run on the same DbContext instance. This
/// includes both parallel execution of async queries and any explicit concurrent use from multiple threads.
/// Therefore, always await async calls immediately, or use separate DbContext instances for operations that execute
/// in parallel. See <see href="https://aka.ms/efcore-docs-threading">Avoiding DbContext threading issues</see> for more information.
/// </para>
/// </summary>
/// <remarks>
/// See <see href="https://aka.ms/efcore-docs-saving-data">Saving data in EF Core</see> for more information.
/// </remarks>
/// <param name="acceptAllChangesOnSuccess">
/// Indicates whether <see cref="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();
SavingChanges?.Invoke(this, new SavingChangesEventArgs(acceptAllChangesOnSuccess));
var interceptionResult = DbContextDependencies.UpdateLogger.SaveChangesStarting(this);
TryDetectChanges();
try
{
var entitiesSaved = interceptionResult.HasResult
? interceptionResult.Result
: DbContextDependencies.StateManager.SaveChanges(acceptAllChangesOnSuccess);
var result = DbContextDependencies.UpdateLogger.SaveChangesCompleted(this, entitiesSaved);
SavedChanges?.Invoke(this, new SavedChangesEventArgs(acceptAllChangesOnSuccess, result));
return result;
}
catch (DbUpdateConcurrencyException exception)
{
EntityFrameworkEventSource.Log.OptimisticConcurrencyFailure();
DbContextDependencies.UpdateLogger.OptimisticConcurrencyException(this, exception);
SaveChangesFailed?.Invoke(this, new SaveChangesFailedEventArgs(acceptAllChangesOnSuccess, exception));
throw;
}
catch (Exception exception)
{
DbContextDependencies.UpdateLogger.SaveChangesFailed(this, exception);
SaveChangesFailed?.Invoke(this, new SaveChangesFailedEventArgs(acceptAllChangesOnSuccess, 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="ChangeTracker.DetectChanges" /> to discover any
/// changes to entity instances before saving to the underlying database. This can be disabled via
/// <see cref="ChangeTracker.AutoDetectChangesEnabled" />.
/// </para>
/// <para>
/// Entity Framework Core does not support multiple parallel operations being run on the same DbContext instance. This
/// includes both parallel execution of async queries and any explicit concurrent use from multiple threads.
/// Therefore, always await async calls immediately, or use separate DbContext instances for operations that execute
/// in parallel. See <see href="https://aka.ms/efcore-docs-threading">Avoiding DbContext threading issues</see> for more information.
/// </para>
/// </summary>
/// <remarks>
/// See <see href="https://aka.ms/efcore-docs-saving-data">Saving data in EF Core</see> for more information.
/// </remarks>
/// <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>
/// <exception cref="OperationCanceledException">If the <see cref="CancellationToken" /> is canceled.</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="ChangeTracker.DetectChanges" /> to discover any
/// changes to entity instances before saving to the underlying database. This can be disabled via
/// <see cref="ChangeTracker.AutoDetectChangesEnabled" />.
/// </para>
/// <para>
/// Entity Framework Core does not support multiple parallel operations being run on the same DbContext instance. This
/// includes both parallel execution of async queries and any explicit concurrent use from multiple threads.
/// Therefore, always await async calls immediately, or use separate DbContext instances for operations that execute
/// in parallel. See <see href="https://aka.ms/efcore-docs-threading">Avoiding DbContext threading issues</see> for more information.
/// </para>
/// </summary>
/// <remarks>
/// See <see href="https://aka.ms/efcore-docs-saving-data">Saving data in EF Core</see> for more information.
/// </remarks>
/// <param name="acceptAllChangesOnSuccess">
/// Indicates whether <see cref="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>
/// <exception cref="OperationCanceledException">If the <see cref="CancellationToken" /> is canceled.</exception>
public virtual async Task<int> SaveChangesAsync(
bool acceptAllChangesOnSuccess,
CancellationToken cancellationToken = default)
{
CheckDisposed();
SavingChanges?.Invoke(this, new SavingChangesEventArgs(acceptAllChangesOnSuccess));
var interceptionResult = await DbContextDependencies.UpdateLogger
.SaveChangesStartingAsync(this, cancellationToken).ConfigureAwait(acceptAllChangesOnSuccess);
TryDetectChanges();
try
{
var entitiesSaved = interceptionResult.HasResult
? interceptionResult.Result
: await DbContextDependencies.StateManager
.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken)
.ConfigureAwait(false);
var result = await DbContextDependencies.UpdateLogger
.SaveChangesCompletedAsync(this, entitiesSaved, cancellationToken)
.ConfigureAwait(false);
SavedChanges?.Invoke(this, new SavedChangesEventArgs(acceptAllChangesOnSuccess, result));
return result;
}
catch (DbUpdateConcurrencyException exception)
{
EntityFrameworkEventSource.Log.OptimisticConcurrencyFailure();
await DbContextDependencies.UpdateLogger.OptimisticConcurrencyExceptionAsync(this, exception, cancellationToken)
.ConfigureAwait(false);
SaveChangesFailed?.Invoke(this, new SaveChangesFailedEventArgs(acceptAllChangesOnSuccess, exception));
throw;
}
catch (Exception exception)
{
await DbContextDependencies.UpdateLogger.SaveChangesFailedAsync(this, exception, cancellationToken).ConfigureAwait(false);
SaveChangesFailed?.Invoke(this, new SaveChangesFailedEventArgs(acceptAllChangesOnSuccess, exception));
throw;
}
}
/// <summary>
/// An event fired at the beginning of a call to <see cref="O:SaveChanges" /> or <see cref="O:SaveChangesAsync" />
/// </summary>
/// <remarks>
/// See <see href="https://aka.ms/efcore-docs-saving-data">Saving data in EF Core</see> and
/// <see href="https://aka.ms/efcore-docs-events">EF Core events</see> for more information.
/// </remarks>
public event EventHandler<SavingChangesEventArgs>? SavingChanges;
/// <summary>
/// An event fired at the end of a call to <see cref="O:SaveChanges" /> or <see cref="O:SaveChangesAsync" />
/// </summary>
/// <remarks>
/// See <see href="https://aka.ms/efcore-docs-saving-data">Saving data in EF Core</see> and
/// <see href="https://aka.ms/efcore-docs-events">EF Core events</see> for more information.
/// </remarks>
public event EventHandler<SavedChangesEventArgs>? SavedChanges;
/// <summary>
/// An event fired if a call to <see cref="O:SaveChanges" /> or <see cref="O:SaveChangesAsync" /> fails with an exception.
/// </summary>
/// <remarks>
/// See <see href="https://aka.ms/efcore-docs-saving-data">Saving data in EF Core</see> and
/// <see href="https://aka.ms/efcore-docs-events">EF Core events</see> for more information.
/// </remarks>
public event EventHandler<SaveChangesFailedEventArgs>? SaveChangesFailed;
/// <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]
void IDbContextPoolable.ClearLease()
=> _lease = DbContextLease.InactiveLease;
/// <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]
void IDbContextPoolable.SetLease(DbContextLease lease)
{
SetLeaseInternal(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]
Task IDbContextPoolable.SetLeaseAsync(DbContextLease lease, CancellationToken cancellationToken)
{
SetLeaseInternal(lease);
return Task.CompletedTask;
}
private void SetLeaseInternal(DbContextLease lease)
{
_lease = lease;
_disposed = false;
++_leaseCount;
Check.DebugAssert(_configurationSnapshot != null, "configurationSnapshot is null");
var changeTracker = ChangeTracker;
changeTracker.AutoDetectChangesEnabled = _configurationSnapshot.AutoDetectChangesEnabled;
changeTracker.QueryTrackingBehavior = _configurationSnapshot.QueryTrackingBehavior;
changeTracker.LazyLoadingEnabled = _configurationSnapshot.LazyLoadingEnabled;
changeTracker.CascadeDeleteTiming = _configurationSnapshot.CascadeDeleteTiming;
changeTracker.DeleteOrphansTiming = _configurationSnapshot.DeleteOrphansTiming;
var database = Database;
database.AutoTransactionsEnabled = _configurationSnapshot.AutoTransactionsEnabled;
database.AutoSavepointsEnabled = _configurationSnapshot.AutoSavepointsEnabled;
SavingChanges = _configurationSnapshot.SavingChanges;
SavedChanges = _configurationSnapshot.SavedChanges;
SaveChangesFailed = _configurationSnapshot.SaveChangesFailed;
}
/// <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]
void IDbContextPoolable.SnapshotConfiguration()
{
var changeTracker = ChangeTracker;
var database = Database;
_configurationSnapshot = new DbContextPoolConfigurationSnapshot(
changeTracker.AutoDetectChangesEnabled,
changeTracker.QueryTrackingBehavior,
database.AutoTransactionsEnabled,
database.AutoSavepointsEnabled,
changeTracker.LazyLoadingEnabled,
changeTracker.CascadeDeleteTiming,
changeTracker.DeleteOrphansTiming,
SavingChanges,
SavedChanges,
SaveChangesFailed);
}
/// <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]
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>
[EntityFrameworkInternal]
async Task IResettableService.ResetStateAsync(CancellationToken cancellationToken)
{
foreach (var service in GetResettableServices())
{
await service.ResetStateAsync(cancellationToken).ConfigureAwait(false);
}
_disposed = true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private IEnumerable<IResettableService> GetResettableServices()
{
if (_cachedResettableServices is not null)
{
return _cachedResettableServices;
}
var resettableServices = new List<IResettableService>();
var services = _contextServices?.InternalServiceProvider.GetService<IEnumerable<IResettableService>>();
if (services is not null)
{
resettableServices.AddRange(services);
// Note that if the context hasn't been initialized yet, we don't cache the resettable services
// (since some services haven't been added yet).
_cachedResettableServices = resettableServices;
}
if (_sets is not null)
{
resettableServices.AddRange(_sets.Values.OfType<IResettableService>());
}
return resettableServices;
}
/// <summary>
/// Releases the allocated resources for this context.
/// </summary>
/// <remarks>
/// See <see href="https://aka.ms/efcore-docs-dbcontext">DbContext lifetime, configuration, and initialization</see>
/// for more information.
/// </remarks>
public virtual void Dispose()
{
var lease = _lease;
var contextShouldBeDisposed = lease.IsActive && _lease.IsStandalone;
if (DisposeSync(lease.IsActive, contextShouldBeDisposed))
{
_serviceScope?.Dispose();
}
lease.ContextDisposed();
}
/// <summary>
/// <para>
/// Releases the allocated resources for this context.
/// </para>
/// <para>
/// Entity Framework Core does not support multiple parallel operations being run on the same DbContext instance. This
/// includes both parallel execution of async queries and any explicit concurrent use from multiple threads.
/// Therefore, always await async calls immediately, or use separate DbContext instances for operations that execute
/// in parallel. See <see href="https://aka.ms/efcore-docs-threading">Avoiding DbContext threading issues</see>
/// for more information.
/// </para>
/// </summary>
/// <remarks>
/// See <see href="https://aka.ms/efcore-docs-dbcontext">DbContext lifetime, configuration, and initialization</see>
/// for more information.
/// </remarks>
public virtual async ValueTask DisposeAsync()
{
var lease = _lease;
var contextShouldBeDisposed = lease.IsActive && _lease.IsStandalone;
if (DisposeSync(lease.IsActive, contextShouldBeDisposed))
{
await _serviceScope.DisposeAsyncIfAvailable().ConfigureAwait(false);
}
await lease.ContextDisposedAsync().ConfigureAwait(false);
}
private bool DisposeSync(bool leaseActive, bool contextShouldBeDisposed)
{