Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[release/7.0] Reset LocalView when returning context to the pool #29181

Merged
merged 2 commits into from
Sep 22, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 8 additions & 21 deletions src/EFCore/ChangeTracking/LocalView.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,7 @@ public class LocalView<[DynamicallyAccessedMembers(IEntityType.DynamicallyAccess
INotifyCollectionChanged,
INotifyPropertyChanged,
INotifyPropertyChanging,
IListSource,
IResettableService
IListSource
where TEntity : class
{
private ObservableBackedBindingList<TEntity>? _bindingList;
Expand Down Expand Up @@ -502,13 +501,11 @@ bool IListSource.ContainsListCollection
=> false;

/// <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.
/// Resets this view, clearing any <see cref="IBindingList" /> created with <see cref="ToBindingList" /> and
/// any <see cref="ObservableCollection{T}" /> created with <see cref="ToObservableCollection" />, and clearing any
/// events registered on <see cref="PropertyChanged" />, <see cref="PropertyChanging" />, or <see cref="CollectionChanged" />.
/// </summary>
[EntityFrameworkInternal]
void IResettableService.ResetState()
public virtual void Reset()
{
_bindingList = null;
_observable = null;
Expand All @@ -517,18 +514,8 @@ void IResettableService.ResetState()
_triggeringStateManagerChange = false;
_triggeringObservableChange = false;
_triggeringLocalViewChange = false;
}

/// <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 IResettableService.ResetStateAsync(CancellationToken cancellationToken)
{
((IResettableService)this).ResetState();
return Task.CompletedTask;
PropertyChanged = null;
PropertyChanging = null;
CollectionChanged = null;
}
}
11 changes: 5 additions & 6 deletions src/EFCore/Internal/InternalDbSet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -520,20 +520,19 @@ IServiceProvider IInfrastructure<IServiceProvider>.Instance
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
void IResettableService.ResetState()
=> ((IResettableService?)_localView)?.ResetState();
=> _localView?.Reset();

/// <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>
async Task IResettableService.ResetStateAsync(CancellationToken cancellationToken)
Task IResettableService.ResetStateAsync(CancellationToken cancellationToken)
{
if (_localView != null)
{
await ((IResettableService)_localView).ResetStateAsync(cancellationToken).ConfigureAwait(false);
}
((IResettableService)this).ResetState();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can also be _localView?.Reset()


return Task.CompletedTask;
}

private EntityEntry<TEntity> EntryWithoutDetectChanges(TEntity entity)
Expand Down
87 changes: 81 additions & 6 deletions test/EFCore.SqlServer.FunctionalTests/DbContextPoolingTest.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore.Internal;
Expand Down Expand Up @@ -164,6 +167,12 @@ public class Customer
{
public string CustomerId { get; set; }
public string CompanyName { get; set; }
public ObservableCollection<Order> Orders { get; } = new();
}

public class Order
{
public string OrderId { get; set; }
}

private interface ISecondContext
Expand Down Expand Up @@ -770,6 +779,17 @@ public async Task Context_configuration_is_reset(bool useInterface, bool async)

var set = context1.Customers;
var localView = set.Local;
localView.PropertyChanged += LocalView_OnPropertyChanged;
localView.PropertyChanging += LocalView_OnPropertyChanging;
localView.CollectionChanged += LocalView_OnCollectionChanged;
var customer1 = new Customer { CustomerId = "C" };
context1.Customers.Attach(customer1);
Assert.Equal(1, localView.Count);
Assert.Same(customer1, localView.ToBindingList().Single());
Assert.Same(customer1, localView.ToObservableCollection().Single());
Assert.True(_localView_OnPropertyChanging);
Assert.True(_localView_OnPropertyChanged);
Assert.True(_localView_OnCollectionChanged);

context1.ChangeTracker.AutoDetectChangesEnabled = true;
context1.ChangeTracker.LazyLoadingEnabled = true;
Expand All @@ -791,6 +811,10 @@ public async Task Context_configuration_is_reset(bool useInterface, bool async)
context1.SavedChanges += Context_OnSavedChanges;
context1.SaveChangesFailed += Context_OnSaveChangesFailed;

_localView_OnPropertyChanging = false;
_localView_OnPropertyChanged = false;
_localView_OnCollectionChanged = false;

await Dispose(serviceScope, async);

serviceScope = serviceProvider.CreateScope();
Expand All @@ -811,9 +835,13 @@ public async Task Context_configuration_is_reset(bool useInterface, bool async)
Assert.False(context2.Database.AutoSavepointsEnabled);
Assert.Null(context1.Database.GetCommandTimeout());

var customer = new Customer { CustomerId = "C" };
context2.Customers.Attach(customer).State = EntityState.Modified;
context2.Customers.Attach(customer).State = EntityState.Unchanged;
Assert.Empty(localView);
Assert.Empty(localView.ToBindingList());
Assert.Empty(localView.ToObservableCollection());

var customer2 = new Customer { CustomerId = "C" };
context2.Customers.Attach(customer2).State = EntityState.Modified;
context2.Customers.Attach(customer2).State = EntityState.Unchanged;

Assert.False(_changeTracker_OnTracking);
Assert.False(_changeTracker_OnTracked);
Expand All @@ -832,6 +860,12 @@ public async Task Context_configuration_is_reset(bool useInterface, bool async)

Assert.Same(set, context2!.Customers);
Assert.Same(localView, context2!.Customers.Local);
Assert.Equal(1, localView.Count);
Assert.Same(customer2, localView.ToBindingList().Single());
Assert.Same(customer2, localView.ToObservableCollection().Single());
Assert.False(_localView_OnPropertyChanging);
Assert.False(_localView_OnPropertyChanged);
Assert.False(_localView_OnCollectionChanged);
}

[ConditionalTheory]
Expand Down Expand Up @@ -872,7 +906,19 @@ public async Task Context_configuration_is_reset_with_factory(bool async, bool w

var context1 = async ? await factory.CreateDbContextAsync() : factory.CreateDbContext();
var set = context1.Customers;

var localView = set.Local;
localView.PropertyChanged += LocalView_OnPropertyChanged;
localView.PropertyChanging += LocalView_OnPropertyChanging;
localView.CollectionChanged += LocalView_OnCollectionChanged;
var customer1 = new Customer { CustomerId = "C" };
context1.Customers.Attach(customer1);
Assert.Equal(1, localView.Count);
Assert.Same(customer1, localView.ToBindingList().Single());
Assert.Same(customer1, localView.ToObservableCollection().Single());
Assert.True(_localView_OnPropertyChanging);
Assert.True(_localView_OnPropertyChanged);
Assert.True(_localView_OnCollectionChanged);

context1.ChangeTracker.AutoDetectChangesEnabled = true;
context1.ChangeTracker.LazyLoadingEnabled = true;
Expand All @@ -893,15 +939,23 @@ public async Task Context_configuration_is_reset_with_factory(bool async, bool w
context1.SavedChanges += Context_OnSavedChanges;
context1.SaveChangesFailed += Context_OnSaveChangesFailed;

_localView_OnPropertyChanging = false;
_localView_OnPropertyChanged = false;
_localView_OnCollectionChanged = false;

await Dispose(context1, async);

var context2 = async ? await factory.CreateDbContextAsync() : factory.CreateDbContext();

Assert.Same(context1, context2);

var customer = new Customer { CustomerId = "C" };
context2.Customers.Attach(customer).State = EntityState.Modified;
context2.Customers.Attach(customer).State = EntityState.Unchanged;
Assert.Empty(localView);
Assert.Empty(localView.ToBindingList());
Assert.Empty(localView.ToObservableCollection());

var customer2 = new Customer { CustomerId = "C" };
context2.Customers.Attach(customer2).State = EntityState.Modified;
context2.Customers.Attach(customer2).State = EntityState.Unchanged;

Assert.False(_changeTracker_OnTracking);
Assert.False(_changeTracker_OnTracked);
Expand All @@ -920,6 +974,12 @@ public async Task Context_configuration_is_reset_with_factory(bool async, bool w

Assert.Same(set, context2!.Customers);
Assert.Same(localView, context2!.Customers.Local);
ajcvickers marked this conversation as resolved.
Show resolved Hide resolved
Assert.Equal(1, localView.Count);
Assert.Same(customer2, localView.ToBindingList().Single());
Assert.Same(customer2, localView.ToObservableCollection().Single());
Assert.False(_localView_OnPropertyChanging);
Assert.False(_localView_OnPropertyChanged);
Assert.False(_localView_OnCollectionChanged);
}

[ConditionalFact]
Expand Down Expand Up @@ -1006,6 +1066,21 @@ private void Context_OnSaveChangesFailed(object sender, SaveChangesFailedEventAr

private bool _context_OnSaveChangesFailed;

private bool _localView_OnPropertyChanged;

private void LocalView_OnPropertyChanged(object sender, PropertyChangedEventArgs e)
=> _localView_OnPropertyChanged = true;

private bool _localView_OnPropertyChanging;

private void LocalView_OnPropertyChanging(object sender, PropertyChangingEventArgs e)
=> _localView_OnPropertyChanging = true;

private bool _localView_OnCollectionChanged;

private void LocalView_OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
=> _localView_OnCollectionChanged = true;

private bool _changeTracker_OnTracking;

private void ChangeTracker_OnTracking(object sender, EntityTrackingEventArgs e)
Expand Down