From b64eafb44b732449f9de05cacde7011c0dff8d89 Mon Sep 17 00:00:00 2001 From: Arthur Vickers Date: Thu, 8 Dec 2022 11:56:48 +0000 Subject: [PATCH] Reset query tracking behavior correctly if set on DbContextOptions Port of #29766 Fixes #29733 --- src/EFCore/DbContext.cs | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/src/EFCore/DbContext.cs b/src/EFCore/DbContext.cs index db53e6bdf18..78ea16d6900 100644 --- a/src/EFCore/DbContext.cs +++ b/src/EFCore/DbContext.cs @@ -52,6 +52,9 @@ public class DbContext : IDbSetCache, IDbContextPoolable { + private static readonly bool QuirkEnabled29733 + = AppContext.TryGetSwitch("Microsoft.EntityFrameworkCore.Issue29733", out var enabled) && enabled; + private readonly DbContextOptions _options; private IDictionary<(Type Type, string? Name), object>? _sets; @@ -882,12 +885,20 @@ private void SetLeaseInternal(DbContextLease lease) || _configurationSnapshot.HasChangeTrackerConfiguration) { var changeTracker = ChangeTracker; - ((IResettableService)changeTracker).ResetState(); - changeTracker.AutoDetectChangesEnabled = _configurationSnapshot.AutoDetectChangesEnabled; - if (_configurationSnapshot.QueryTrackingBehavior.HasValue) + if (QuirkEnabled29733 + && _configurationSnapshot.QueryTrackingBehavior.HasValue) { changeTracker.QueryTrackingBehavior = _configurationSnapshot.QueryTrackingBehavior.Value; } + else + { + ((IResettableService)changeTracker).ResetState(); + if (_configurationSnapshot.QueryTrackingBehavior.HasValue) + { + changeTracker.QueryTrackingBehavior = _configurationSnapshot.QueryTrackingBehavior.Value; + } + } + changeTracker.AutoDetectChangesEnabled = _configurationSnapshot.AutoDetectChangesEnabled; changeTracker.LazyLoadingEnabled = _configurationSnapshot.LazyLoadingEnabled; changeTracker.CascadeDeleteTiming = _configurationSnapshot.CascadeDeleteTiming; changeTracker.DeleteOrphansTiming = _configurationSnapshot.DeleteOrphansTiming; @@ -944,7 +955,9 @@ void IDbContextPoolable.SnapshotConfiguration() _changeTracker != null, changeDetectorEvents != null, _changeTracker?.AutoDetectChangesEnabled ?? true, - _changeTracker?.QueryTrackingBehavior, + QuirkEnabled29733 + ? _changeTracker?.QueryTrackingBehavior ?? QueryTrackingBehavior.TrackAll + : _changeTracker?.QueryTrackingBehavior, _database?.AutoTransactionBehavior ?? AutoTransactionBehavior.WhenNeeded, _database?.AutoSavepointsEnabled ?? true, _changeTracker?.LazyLoadingEnabled ?? true,