From a8dd510a1faea8fc206eff2fe015688bac734bfb Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Fri, 23 Aug 2024 08:07:48 +0200 Subject: [PATCH] Various tweaks that came out of PG sync --- .../Storage/RelationalSqlGenerationHelper.cs | 4 +- .../EmbeddedDocumentsTest.cs | 4 +- .../TestUtilities/CosmosTestStore.cs | 5 +- .../ConfigurationPatternsTest.cs | 14 +- .../EndToEndTest.cs | 7 +- .../Query/QueryBugsInMemoryTest.cs | 76 +++---- .../Query/NullSemanticsQueryFixtureBase.cs | 20 +- .../Query/NullSemanticsQueryTestBase.cs | 9 +- .../TestUtilities/RelationalTestStore.cs | 6 +- .../MonsterFixupTestBase.cs | 9 +- .../Query/NorthwindFunctionsQueryTestBase.cs | 3 +- .../SharedStoreFixtureBase.cs | 4 +- .../TestModels/Northwind/NorthwindContext.cs | 6 +- .../TestUtilities/TestStore.cs | 13 +- .../ComputedColumnTest.cs | 7 +- .../ConnectionSpecificationTest.cs | 40 ++-- .../DefaultValuesTest.cs | 7 +- .../MemoryOptimizedTablesTest.cs | 2 +- .../SequenceEndToEndTest.cs | 7 +- .../SequentialGuidEndToEndTest.cs | 7 +- .../SqlAzure/SqlAzureDatabaseCreationTest.cs | 12 +- .../SqlServerConfigPatternsTest.cs | 24 +-- .../SqlServerDatabaseCreatorTest.cs | 52 ++--- .../SqlServerEndToEndTest.cs | 118 +++++------ .../SqlServerTypeAliasTest.cs | 2 +- ...lServerValueGenerationScenariosTestBase.cs | 191 +++++++++--------- .../TestUtilities/SqlServerTestStore.cs | 89 ++++---- .../Update/MismatchedKeyTypesSqlServerTest.cs | 7 +- .../SqliteDatabaseCreatorTest.cs | 8 +- 29 files changed, 355 insertions(+), 398 deletions(-) diff --git a/src/EFCore.Relational/Storage/RelationalSqlGenerationHelper.cs b/src/EFCore.Relational/Storage/RelationalSqlGenerationHelper.cs index bf7f9f9f483..30773f67e16 100644 --- a/src/EFCore.Relational/Storage/RelationalSqlGenerationHelper.cs +++ b/src/EFCore.Relational/Storage/RelationalSqlGenerationHelper.cs @@ -74,9 +74,7 @@ public virtual string SingleLineCommentToken /// A valid name based on the candidate name. /// public virtual string GenerateParameterName(string name) - => name.StartsWith("@", StringComparison.Ordinal) - ? name - : "@" + name; + => name.StartsWith('@') ? name : "@" + name; /// /// Writes a valid parameter name for the given candidate name. diff --git a/test/EFCore.Cosmos.FunctionalTests/EmbeddedDocumentsTest.cs b/test/EFCore.Cosmos.FunctionalTests/EmbeddedDocumentsTest.cs index ffd405b6f86..b2b6b0c8f29 100644 --- a/test/EFCore.Cosmos.FunctionalTests/EmbeddedDocumentsTest.cs +++ b/test/EFCore.Cosmos.FunctionalTests/EmbeddedDocumentsTest.cs @@ -720,8 +720,8 @@ protected override object GetAdditionalModelCacheKey(DbContext context) public Task InitializeAsync() => Task.CompletedTask; - public Task DisposeAsync() - => TestStore.DisposeAsync(); + public async Task DisposeAsync() + => await TestStore.DisposeAsync(); } public record class EmbeddedTransportationContextOptions(DbContextOptions Options, Action OnModelCreating); diff --git a/test/EFCore.Cosmos.FunctionalTests/TestUtilities/CosmosTestStore.cs b/test/EFCore.Cosmos.FunctionalTests/TestUtilities/CosmosTestStore.cs index 4b2c755da80..79ebcaeb66a 100644 --- a/test/EFCore.Cosmos.FunctionalTests/TestUtilities/CosmosTestStore.cs +++ b/test/EFCore.Cosmos.FunctionalTests/TestUtilities/CosmosTestStore.cs @@ -507,10 +507,7 @@ private static async Task SeedAsync(DbContext context) await creator.SeedDataAsync(created: true).ConfigureAwait(false); } - public override void Dispose() - => throw new InvalidOperationException("Calling Dispose can cause deadlocks. Use DisposeAsync instead."); - - public override async Task DisposeAsync() + public override async ValueTask DisposeAsync() { if (_initialized && _dataFilePath == null) diff --git a/test/EFCore.CrossStore.FunctionalTests/ConfigurationPatternsTest.cs b/test/EFCore.CrossStore.FunctionalTests/ConfigurationPatternsTest.cs index c2cb66619a2..4bb95ee5669 100644 --- a/test/EFCore.CrossStore.FunctionalTests/ConfigurationPatternsTest.cs +++ b/test/EFCore.CrossStore.FunctionalTests/ConfigurationPatternsTest.cs @@ -288,19 +288,13 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) public async Task InitializeAsync() => ExistingTestStore = await Fixture.CreateTestStoreAsync(SqlServerTestStoreFactory.Instance, StoreName, SeedAsync); - public Task DisposeAsync() - { - ExistingTestStore.Dispose(); - return Task.CompletedTask; - } + public async Task DisposeAsync() + => await ExistingTestStore.DisposeAsync(); } public async Task InitializeAsync() => ExistingTestStore = await Fixture.CreateTestStoreAsync(SqlServerTestStoreFactory.Instance, StoreName, SeedAsync); - public Task DisposeAsync() - { - ExistingTestStore.Dispose(); - return Task.CompletedTask; - } + public async Task DisposeAsync() + => await ExistingTestStore.DisposeAsync(); } diff --git a/test/EFCore.CrossStore.FunctionalTests/EndToEndTest.cs b/test/EFCore.CrossStore.FunctionalTests/EndToEndTest.cs index 083b173aadc..68ac9800ab0 100644 --- a/test/EFCore.CrossStore.FunctionalTests/EndToEndTest.cs +++ b/test/EFCore.CrossStore.FunctionalTests/EndToEndTest.cs @@ -64,11 +64,8 @@ protected CrossStoreContext CreateContext() public async Task InitializeAsync() => TestStore = await Fixture.CreateTestStoreAsync(TestStoreFactory, "CrossStoreTest"); - public Task DisposeAsync() - { - TestStore.Dispose(); - return Task.CompletedTask; - } + public async Task DisposeAsync() + => await TestStore.DisposeAsync(); } public class InMemoryEndToEndTest(CrossStoreFixture fixture) : EndToEndTest(fixture), IClassFixture diff --git a/test/EFCore.InMemory.FunctionalTests/Query/QueryBugsInMemoryTest.cs b/test/EFCore.InMemory.FunctionalTests/Query/QueryBugsInMemoryTest.cs index d9228539327..82fbe1c909a 100644 --- a/test/EFCore.InMemory.FunctionalTests/Query/QueryBugsInMemoryTest.cs +++ b/test/EFCore.InMemory.FunctionalTests/Query/QueryBugsInMemoryTest.cs @@ -16,7 +16,7 @@ public class QueryBugsInMemoryTest : IClassFixture [ConditionalFact] public virtual async Task Include_throw_when_empty_9849() { - using (await CreateScratchAsync(_ => Task.CompletedTask, "9849")) + await using (await CreateScratchAsync(_ => Task.CompletedTask, "9849")) { using var context = new DatabaseContext(); var results = context.VehicleInspections.Include(_ => _.Motors).ToList(); @@ -28,7 +28,7 @@ public virtual async Task Include_throw_when_empty_9849() [ConditionalFact] public virtual async Task Include_throw_when_empty_9849_2() { - using (await CreateScratchAsync(_ => Task.CompletedTask, "9849")) + await using (await CreateScratchAsync(_ => Task.CompletedTask, "9849")) { using var context = new DatabaseContext(); #pragma warning disable IDE1006 // Naming Styles @@ -42,7 +42,7 @@ public virtual async Task Include_throw_when_empty_9849_2() [ConditionalFact] public virtual async Task Include_throw_when_empty_9849_3() { - using (await CreateScratchAsync(_ => Task.CompletedTask, "9849")) + await using (await CreateScratchAsync(_ => Task.CompletedTask, "9849")) { using var context = new DatabaseContext(); #pragma warning disable IDE1006 // Naming Styles @@ -56,7 +56,7 @@ public virtual async Task Include_throw_when_empty_9849_3() [ConditionalFact] public virtual async Task Include_throw_when_empty_9849_4() { - using (await CreateScratchAsync(_ => Task.CompletedTask, "9849")) + await using (await CreateScratchAsync(_ => Task.CompletedTask, "9849")) { using var context = new DatabaseContext(); #pragma warning disable IDE1006 // Naming Styles @@ -70,7 +70,7 @@ public virtual async Task Include_throw_when_empty_9849_4() [ConditionalFact] public virtual async Task Include_throw_when_empty_9849_5() { - using (await CreateScratchAsync(_ => Task.CompletedTask, "9849")) + await using (await CreateScratchAsync(_ => Task.CompletedTask, "9849")) { using var context = new DatabaseContext(); var results @@ -86,7 +86,7 @@ join __ in context.VehicleInspections on _f.Id equals __.Id [ConditionalFact] public virtual async Task Include_throw_when_empty_9849_6() { - using (await CreateScratchAsync(_ => Task.CompletedTask, "9849")) + await using (await CreateScratchAsync(_ => Task.CompletedTask, "9849")) { using var context = new DatabaseContext(); #pragma warning disable IDE1006 // Naming Styles @@ -146,7 +146,7 @@ private class Motor [ConditionalFact] public virtual async Task GroupBy_with_uninitialized_datetime_projection_3595() { - using (await CreateScratchAsync(Seed3595, "3595")) + await using (await CreateScratchAsync(Seed3595, "3595")) { using var context = new Context3595(); var q0 = from instance in context.Exams @@ -224,7 +224,7 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) [ConditionalFact] public virtual async Task Repro3101_simple_coalesce1() { - using (await CreateScratchAsync(Seed3101, "3101")) + await using (await CreateScratchAsync(Seed3101, "3101")) { using var ctx = new MyContext3101(); var query = from eVersion in ctx.Entities @@ -241,7 +241,7 @@ from eRootJoined in RootEntities.DefaultIfEmpty() [ConditionalFact] public virtual async Task Repro3101_simple_coalesce2() { - using (await CreateScratchAsync(Seed3101, "3101")) + await using (await CreateScratchAsync(Seed3101, "3101")) { using var ctx = new MyContext3101(); var query = from eVersion in ctx.Entities @@ -259,7 +259,7 @@ from eRootJoined in RootEntities.DefaultIfEmpty() [ConditionalFact] public virtual async Task Repro3101_simple_coalesce3() { - using (await CreateScratchAsync(Seed3101, "3101")) + await using (await CreateScratchAsync(Seed3101, "3101")) { using var ctx = new MyContext3101(); var query = from eVersion in ctx.Entities.Include(e => e.Children) @@ -278,7 +278,7 @@ from eRootJoined in RootEntities.DefaultIfEmpty() [ConditionalFact] public virtual async Task Repro3101_complex_coalesce1() { - using (await CreateScratchAsync(Seed3101, "3101")) + await using (await CreateScratchAsync(Seed3101, "3101")) { using var ctx = new MyContext3101(); var query = from eVersion in ctx.Entities.Include(e => e.Children) @@ -296,7 +296,7 @@ from eRootJoined in RootEntities.DefaultIfEmpty() [ConditionalFact] public virtual async Task Repro3101_complex_coalesce2() { - using (await CreateScratchAsync(Seed3101, "3101")) + await using (await CreateScratchAsync(Seed3101, "3101")) { using var ctx = new MyContext3101(); var query = from eVersion in ctx.Entities @@ -314,7 +314,7 @@ from eRootJoined in RootEntities.DefaultIfEmpty() [ConditionalFact] public virtual async Task Repro3101_nested_coalesce1() { - using (await CreateScratchAsync(Seed3101, "3101")) + await using (await CreateScratchAsync(Seed3101, "3101")) { using var ctx = new MyContext3101(); var query = from eVersion in ctx.Entities @@ -332,7 +332,7 @@ from eRootJoined in RootEntities.DefaultIfEmpty() [ConditionalFact] public virtual async Task Repro3101_nested_coalesce2() { - using (await CreateScratchAsync(Seed3101, "3101")) + await using (await CreateScratchAsync(Seed3101, "3101")) { using var ctx = new MyContext3101(); var query = from eVersion in ctx.Entities.Include(e => e.Children) @@ -355,7 +355,7 @@ from eRootJoined in RootEntities.DefaultIfEmpty() [ConditionalFact] public virtual async Task Repro3101_conditional() { - using (await CreateScratchAsync(Seed3101, "3101")) + await using (await CreateScratchAsync(Seed3101, "3101")) { using var ctx = new MyContext3101(); var query = from eVersion in ctx.Entities.Include(e => e.Children) @@ -375,7 +375,7 @@ from eRootJoined in RootEntities.DefaultIfEmpty() [ConditionalFact] public virtual async Task Repro3101_coalesce_tracking() { - using (await CreateScratchAsync(Seed3101, "3101")) + await using (await CreateScratchAsync(Seed3101, "3101")) { using var ctx = new MyContext3101(); var query = from eVersion in ctx.Entities @@ -459,7 +459,7 @@ private class Child3101 [ConditionalFact] public virtual async Task Repro5456_include_group_join_is_per_query_context() { - using (await CreateScratchAsync(Seed5456, "5456")) + await using (await CreateScratchAsync(Seed5456, "5456")) { Parallel.For( 0, 10, i => @@ -475,7 +475,7 @@ public virtual async Task Repro5456_include_group_join_is_per_query_context() [ConditionalFact] public virtual async Task Repro5456_include_group_join_is_per_query_context_async() { - using (await CreateScratchAsync(Seed5456, "5456")) + await using (await CreateScratchAsync(Seed5456, "5456")) { var tasks = new List(); for (var i = 0; i < 10; i++) @@ -498,7 +498,7 @@ async Task Action() [ConditionalFact] public virtual async Task Repro5456_multiple_include_group_join_is_per_query_context() { - using (await CreateScratchAsync(Seed5456, "5456")) + await using (await CreateScratchAsync(Seed5456, "5456")) { Parallel.For( 0, 10, i => @@ -514,7 +514,7 @@ public virtual async Task Repro5456_multiple_include_group_join_is_per_query_con [ConditionalFact] public virtual async Task Repro5456_multiple_include_group_join_is_per_query_context_async() { - using (await CreateScratchAsync(Seed5456, "5456")) + await using (await CreateScratchAsync(Seed5456, "5456")) { var tasks = new List(); for (var i = 0; i < 10; i++) @@ -538,7 +538,7 @@ async Task Action() [ConditionalFact] public virtual async Task Repro5456_multi_level_include_group_join_is_per_query_context() { - using (await CreateScratchAsync(Seed5456, "5456")) + await using (await CreateScratchAsync(Seed5456, "5456")) { Parallel.For( 0, 10, i => @@ -554,7 +554,7 @@ public virtual async Task Repro5456_multi_level_include_group_join_is_per_query_ [ConditionalFact] public virtual async Task Repro5456_multi_level_include_group_join_is_per_query_context_async() { - using (await CreateScratchAsync(Seed5456, "5456")) + await using (await CreateScratchAsync(Seed5456, "5456")) { var tasks = new List(); for (var i = 0; i < 10; i++) @@ -642,7 +642,7 @@ private class Comment5456 [ConditionalFact] public virtual async Task Entity_passed_to_DTO_constructor_works() { - using (await CreateScratchAsync(_ => Task.CompletedTask, "8282")) + await using (await CreateScratchAsync(_ => Task.CompletedTask, "8282")) { using var context = new MyContext8282(); var query = context.Entity.Select(e => new EntityDto8282(e)).ToList(); @@ -679,7 +679,7 @@ private class EntityDto8282(Entity8282 entity) [ConditionalFact] public virtual async Task Select_enumerable_navigation_backed_by_collection() { - using (await CreateScratchAsync(Seed21803, "21803")) + await using (await CreateScratchAsync(Seed21803, "21803")) { using var context = new MyContext21803(); @@ -734,7 +734,7 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) [ConditionalFact] public virtual async Task Multiple_owned_references_at_same_level_maintains_valueBuffer_positions() { - using (await CreateScratchAsync(Seed20729, "20729")) + await using (await CreateScratchAsync(Seed20729, "20729")) { using var context = new MyContext20729(); @@ -812,7 +812,7 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) [ConditionalFact] public virtual async Task Owned_reference_on_base_with_hierarchy() { - using (await CreateScratchAsync(Seed23285, "23285")) + await using (await CreateScratchAsync(Seed23285, "23285")) { using var context = new MyContext23285(); @@ -877,7 +877,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) [ConditionalFact] public virtual async Task Owned_reference_with_composite_key() { - using (await CreateScratchAsync(Seed23687, "23687")) + await using (await CreateScratchAsync(Seed23687, "23687")) { using var context = new MyContext23687(); @@ -938,7 +938,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) [ConditionalFact] public virtual async Task Join_with_enum_as_key_selector() { - using (await CreateScratchAsync(Seed23593, "23593")) + await using (await CreateScratchAsync(Seed23593, "23593")) { using var context = new MyContext23593(); @@ -954,7 +954,7 @@ join sme in context.StatusMapEvents on sm.Id equals sme.Id [ConditionalFact] public virtual async Task Join_with_enum_inside_anonymous_type_as_key_selector() { - using (await CreateScratchAsync(Seed23593, "23593")) + await using (await CreateScratchAsync(Seed23593, "23593")) { using var context = new MyContext23593(); @@ -970,7 +970,7 @@ public virtual async Task Join_with_enum_inside_anonymous_type_as_key_selector() [ConditionalFact] public virtual async Task Join_with_enum_inside_anonymous_type_with_other_property_as_key_selector() { - using (await CreateScratchAsync(Seed23593, "23593")) + await using (await CreateScratchAsync(Seed23593, "23593")) { using var context = new MyContext23593(); @@ -1031,7 +1031,7 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) [ConditionalFact] public virtual async Task Left_join_with_entity_with_enum_discriminator() { - using (await CreateScratchAsync(Seed23926, "23926")) + await using (await CreateScratchAsync(Seed23926, "23926")) { using var context = new MyContext23926(); @@ -1098,7 +1098,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) [ConditionalFact] public virtual async Task Shared_owned_property_on_multiple_level_in_Select() { - using (await CreateScratchAsync(Seed18435, "18435")) + await using (await CreateScratchAsync(Seed18435, "18435")) { using var context = new MyContext18435(); @@ -1188,7 +1188,7 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) [ConditionalFact(Skip = "Issue#19425")] public virtual async Task Non_nullable_cast_in_null_check() { - using (await CreateScratchAsync(Seed19425, "19425")) + await using (await CreateScratchAsync(Seed19425, "19425")) { using var context = new MyContext19425(); @@ -1236,7 +1236,7 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) [ConditionalFact] public virtual async Task Property_access_on_nullable_converted_scalar_type() { - using (await CreateScratchAsync(Seed19667, "19667")) + await using (await CreateScratchAsync(Seed19667, "19667")) { using var context = new MyContext19667(); @@ -1285,7 +1285,7 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) [ConditionalFact] public virtual async Task Changing_order_of_projection_in_anonymous_type_works() { - using (await CreateScratchAsync(Seed20359, "20359")) + await using (await CreateScratchAsync(Seed20359, "20359")) { using var context = new MyContext20359(); @@ -1372,7 +1372,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) [ConditionalFact] public virtual async Task Union_with_different_property_name_using_same_anonymous_type() { - using (await CreateScratchAsync(Seed23360, "23360")) + await using (await CreateScratchAsync(Seed23360, "23360")) { using var context = new MyContext23360(); @@ -1460,7 +1460,7 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) [ConditionalFact] public virtual async Task Ordering_of_collection_result_is_correct() { - using (await CreateScratchAsync(Seed18394, "18394")) + await using (await CreateScratchAsync(Seed18394, "18394")) { using var context = new MyContext18394(); @@ -1565,7 +1565,7 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) [ConditionalFact] public virtual async Task Owned_entity_indexes_are_maintained_properly() { - using (await CreateScratchAsync(Seed23934, "23934")) + await using (await CreateScratchAsync(Seed23934, "23934")) { using var context = new MyContext23934(); diff --git a/test/EFCore.Relational.Specification.Tests/Query/NullSemanticsQueryFixtureBase.cs b/test/EFCore.Relational.Specification.Tests/Query/NullSemanticsQueryFixtureBase.cs index 81779164442..e820bc253e1 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/NullSemanticsQueryFixtureBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/NullSemanticsQueryFixtureBase.cs @@ -122,26 +122,24 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con modelBuilder.Entity().Property(e => e.StringC).IsRequired(); modelBuilder.HasDbFunction( - typeof(NullSemanticsQueryFixtureBase).GetMethod(nameof(Cases)), + typeof(NullSemanticsQueryFixtureBase).GetMethod(nameof(Cases))!, b => b.HasTranslation( args => new CaseExpression( [ new CaseWhenClause(args[0], args[1]), new CaseWhenClause(args[2], args[3]), - new CaseWhenClause(args[4], args[5]), - ])) - ); + new CaseWhenClause(args[4], args[5]) + ]))); modelBuilder.HasDbFunction( - typeof(NullSemanticsQueryFixtureBase).GetMethod(nameof(BoolSwitch)), + typeof(NullSemanticsQueryFixtureBase).GetMethod(nameof(BoolSwitch))!, b => b.HasTranslation( args => new CaseExpression( operand: args[0], [ new CaseWhenClause(new SqlConstantExpression(true, typeMapping: BoolTypeMapping.Default), args[1]), - new CaseWhenClause(new SqlConstantExpression(false, typeMapping: BoolTypeMapping.Default), args[2]), - ])) - ); + new CaseWhenClause(new SqlConstantExpression(false, typeMapping: BoolTypeMapping.Default), args[2]) + ]))); } public static int? Cases(bool c1, int v1, bool c2, int v2, bool c3, int v3) @@ -151,9 +149,5 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con null; public static int BoolSwitch(bool x, int whenTrue, int whenFalse) - => x switch - { - true => whenTrue, - false => whenFalse, - }; + => x ? whenTrue : whenFalse; } diff --git a/test/EFCore.Relational.Specification.Tests/Query/NullSemanticsQueryTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/NullSemanticsQueryTestBase.cs index 4ac99509883..6ce93abfd78 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/NullSemanticsQueryTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/NullSemanticsQueryTestBase.cs @@ -1973,8 +1973,7 @@ public virtual Task CaseWhen_equal_to_first_or_third_select(bool async) x.StringC == "Foo", 3 ) == 3), - assertOrder: true - ); + assertOrder: true); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] @@ -1985,10 +1984,8 @@ public virtual Task CaseOpWhen_projection(bool async) .OrderBy(x => x.Id) .Select( x => NullSemanticsQueryFixtureBase.BoolSwitch( - x.StringA == "Foo", 3, 2 - )), - assertOrder: true - ); + x.StringA == "Foo", 3, 2)), + assertOrder: true); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] diff --git a/test/EFCore.Relational.Specification.Tests/TestUtilities/RelationalTestStore.cs b/test/EFCore.Relational.Specification.Tests/TestUtilities/RelationalTestStore.cs index 84b476f631a..adcec5650b5 100644 --- a/test/EFCore.Relational.Specification.Tests/TestUtilities/RelationalTestStore.cs +++ b/test/EFCore.Relational.Specification.Tests/TestUtilities/RelationalTestStore.cs @@ -44,10 +44,10 @@ public override async Task InitializeAsync( return this; } - public override void Dispose() + public override async ValueTask DisposeAsync() { - Connection?.Dispose(); - base.Dispose(); + await Connection.DisposeAsync(); + await base.DisposeAsync(); } public virtual string NormalizeDelimitersInRawString(string sql) diff --git a/test/EFCore.Specification.Tests/MonsterFixupTestBase.cs b/test/EFCore.Specification.Tests/MonsterFixupTestBase.cs index 91244c56db7..590ec78737d 100644 --- a/test/EFCore.Specification.Tests/MonsterFixupTestBase.cs +++ b/test/EFCore.Specification.Tests/MonsterFixupTestBase.cs @@ -10,7 +10,7 @@ namespace Microsoft.EntityFrameworkCore; #nullable disable -public abstract class MonsterFixupTestBase : IClassFixture, IDisposable +public abstract class MonsterFixupTestBase : IClassFixture, IAsyncLifetime where TFixture : MonsterFixupTestBase.MonsterFixupFixtureBase, new() { protected MonsterFixupTestBase(TFixture fixture) @@ -1405,8 +1405,11 @@ protected Task CreateAndSeedDatabase(Func seed) protected MonsterContext CreateContext() => Fixture.CreateContext(Options); - public virtual void Dispose() - => TestStore.Dispose(); + public Task InitializeAsync() + => Task.CompletedTask; + + public virtual async Task DisposeAsync() + => await TestStore.DisposeAsync(); public abstract class MonsterFixupFixtureBase : ServiceProviderFixtureBase { diff --git a/test/EFCore.Specification.Tests/Query/NorthwindFunctionsQueryTestBase.cs b/test/EFCore.Specification.Tests/Query/NorthwindFunctionsQueryTestBase.cs index 81015e204f9..39af9e8322f 100644 --- a/test/EFCore.Specification.Tests/Query/NorthwindFunctionsQueryTestBase.cs +++ b/test/EFCore.Specification.Tests/Query/NorthwindFunctionsQueryTestBase.cs @@ -362,7 +362,8 @@ public virtual Task String_Join_with_predicate(bool async) .Select( g => new { - City = g.Key, Customers = string.Join("|", g.Where(e => e.ContactName.Length > 10).Select(e => e.CustomerID)) + City = g.Key, + Customers = string.Join("|", g.Where(e => e.ContactName.Length > 10).Select(e => e.CustomerID)) }), elementSorter: x => x.City, elementAsserter: (e, a) => diff --git a/test/EFCore.Specification.Tests/SharedStoreFixtureBase.cs b/test/EFCore.Specification.Tests/SharedStoreFixtureBase.cs index 226300402d7..6fed8e56418 100644 --- a/test/EFCore.Specification.Tests/SharedStoreFixtureBase.cs +++ b/test/EFCore.Specification.Tests/SharedStoreFixtureBase.cs @@ -111,6 +111,6 @@ protected virtual Task CleanAsync(DbContext context) return Task.CompletedTask; } - public virtual Task DisposeAsync() - => TestStore.DisposeAsync(); + public virtual async Task DisposeAsync() + => await TestStore.DisposeAsync(); } diff --git a/test/EFCore.Specification.Tests/TestModels/Northwind/NorthwindContext.cs b/test/EFCore.Specification.Tests/TestModels/Northwind/NorthwindContext.cs index 9d2357038fe..7e63a90966a 100644 --- a/test/EFCore.Specification.Tests/TestModels/Northwind/NorthwindContext.cs +++ b/test/EFCore.Specification.Tests/TestModels/Northwind/NorthwindContext.cs @@ -75,11 +75,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) }); modelBuilder.Entity( - e => - { - e.HasKey( - od => new { od.OrderID, od.ProductID }); - }); + e => e.HasKey(od => new { od.OrderID, od.ProductID })); modelBuilder.Entity().HasNoKey(); modelBuilder.Entity().HasNoKey(); diff --git a/test/EFCore.Specification.Tests/TestUtilities/TestStore.cs b/test/EFCore.Specification.Tests/TestUtilities/TestStore.cs index bf2c333fd80..035197a2d59 100644 --- a/test/EFCore.Specification.Tests/TestUtilities/TestStore.cs +++ b/test/EFCore.Specification.Tests/TestUtilities/TestStore.cs @@ -5,7 +5,7 @@ namespace Microsoft.EntityFrameworkCore.TestUtilities; -public abstract class TestStore(string name, bool shared) : IDisposable +public abstract class TestStore(string name, bool shared) : IAsyncDisposable { private static readonly TestStoreIndex GlobalTestStoreIndex = new(); public IServiceProvider? ServiceProvider { get; protected set; } @@ -83,15 +83,8 @@ protected virtual DbContext CreateDefaultContext() protected virtual TestStoreIndex GetTestStoreIndex(IServiceProvider? serviceProvider) => GlobalTestStoreIndex; - public virtual void Dispose() - { - } - - public virtual Task DisposeAsync() - { - Dispose(); - return Task.CompletedTask; - } + public virtual ValueTask DisposeAsync() + => default; private static readonly SemaphoreSlim _transactionSyncRoot = new(1); diff --git a/test/EFCore.SqlServer.FunctionalTests/ComputedColumnTest.cs b/test/EFCore.SqlServer.FunctionalTests/ComputedColumnTest.cs index 009d5739827..fd0c4fd5021 100644 --- a/test/EFCore.SqlServer.FunctionalTests/ComputedColumnTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/ComputedColumnTest.cs @@ -133,9 +133,6 @@ public void Can_use_computed_columns_with_nullable_enum() public async Task InitializeAsync() => TestStore = await SqlServerTestStore.CreateInitializedAsync("ComputedColumnTest"); - public Task DisposeAsync() - { - TestStore.Dispose(); - return Task.CompletedTask; - } + public async Task DisposeAsync() + => await TestStore.DisposeAsync(); } diff --git a/test/EFCore.SqlServer.FunctionalTests/ConnectionSpecificationTest.cs b/test/EFCore.SqlServer.FunctionalTests/ConnectionSpecificationTest.cs index 5e25523b0ef..f641b8c3c56 100644 --- a/test/EFCore.SqlServer.FunctionalTests/ConnectionSpecificationTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/ConnectionSpecificationTest.cs @@ -22,7 +22,7 @@ var serviceProvider .AddDbContext() .BuildServiceProvider(validateScopes: true); - using (await SqlServerTestStore.GetNorthwindStoreAsync()) + await using (await SqlServerTestStore.GetNorthwindStoreAsync()) { using var scope = serviceProvider.CreateScope(); var context = scope.ServiceProvider.GetRequiredService(); @@ -36,7 +36,7 @@ var serviceProvider [ConditionalFact] public async Task Can_specify_no_connection_string_in_OnConfiguring_with_default_service_provider() { - using (await SqlServerTestStore.GetNorthwindStoreAsync()) + await using (await SqlServerTestStore.GetNorthwindStoreAsync()) { using var context = new NoneInOnConfiguringContext(); @@ -49,7 +49,7 @@ public async Task Can_specify_no_connection_string_in_OnConfiguring_with_default [ConditionalFact] public async Task Throws_if_context_used_with_no_connection_or_connection_string() { - using (await SqlServerTestStore.GetNorthwindStoreAsync()) + await using (await SqlServerTestStore.GetNorthwindStoreAsync()) { using var context = new NoneInOnConfiguringContext(); @@ -73,7 +73,7 @@ var serviceProvider .AddDbContext() .BuildServiceProvider(validateScopes: true); - using (await SqlServerTestStore.GetNorthwindStoreAsync()) + await using (await SqlServerTestStore.GetNorthwindStoreAsync()) { using var scope = serviceProvider.CreateScope(); var context = scope.ServiceProvider.GetRequiredService(); @@ -84,7 +84,7 @@ var serviceProvider [ConditionalFact] public async Task Can_specify_connection_string_in_OnConfiguring_with_default_service_provider() { - using (await SqlServerTestStore.GetNorthwindStoreAsync()) + await using (await SqlServerTestStore.GetNorthwindStoreAsync()) { using var context = new StringInOnConfiguringContext(); Assert.True(await context.Customers.AnyAsync()); @@ -111,7 +111,7 @@ var serviceProvider SqlConnection connection; - using (await SqlServerTestStore.GetNorthwindStoreAsync()) + await using (await SqlServerTestStore.GetNorthwindStoreAsync()) { using var scope = serviceProvider.CreateScope(); var context = scope.ServiceProvider.GetRequiredService(); @@ -141,7 +141,7 @@ public async Task Can_specify_no_connection_in_OnConfiguring_with_default_servic { SqlConnection connection; - using (await SqlServerTestStore.GetNorthwindStoreAsync()) + await using (await SqlServerTestStore.GetNorthwindStoreAsync()) { using var context = new NoneInOnConfiguringContext(); @@ -171,7 +171,7 @@ var serviceProvider .AddScoped(p => new SqlConnection(SqlServerNorthwindTestStoreFactory.NorthwindConnectionString)) .AddDbContext().BuildServiceProvider(validateScopes: true); - using (await SqlServerTestStore.GetNorthwindStoreAsync()) + await using (await SqlServerTestStore.GetNorthwindStoreAsync()) { using var scope = serviceProvider.CreateScope(); var context = scope.ServiceProvider.GetRequiredService(); @@ -182,7 +182,7 @@ var serviceProvider [ConditionalFact] public async Task Can_specify_connection_in_OnConfiguring_with_default_service_provider() { - using (await SqlServerTestStore.GetNorthwindStoreAsync()) + await using (await SqlServerTestStore.GetNorthwindStoreAsync()) { using var connection = new SqlConnection(SqlServerNorthwindTestStoreFactory.NorthwindConnectionString); using var context = new ConnectionInOnConfiguringContext(connection); @@ -201,7 +201,7 @@ var serviceProvider SqlConnection connection; - using (await SqlServerTestStore.GetNorthwindStoreAsync()) + await using (await SqlServerTestStore.GetNorthwindStoreAsync()) { connection = serviceProvider.GetRequiredService(); @@ -218,7 +218,7 @@ public async Task Can_specify_owned_connection_in_OnConfiguring_with_default_ser { SqlConnection connection; - using (await SqlServerTestStore.GetNorthwindStoreAsync()) + await using (await SqlServerTestStore.GetNorthwindStoreAsync()) { connection = new SqlConnection(SqlServerNorthwindTestStoreFactory.NorthwindConnectionString); using var context = new OwnedConnectionInOnConfiguringContext(connection); @@ -239,7 +239,7 @@ var serviceProvider .AddScoped(p => connection) .AddDbContext().BuildServiceProvider(validateScopes: true); - using (await SqlServerTestStore.GetNorthwindStoreAsync()) + await using (await SqlServerTestStore.GetNorthwindStoreAsync()) { using var scope = serviceProvider.CreateScope(); var context = scope.ServiceProvider.GetRequiredService(); @@ -265,7 +265,7 @@ var serviceProvider .AddScoped(p => connection) .AddDbContext().BuildServiceProvider(validateScopes: true); - using (await SqlServerTestStore.GetNorthwindStoreAsync()) + await using (await SqlServerTestStore.GetNorthwindStoreAsync()) { using var scope = serviceProvider.CreateScope(); var context = scope.ServiceProvider.GetRequiredService(); @@ -292,7 +292,7 @@ var serviceProvider .AddScoped(p => connection) .AddDbContext().BuildServiceProvider(validateScopes: true); - using (await SqlServerTestStore.GetNorthwindStoreAsync()) + await using (await SqlServerTestStore.GetNorthwindStoreAsync()) { using var scope = serviceProvider.CreateScope(); var context = scope.ServiceProvider.GetRequiredService(); @@ -378,7 +378,7 @@ var serviceProvider .AddDbContext() .BuildServiceProvider(validateScopes: true); - using (await SqlServerTestStore.GetNorthwindStoreAsync()) + await using (await SqlServerTestStore.GetNorthwindStoreAsync()) { using var scope = serviceProvider.CreateScope(); var context = scope.ServiceProvider.GetRequiredService(); @@ -389,7 +389,7 @@ var serviceProvider [ConditionalFact] public async Task Can_depend_on_DbContextOptions_with_default_service_provider() { - using (await SqlServerTestStore.GetNorthwindStoreAsync()) + await using (await SqlServerTestStore.GetNorthwindStoreAsync()) { using var connection = new SqlConnection(SqlServerNorthwindTestStoreFactory.NorthwindConnectionString); @@ -432,7 +432,7 @@ var serviceProvider .AddDbContext() .BuildServiceProvider(validateScopes: true); - using (await SqlServerTestStore.GetNorthwindStoreAsync()) + await using (await SqlServerTestStore.GetNorthwindStoreAsync()) { using var scope = serviceProvider.CreateScope(); var context = scope.ServiceProvider.GetRequiredService(); @@ -443,7 +443,7 @@ var serviceProvider [ConditionalFact] public async Task Can_depend_on_non_generic_options_when_only_one_context_with_default_service_provider() { - using (await SqlServerTestStore.GetNorthwindStoreAsync()) + await using (await SqlServerTestStore.GetNorthwindStoreAsync()) { using var context = new NonGenericOptionsContext(new DbContextOptions()); Assert.True(await context.Customers.AnyAsync()); @@ -483,7 +483,7 @@ var serviceProvider b => b.UseSqlServer(connectionString).EnableServiceProviderCaching(false)) .BuildServiceProvider(validateScopes: true); - using (await SqlServerTestStore.GetNorthwindStoreAsync()) + await using (await SqlServerTestStore.GetNorthwindStoreAsync()) { using var serviceScope = serviceProvider.GetRequiredService().CreateScope(); using var context = serviceScope.ServiceProvider.GetRequiredService(); @@ -535,7 +535,7 @@ public async Task Can_use_an_existing_closed_connection_test(bool openConnection .AddEntityFrameworkSqlServer() .BuildServiceProvider(validateScopes: true); - using var store = await SqlServerTestStore.GetNorthwindStoreAsync(); + await using var store = await SqlServerTestStore.GetNorthwindStoreAsync(); store.CloseConnection(); var openCount = 0; diff --git a/test/EFCore.SqlServer.FunctionalTests/DefaultValuesTest.cs b/test/EFCore.SqlServer.FunctionalTests/DefaultValuesTest.cs index ef03987f5b1..07cf0c41aee 100644 --- a/test/EFCore.SqlServer.FunctionalTests/DefaultValuesTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/DefaultValuesTest.cs @@ -91,9 +91,6 @@ private class Chipper public async Task InitializeAsync() => TestStore = await SqlServerTestStore.CreateInitializedAsync("DefaultValuesTest"); - public Task DisposeAsync() - { - TestStore.Dispose(); - return Task.CompletedTask; - } + public async Task DisposeAsync() + => await TestStore.DisposeAsync(); } diff --git a/test/EFCore.SqlServer.FunctionalTests/MemoryOptimizedTablesTest.cs b/test/EFCore.SqlServer.FunctionalTests/MemoryOptimizedTablesTest.cs index e834f928fba..c51639e7a24 100644 --- a/test/EFCore.SqlServer.FunctionalTests/MemoryOptimizedTablesTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/MemoryOptimizedTablesTest.cs @@ -19,7 +19,7 @@ public class MemoryOptimizedTablesTest(MemoryOptimizedTablesTest.MemoryOptimized [ConditionalFact] public async Task Can_create_memoryOptimized_table() { - using (await CreateTestStoreAsync()) + await using (await CreateTestStoreAsync()) { var bigUn = new BigUn(); var fastUns = new[] { new FastUn { Name = "First 'un", BigUn = bigUn }, new FastUn { Name = "Second 'un", BigUn = bigUn } }; diff --git a/test/EFCore.SqlServer.FunctionalTests/SequenceEndToEndTest.cs b/test/EFCore.SqlServer.FunctionalTests/SequenceEndToEndTest.cs index c27a01857bc..a04349cb6d8 100644 --- a/test/EFCore.SqlServer.FunctionalTests/SequenceEndToEndTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/SequenceEndToEndTest.cs @@ -408,9 +408,6 @@ private class Unicon public async Task InitializeAsync() => TestStore = await SqlServerTestStore.CreateInitializedAsync("SequenceEndToEndTest"); - public Task DisposeAsync() - { - TestStore.Dispose(); - return Task.CompletedTask; - } + public async Task DisposeAsync() + => await TestStore.DisposeAsync(); } diff --git a/test/EFCore.SqlServer.FunctionalTests/SequentialGuidEndToEndTest.cs b/test/EFCore.SqlServer.FunctionalTests/SequentialGuidEndToEndTest.cs index ab5b04f98ce..5fd9caec040 100644 --- a/test/EFCore.SqlServer.FunctionalTests/SequentialGuidEndToEndTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/SequentialGuidEndToEndTest.cs @@ -106,9 +106,6 @@ private class Pegasus public async Task InitializeAsync() => TestStore = await SqlServerTestStore.CreateInitializedAsync("SequentialGuidEndToEndTest"); - public Task DisposeAsync() - { - TestStore.Dispose(); - return Task.CompletedTask; - } + public async Task DisposeAsync() + => await TestStore.DisposeAsync(); } diff --git a/test/EFCore.SqlServer.FunctionalTests/SqlAzure/SqlAzureDatabaseCreationTest.cs b/test/EFCore.SqlServer.FunctionalTests/SqlAzure/SqlAzureDatabaseCreationTest.cs index 762ac3dd74f..db3403dac0e 100644 --- a/test/EFCore.SqlServer.FunctionalTests/SqlAzure/SqlAzureDatabaseCreationTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/SqlAzure/SqlAzureDatabaseCreationTest.cs @@ -16,8 +16,8 @@ public class SqlAzureDatabaseCreationTest [ConditionalFact] public async Task Creates_database_in_elastic_pool() { - using var testDatabase = SqlServerTestStore.Create(StoreName + "Elastic"); - using var context = new ElasticPoolContext(testDatabase); + await using var testDatabase = SqlServerTestStore.Create(StoreName + "Elastic"); + await using var context = new ElasticPoolContext(testDatabase); await context.Database.EnsureDeletedAsync(); await context.Database.EnsureCreatedAsync(); @@ -41,8 +41,8 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) [ConditionalFact] public async Task Creates_basic_database() { - using var testDatabase = SqlServerTestStore.Create(StoreName + "Basic"); - using var context = new BasicContext(testDatabase); + await using var testDatabase = SqlServerTestStore.Create(StoreName + "Basic"); + await using var context = new BasicContext(testDatabase); await context.Database.EnsureDeletedAsync(); await context.Database.EnsureCreatedAsync(); @@ -69,8 +69,8 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) [ConditionalFact] public async Task Creates_business_critical_database() { - using var testDatabase = SqlServerTestStore.Create(StoreName + "BusinessCritical"); - using var context = new BusinessCriticalContext(testDatabase); + await using var testDatabase = SqlServerTestStore.Create(StoreName + "BusinessCritical"); + await using var context = new BusinessCriticalContext(testDatabase); await context.Database.EnsureDeletedAsync(); await context.Database.EnsureCreatedAsync(); diff --git a/test/EFCore.SqlServer.FunctionalTests/SqlServerConfigPatternsTest.cs b/test/EFCore.SqlServer.FunctionalTests/SqlServerConfigPatternsTest.cs index 6d23947a4fd..4f18610337b 100644 --- a/test/EFCore.SqlServer.FunctionalTests/SqlServerConfigPatternsTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/SqlServerConfigPatternsTest.cs @@ -18,7 +18,7 @@ public class ImplicitServicesAndConfig [ConditionalFact] public async Task Can_query_with_implicit_services_and_OnConfiguring() { - using (await SqlServerTestStore.GetNorthwindStoreAsync()) + await using (await SqlServerTestStore.GetNorthwindStoreAsync()) { using var context = new NorthwindContext(); Assert.Equal(91, await context.Customers.CountAsync()); @@ -46,7 +46,7 @@ public class ImplicitServicesExplicitConfig [ConditionalFact] public async Task Can_query_with_implicit_services_and_explicit_config() { - using (await SqlServerTestStore.GetNorthwindStoreAsync()) + await using (await SqlServerTestStore.GetNorthwindStoreAsync()) { using var context = new NorthwindContext( new DbContextOptionsBuilder() @@ -71,7 +71,7 @@ public class ExplicitServicesImplicitConfig [ConditionalFact] public async Task Can_query_with_explicit_services_and_OnConfiguring() { - using (await SqlServerTestStore.GetNorthwindStoreAsync()) + await using (await SqlServerTestStore.GetNorthwindStoreAsync()) { using var context = new NorthwindContext( new DbContextOptionsBuilder().UseInternalServiceProvider( @@ -100,7 +100,7 @@ public class ExplicitServicesAndConfig [ConditionalFact] public async Task Can_query_with_explicit_services_and_explicit_config() { - using (await SqlServerTestStore.GetNorthwindStoreAsync()) + await using (await SqlServerTestStore.GetNorthwindStoreAsync()) { using var context = new NorthwindContext( new DbContextOptionsBuilder() @@ -127,7 +127,7 @@ public class ExplicitServicesAndNoConfig [ConditionalFact] public async Task Throws_on_attempt_to_use_SQL_Server_without_providing_connection_string() { - using (await SqlServerTestStore.GetNorthwindStoreAsync()) + await using (await SqlServerTestStore.GetNorthwindStoreAsync()) { Assert.Equal( CoreStrings.NoProviderConfigured, @@ -158,7 +158,7 @@ public class NoServicesAndNoConfig [ConditionalFact] public async Task Throws_on_attempt_to_use_context_with_no_store() { - using (await SqlServerTestStore.GetNorthwindStoreAsync()) + await using (await SqlServerTestStore.GetNorthwindStoreAsync()) { Assert.Equal( CoreStrings.NoProviderConfigured, @@ -192,7 +192,7 @@ public async Task Throws_on_attempt_to_use_store_with_no_store_services() new EntityFrameworkServicesBuilder(serviceCollection).TryAddCoreServices(); var serviceProvider = serviceCollection.BuildServiceProvider(validateScopes: true); - using (await SqlServerTestStore.GetNorthwindStoreAsync()) + await using (await SqlServerTestStore.GetNorthwindStoreAsync()) { Assert.Equal( CoreStrings.NoProviderConfigured, @@ -232,7 +232,7 @@ public async Task Can_register_context_with_DI_container_and_have_it_injected() .AddSingleton(p => new DbContextOptionsBuilder().UseInternalServiceProvider(p).Options) .BuildServiceProvider(validateScopes: true); - using (await SqlServerTestStore.GetNorthwindStoreAsync()) + await using (await SqlServerTestStore.GetNorthwindStoreAsync()) { await serviceProvider.GetRequiredService().TestAsync(); } @@ -284,7 +284,7 @@ public async Task Can_register_context_and_configuration_with_DI_container_and_h .UseSqlServer(SqlServerNorthwindTestStoreFactory.NorthwindConnectionString, b => b.ApplyConfiguration()) .Options).BuildServiceProvider(validateScopes: true); - using (await SqlServerTestStore.GetNorthwindStoreAsync()) + await using (await SqlServerTestStore.GetNorthwindStoreAsync()) { await serviceProvider.GetRequiredService().TestAsync(); } @@ -323,7 +323,7 @@ public class ConstructorArgsToBuilder [ConditionalFact] public async Task Can_pass_context_options_to_constructor_and_use_in_builder() { - using (await SqlServerTestStore.GetNorthwindStoreAsync()) + await using (await SqlServerTestStore.GetNorthwindStoreAsync()) { using var context = new NorthwindContext( new DbContextOptionsBuilder() @@ -348,7 +348,7 @@ public class ConstructorArgsToOnConfiguring [ConditionalFact] public async Task Can_pass_connection_string_to_constructor_and_use_in_OnConfiguring() { - using (await SqlServerTestStore.GetNorthwindStoreAsync()) + await using (await SqlServerTestStore.GetNorthwindStoreAsync()) { using var context = new NorthwindContext(SqlServerNorthwindTestStoreFactory.NorthwindConnectionString); Assert.Equal(91, await context.Customers.CountAsync()); @@ -376,7 +376,7 @@ public class NestedContext [ConditionalFact] public async Task Can_use_one_context_nested_inside_another_of_the_same_type() { - using (await SqlServerTestStore.GetNorthwindStoreAsync()) + await using (await SqlServerTestStore.GetNorthwindStoreAsync()) { var serviceProvider = new ServiceCollection() .AddEntityFrameworkSqlServer() diff --git a/test/EFCore.SqlServer.FunctionalTests/SqlServerDatabaseCreatorTest.cs b/test/EFCore.SqlServer.FunctionalTests/SqlServerDatabaseCreatorTest.cs index 4ccab8bdd31..71c7b388b3c 100644 --- a/test/EFCore.SqlServer.FunctionalTests/SqlServerDatabaseCreatorTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/SqlServerDatabaseCreatorTest.cs @@ -39,8 +39,8 @@ private static async Task Returns_false_when_database_does_not_exist_test( bool useCanConnect, bool file) { - using var testDatabase = SqlServerTestStore.Create("NonExisting", file); - using var context = new BloggingContext(testDatabase); + await using var testDatabase = SqlServerTestStore.Create("NonExisting", file); + await using var context = new BloggingContext(testDatabase); var creator = GetDatabaseCreator(context); await context.Database.CreateExecutionStrategy().ExecuteAsync( @@ -81,10 +81,10 @@ public Task Returns_true_when_database_with_filename_exists(bool async, bool amb private static async Task Returns_true_when_database_exists_test(bool async, bool ambientTransaction, bool useCanConnect, bool file) { - using var testDatabase = file + await using var testDatabase = file ? await SqlServerTestStore.CreateInitializedAsync("ExistingBloggingFile", useFileName: true) : await SqlServerTestStore.GetOrCreateInitializedAsync("ExistingBlogging"); - using var context = new BloggingContext(testDatabase); + await using var context = new BloggingContext(testDatabase); var creator = GetDatabaseCreator(context); await context.Database.CreateExecutionStrategy().ExecuteAsync( @@ -129,7 +129,7 @@ public Task Deletes_database_with_filename(bool async, bool open, bool ambientTr private static async Task Delete_database_test(bool async, bool open, bool ambientTransaction, bool file) { - using var testDatabase = await SqlServerTestStore.CreateInitializedAsync("EnsureDeleteBlogging" + (file ? "File" : ""), file); + await using var testDatabase = await SqlServerTestStore.CreateInitializedAsync("EnsureDeleteBlogging" + (file ? "File" : ""), file); if (!open) { testDatabase.CloseConnection(); @@ -178,8 +178,8 @@ public Task Noop_when_database_with_filename_does_not_exist(bool async) private static async Task Noop_when_database_does_not_exist_test(bool async, bool file) { - using var testDatabase = SqlServerTestStore.Create("NonExisting", file); - using var context = new BloggingContext(testDatabase); + await using var testDatabase = SqlServerTestStore.Create("NonExisting", file); + await using var context = new BloggingContext(testDatabase); var creator = GetDatabaseCreator(context); Assert.False(async ? await creator.ExistsAsync() : creator.Exists()); @@ -247,15 +247,15 @@ private static async Task Creates_physical_database_and_schema_test( (bool CreateDatabase, bool Async, bool ambientTransaction, bool File) options) { var (createDatabase, async, ambientTransaction, file) = options; - using var testDatabase = SqlServerTestStore.Create("EnsureCreatedTest" + (file ? "File" : ""), file); - using var context = new BloggingContext(testDatabase); + await using var testDatabase = SqlServerTestStore.Create("EnsureCreatedTest" + (file ? "File" : ""), file); + await using var context = new BloggingContext(testDatabase); if (createDatabase) { await testDatabase.InitializeAsync(null, (Func)null); } else { - testDatabase.DeleteDatabase(); + await testDatabase.DeleteDatabaseAsync(); } var creator = GetDatabaseCreator(context); @@ -327,8 +327,8 @@ public Task Noop_when_database_with_filename_exists_and_has_schema(bool async) private static async Task Noop_when_database_exists_and_has_schema_test(bool async, bool file) { - using var testDatabase = await SqlServerTestStore.CreateInitializedAsync("InitializedBlogging" + (file ? "File" : ""), file); - using var context = new BloggingContext(testDatabase); + await using var testDatabase = await SqlServerTestStore.CreateInitializedAsync("InitializedBlogging" + (file ? "File" : ""), file); + await using var context = new BloggingContext(testDatabase); context.Database.EnsureCreatedResiliently(); if (async) @@ -346,8 +346,8 @@ private static async Task Noop_when_database_exists_and_has_schema_test(bool asy [ConditionalFact] public async Task Throws_for_missing_seed() { - using var testDatabase = await SqlServerTestStore.CreateInitializedAsync("EnsureCreatedSeedTest"); - using var context = new BloggingContext(testDatabase.ConnectionString, asyncSeed: true); + await using var testDatabase = await SqlServerTestStore.CreateInitializedAsync("EnsureCreatedSeedTest"); + await using var context = new BloggingContext(testDatabase.ConnectionString, asyncSeed: true); Assert.Equal( CoreStrings.MissingSeeder, @@ -357,8 +357,8 @@ public async Task Throws_for_missing_seed() [ConditionalFact] public async Task Throws_for_missing_seed_async() { - using var testDatabase = await SqlServerTestStore.CreateInitializedAsync("EnsureCreatedSeedTest"); - using var context = new BloggingContext(testDatabase.ConnectionString, seed: true); + await using var testDatabase = await SqlServerTestStore.CreateInitializedAsync("EnsureCreatedSeedTest"); + await using var context = new BloggingContext(testDatabase.ConnectionString, seed: true); Assert.Equal( CoreStrings.MissingSeeder, @@ -374,7 +374,7 @@ public class SqlServerDatabaseCreatorHasTablesTest : SqlServerDatabaseCreatorTes [InlineData(false)] public async Task Throws_when_database_does_not_exist(bool async) { - using var testDatabase = SqlServerTestStore.GetOrCreate("NonExisting"); + await using var testDatabase = SqlServerTestStore.GetOrCreate("NonExisting"); var databaseCreator = GetDatabaseCreator(testDatabase); await databaseCreator.ExecutionStrategy.ExecuteAsync( databaseCreator, @@ -398,7 +398,7 @@ await databaseCreator.ExecutionStrategy.ExecuteAsync( [InlineData(false, true)] public async Task Returns_false_when_database_exists_but_has_no_tables(bool async, bool ambientTransaction) { - using var testDatabase = await SqlServerTestStore.GetOrCreateInitializedAsync("Empty"); + await using var testDatabase = await SqlServerTestStore.GetOrCreateInitializedAsync("Empty"); var creator = GetDatabaseCreator(testDatabase); await GetExecutionStrategy(testDatabase).ExecuteAsync( @@ -416,7 +416,7 @@ await GetExecutionStrategy(testDatabase).ExecuteAsync( [InlineData(false, false)] public async Task Returns_true_when_database_exists_and_has_any_tables(bool async, bool ambientTransaction) { - using var testDatabase = await SqlServerTestStore.GetOrCreate("ExistingTables") + await using var testDatabase = await SqlServerTestStore.GetOrCreate("ExistingTables") .InitializeSqlServerAsync(null, t => new BloggingContext(t), null); var creator = GetDatabaseCreator(testDatabase); @@ -439,7 +439,7 @@ public class SqlServerDatabaseCreatorDeleteTest : SqlServerDatabaseCreatorTestBa [InlineData(false, false)] public static async Task Deletes_database(bool async, bool ambientTransaction) { - using var testDatabase = await SqlServerTestStore.CreateInitializedAsync("DeleteBlogging"); + await using var testDatabase = await SqlServerTestStore.CreateInitializedAsync("DeleteBlogging"); testDatabase.CloseConnection(); var creator = GetDatabaseCreator(testDatabase); @@ -466,7 +466,7 @@ public static async Task Deletes_database(bool async, bool ambientTransaction) [InlineData(false)] public async Task Throws_when_database_does_not_exist(bool async) { - using var testDatabase = SqlServerTestStore.GetOrCreate("NonExistingBlogging"); + await using var testDatabase = SqlServerTestStore.GetOrCreate("NonExistingBlogging"); var creator = GetDatabaseCreator(testDatabase); if (async) @@ -501,8 +501,8 @@ public class SqlServerDatabaseCreatorCreateTablesTest : SqlServerDatabaseCreator [InlineData(false, false)] public async Task Creates_schema_in_existing_database_test(bool async, bool ambientTransaction) { - using var testDatabase = await SqlServerTestStore.GetOrCreateInitializedAsync("ExistingBlogging" + (async ? "Async" : "")); - using var context = new BloggingContext(testDatabase); + await using var testDatabase = await SqlServerTestStore.GetOrCreateInitializedAsync("ExistingBlogging" + (async ? "Async" : "")); + await using var context = new BloggingContext(testDatabase); var creator = GetDatabaseCreator(context); using (CreateTransactionScope(ambientTransaction)) @@ -551,7 +551,7 @@ public async Task Creates_schema_in_existing_database_test(bool async, bool ambi [InlineData(false)] public async Task Throws_if_database_does_not_exist(bool async) { - using var testDatabase = SqlServerTestStore.GetOrCreate("NonExisting"); + await using var testDatabase = SqlServerTestStore.GetOrCreate("NonExisting"); var creator = GetDatabaseCreator(testDatabase); var exception = async @@ -628,7 +628,7 @@ public class SqlServerDatabaseCreatorCreateTest : SqlServerDatabaseCreatorTestBa [InlineData(false, true)] public async Task Creates_physical_database_but_not_tables(bool async, bool ambientTransaction) { - using var testDatabase = SqlServerTestStore.GetOrCreate("CreateTest"); + await using var testDatabase = SqlServerTestStore.GetOrCreate("CreateTest"); var creator = GetDatabaseCreator(testDatabase); creator.EnsureDeleted(); @@ -673,7 +673,7 @@ await testDatabase.ExecuteScalarAsync( [InlineData(false)] public async Task Throws_if_database_already_exists(bool async) { - using var testDatabase = await SqlServerTestStore.GetOrCreateInitializedAsync("ExistingBlogging"); + await using var testDatabase = await SqlServerTestStore.GetOrCreateInitializedAsync("ExistingBlogging"); var creator = GetDatabaseCreator(testDatabase); var ex = async diff --git a/test/EFCore.SqlServer.FunctionalTests/SqlServerEndToEndTest.cs b/test/EFCore.SqlServer.FunctionalTests/SqlServerEndToEndTest.cs index b97e8543014..84a860c1079 100644 --- a/test/EFCore.SqlServer.FunctionalTests/SqlServerEndToEndTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/SqlServerEndToEndTest.cs @@ -30,7 +30,7 @@ public SqlServerEndToEndTest(SqlServerFixture fixture) [ConditionalFact] public async Task Can_use_decimal_and_byte_as_identity_columns() { - using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); var nownNum1 = new NownNum { Id = 77.0m, TheWalrus = "Crying" }; var nownNum2 = new NownNum { Id = 78.0m, TheWalrus = "Walrus" }; @@ -217,9 +217,9 @@ private class ByteAdNum [ConditionalFact] // Issue #29931 public async Task Can_use_SqlQuery_when_context_has_DbFunction() { - using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); var options = Fixture.CreateOptions(testDatabase); - using (var context = new DbFunctionContext(options)) + await using (var context = new DbFunctionContext(options)) { var result = context.Database .SqlQueryRaw("SELECT Name from sys.databases") @@ -257,7 +257,7 @@ private class RawResult [ConditionalFact] public async Task Can_use_string_enum_or_byte_array_as_key() { - using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); var sNum1 = new SNum { TheWalrus = "I" }; var sNum2 = new SNum { TheWalrus = "Am" }; @@ -268,7 +268,7 @@ public async Task Can_use_string_enum_or_byte_array_as_key() var bNum2 = new BNum { TheWalrus = "Eggmen" }; var options = Fixture.CreateOptions(testDatabase); - using (var context = new ENumContext(options)) + await using (var context = new ENumContext(options)) { context.Database.EnsureCreatedResiliently(); @@ -277,7 +277,7 @@ public async Task Can_use_string_enum_or_byte_array_as_key() context.SaveChanges(); } - using (var context = new ENumContext(options)) + await using (var context = new ENumContext(options)) { Assert.Equal(sNum1.Id, context.SNums.Single(e => e.TheWalrus == "I").Id); Assert.Equal(sNum2.Id, context.SNums.Single(e => e.TheWalrus == "Am").Id); @@ -293,12 +293,12 @@ public async Task Can_use_string_enum_or_byte_array_as_key() [ConditionalFact] public async Task Can_remove_multiple_byte_array_as_key() { - using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); var bNum1 = new BNum { TheWalrus = "Eggman" }; var bNum2 = new BNum { TheWalrus = "Eggmen" }; var options = Fixture.CreateOptions(testDatabase); - using (var context = new ENumContext(options)) + await using (var context = new ENumContext(options)) { context.Database.EnsureCreatedResiliently(); @@ -307,7 +307,7 @@ public async Task Can_remove_multiple_byte_array_as_key() context.SaveChanges(); } - using (var context = new ENumContext(options)) + await using (var context = new ENumContext(options)) { Assert.Equal(bNum1.Id, context.BNums.Single(e => e.TheWalrus == "Eggman").Id); Assert.Equal(bNum2.Id, context.BNums.Single(e => e.TheWalrus == "Eggmen").Id); @@ -328,11 +328,11 @@ private class ENumContext(DbContextOptions options) : DbContext(options) [ConditionalFact] public async Task Can_add_table_splitting_dependent_after_principal() { - using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); var options = Fixture.CreateOptions(testDatabase); EvaluationAction evaluationAction = null; - using (var context = new ProjectContext(options)) + await using (var context = new ProjectContext(options)) { context.Database.EnsureCreatedResiliently(); @@ -346,7 +346,7 @@ public async Task Can_add_table_splitting_dependent_after_principal() context.SaveChanges(); } - using (var context = new ProjectContext(options)) + await using (var context = new ProjectContext(options)) { context.Database.EnsureCreatedResiliently(); @@ -361,7 +361,7 @@ public async Task Can_add_table_splitting_dependent_after_principal() context.SaveChanges(); } - using (var context = new ProjectContext(options)) + await using (var context = new ProjectContext(options)) { Assert.NotNull(context.ProjectActions.Single()); Assert.NotNull(context.EvaluationActions.Single()); @@ -371,10 +371,10 @@ public async Task Can_add_table_splitting_dependent_after_principal() [ConditionalFact] public async Task Throws_when_adding_table_splitting_dependent_without_principal() { - using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); var options = Fixture.CreateOptions(testDatabase); - using (var context = new ProjectContext(options)) + await using (var context = new ProjectContext(options)) { context.Database.EnsureCreatedResiliently(); @@ -463,10 +463,10 @@ private class BNum [ConditionalFact] public async Task Can_add_and_remove_entities_with_keys_of_different_type() { - using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); var options = Fixture.CreateOptions(testDatabase); - using (var context = new CompositeKeysDbContext(options)) + await using (var context = new CompositeKeysDbContext(options)) { context.Database.EnsureCreatedResiliently(); var first = new Int32CompositeKeys { Id1 = 1, Id2 = 2 }; @@ -479,7 +479,7 @@ public async Task Can_add_and_remove_entities_with_keys_of_different_type() await context.SaveChangesAsync(); } - using (var context = new CompositeKeysDbContext(options)) + await using (var context = new CompositeKeysDbContext(options)) { var first = context.Set().Single(); context.Remove(first); @@ -515,10 +515,10 @@ private class Int64CompositeKeys [ConditionalFact] public async Task Can_insert_non_owner_principal_for_owned() { - using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); var options = Fixture.CreateOptions(testDatabase); - using (var context = new FileContext(options)) + await using (var context = new FileContext(options)) { context.Database.EnsureCreatedResiliently(); @@ -577,10 +577,10 @@ private sealed class FileSource [ConditionalFact] public async Task Can_insert_TPT_dependents_with_identity() { - using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); var options = Fixture.CreateOptions(testDatabase); - using (var context = new CarContext(options)) + await using (var context = new CarContext(options)) { context.Database.EnsureCreatedResiliently(); @@ -615,8 +615,8 @@ private class Ferrari : Car [ConditionalFact] public async Task Can_run_linq_query_on_entity_set() { - using var testStore = await SqlServerTestStore.GetNorthwindStoreAsync(); - using var db = new NorthwindContext(Fixture.CreateOptions(testStore)); + await using var testStore = await SqlServerTestStore.GetNorthwindStoreAsync(); + await using var db = new NorthwindContext(Fixture.CreateOptions(testStore)); var results = db.Customers .Where(c => c.CompanyName.StartsWith("A")) .OrderByDescending(c => c.CustomerID) @@ -637,8 +637,8 @@ public async Task Can_run_linq_query_on_entity_set() [ConditionalFact] public async Task Can_run_linq_query_on_entity_set_with_value_buffer_reader() { - using var testStore = await SqlServerTestStore.GetNorthwindStoreAsync(); - using var db = new NorthwindContext(Fixture.CreateOptions(testStore)); + await using var testStore = await SqlServerTestStore.GetNorthwindStoreAsync(); + await using var db = new NorthwindContext(Fixture.CreateOptions(testStore)); var results = db.Customers .Where(c => c.CompanyName.StartsWith("A")) .OrderByDescending(c => c.CustomerID) @@ -659,8 +659,8 @@ public async Task Can_run_linq_query_on_entity_set_with_value_buffer_reader() [ConditionalFact] public async Task Can_enumerate_entity_set() { - using var testStore = await SqlServerTestStore.GetNorthwindStoreAsync(); - using var db = new NorthwindContext(Fixture.CreateOptions(testStore)); + await using var testStore = await SqlServerTestStore.GetNorthwindStoreAsync(); + await using var db = new NorthwindContext(Fixture.CreateOptions(testStore)); var results = new List(); foreach (var item in db.Customers) { @@ -675,16 +675,16 @@ public async Task Can_enumerate_entity_set() [ConditionalFact] public async Task Can_save_changes() { - using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); var options = Fixture.CreateOptions(testDatabase); - using (var db = new BloggingContext(options)) + await using (var db = new BloggingContext(options)) { await CreateBlogDatabaseAsync(db); } Fixture.TestSqlLoggerFactory.Clear(); - using (var db = new BloggingContext(options)) + await using (var db = new BloggingContext(options)) { var toUpdate = db.Blogs.Single(b => b.Name == "Blog1"); toUpdate.Name = "Blog is Updated"; @@ -748,12 +748,12 @@ public async Task Can_save_changes() [ConditionalFact] public async Task Can_save_changes_in_tracked_entities() { - using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); int updatedId; int deletedId; int addedId; var options = Fixture.CreateOptions(testDatabase); - using (var db = new BloggingContext(options)) + await using (var db = new BloggingContext(options)) { var blogs = await CreateBlogDatabaseAsync(db); @@ -793,7 +793,7 @@ public async Task Can_save_changes_in_tracked_entities() Assert.DoesNotContain(toDelete, db.ChangeTracker.Entries().Select(e => e.Entity)); } - using (var db = new BloggingContext(options)) + await using (var db = new BloggingContext(options)) { var toUpdate = db.Blogs.Single(b => b.Id == updatedId); Assert.Equal("Blog is Updated", toUpdate.Name); @@ -805,9 +805,9 @@ public async Task Can_save_changes_in_tracked_entities() [ConditionalFact] public async Task Can_track_an_entity_with_more_than_10_properties() { - using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); var options = Fixture.CreateOptions(testDatabase); - using (var context = new GameDbContext(options)) + await using (var context = new GameDbContext(options)) { context.Database.EnsureCreatedResiliently(); @@ -818,7 +818,7 @@ public async Task Can_track_an_entity_with_more_than_10_properties() context.SaveChanges(); } - using (var context = new GameDbContext(options)) + await using (var context = new GameDbContext(options)) { var character = context.Characters .Include(c => c.Level.Game) @@ -834,10 +834,10 @@ public async Task Can_track_an_entity_with_more_than_10_properties() [ConditionalFact] public async Task Can_replace_identifying_FK_entity_with_many_to_many() { - using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); var options = Fixture.CreateOptions(testDatabase); - using (var context = new SomeDbContext(options)) + await using (var context = new SomeDbContext(options)) { context.Database.EnsureCreatedResiliently(); @@ -937,11 +937,11 @@ public async Task Can_insert_entities_with_generated_PKs(int studentCount, int c new() { Title = "Literature", Credits = 4 } }; - using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); var options = Fixture.CreateOptions(testDatabase); var nextCourse = 0; - using (var context = new UniversityContext(options)) + await using (var context = new UniversityContext(options)) { context.Database.EnsureCreatedResiliently(); for (var i = 0; i < studentCount; i++) @@ -1000,7 +1000,7 @@ public async Task Can_insert_entities_with_generated_PKs(int studentCount, int c }); } - using (var context = new UniversityContext(options)) + await using (var context = new UniversityContext(options)) { Assert.Equal(studentCount, context.Students.ToList().Count()); Assert.Equal(courseCount, context.Courses.ToList().Count()); @@ -1190,10 +1190,10 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) [ConditionalFact] public async Task Adding_an_item_to_a_collection_marks_it_as_modified() { - using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); var options = Fixture.CreateOptions(testDatabase); - using var context = new GameDbContext(options); + await using var context = new GameDbContext(options); context.Database.EnsureCreatedResiliently(); var player = new PlayerCharacter( @@ -1215,10 +1215,10 @@ public async Task Adding_an_item_to_a_collection_marks_it_as_modified() [ConditionalFact] public async Task Can_set_reference_twice() { - using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); var options = Fixture.CreateOptions(testDatabase); - using (var context = new GameDbContext(options)) + await using (var context = new GameDbContext(options)) { context.Database.EnsureCreatedResiliently(); @@ -1255,10 +1255,10 @@ public async Task Can_set_reference_twice() [ConditionalFact] public async Task Can_include_on_loaded_entity() { - using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); var options = Fixture.CreateOptions(testDatabase); - using (var context = new GameDbContext(options)) + await using (var context = new GameDbContext(options)) { context.Database.EnsureCreatedResiliently(); @@ -1281,7 +1281,7 @@ public async Task Can_include_on_loaded_entity() context.SaveChanges(); } - using (var context = new GameDbContext(options)) + await using (var context = new GameDbContext(options)) { var player = context.Characters .Include(p => p.CurrentWeapon) @@ -1301,7 +1301,7 @@ public async Task Can_include_on_loaded_entity() Assert.Equal(2, player.Items.Count); } - using (var context = new GameDbContext(options)) + await using (var context = new GameDbContext(options)) { var player = context.Characters .Include(p => p.CurrentWeapon) @@ -1483,8 +1483,8 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) [ConditionalFact] public async Task Tracking_entities_asynchronously_returns_tracked_entities_back() { - using var testStore = await SqlServerTestStore.GetNorthwindStoreAsync(); - using var db = new NorthwindContext(Fixture.CreateOptions(testStore)); + await using var testStore = await SqlServerTestStore.GetNorthwindStoreAsync(); + await using var db = new NorthwindContext(Fixture.CreateOptions(testStore)); var customer = await db.Customers.OrderBy(c => c.CustomerID).FirstOrDefaultAsync(); var trackedCustomerEntry = db.ChangeTracker.Entries().Single(); @@ -1497,14 +1497,14 @@ public async Task Tracking_entities_asynchronously_returns_tracked_entities_back [ConditionalFact] // Issue #931 public async Task Can_save_and_query_with_schema() { - using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); var options = Fixture.CreateOptions(testStore); await testStore.ExecuteNonQueryAsync("CREATE SCHEMA Apple"); await testStore.ExecuteNonQueryAsync("CREATE TABLE Apple.Jack (MyKey int)"); await testStore.ExecuteNonQueryAsync("CREATE TABLE Apple.Black (MyKey int)"); - using (var context = new SchemaContext(options)) + await using (var context = new SchemaContext(options)) { await context.AddAsync( new Jack { MyKey = 1 }); @@ -1513,7 +1513,7 @@ await context.AddAsync( context.SaveChanges(); } - using (var context = new SchemaContext(options)) + await using (var context = new SchemaContext(options)) { Assert.Equal(1, context.Jacks.Count()); Assert.Equal(1, context.Blacks.Count()); @@ -1564,14 +1564,14 @@ public Task Can_round_trip_changes_with_changed_only_notification_entities() private async Task RoundTripChanges() where TBlog : class, IBlog, new() { - using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); var options = Fixture.CreateOptions(testDatabase); int blog1Id; int blog2Id; int blog3Id; - using (var context = new BloggingContext(options)) + await using (var context = new BloggingContext(options)) { var blogs = await CreateBlogDatabaseAsync(context); blog1Id = blogs[0].Id; @@ -1582,7 +1582,7 @@ private async Task RoundTripChanges() Assert.NotEqual(blog1Id, blog2Id); } - using (var context = new BloggingContext(options)) + await using (var context = new BloggingContext(options)) { var blogs = context.Blogs.ToList(); Assert.Equal(2, blogs.Count); @@ -1618,7 +1618,7 @@ private async Task RoundTripChanges() Assert.NotEqual(0, blog3Id); } - using (var context = new BloggingContext(options)) + await using (var context = new BloggingContext(options)) { var blogs = context.Blogs.ToList(); Assert.Equal(3, blogs.Count); diff --git a/test/EFCore.SqlServer.FunctionalTests/SqlServerTypeAliasTest.cs b/test/EFCore.SqlServer.FunctionalTests/SqlServerTypeAliasTest.cs index 132022c41c4..37edba51415 100644 --- a/test/EFCore.SqlServer.FunctionalTests/SqlServerTypeAliasTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/SqlServerTypeAliasTest.cs @@ -14,7 +14,7 @@ public class SqlServerTypeAliasTest(SqlServerFixture fixture) : IClassFixture model [ConditionalFact] public async Task Insert_with_sequence_HiLo() { - using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); - using (var context = new BlogContextHiLo(testStore.Name, OnModelCreating)) + await using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using (var context = new BlogContextHiLo(testStore.Name, OnModelCreating)) { context.Database.EnsureCreatedResiliently(); @@ -68,7 +68,7 @@ public async Task Insert_with_sequence_HiLo() context.SaveChanges(); } - using (var context = new BlogContextHiLo(testStore.Name, OnModelCreating)) + await using (var context = new BlogContextHiLo(testStore.Name, OnModelCreating)) { var blogs = context.Blogs.OrderBy(e => e.Id).ToList(); @@ -100,8 +100,8 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) [ConditionalFact] public async Task Insert_with_key_sequence() { - using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); - using (var context = new BlogContextKeySequence(testStore.Name, OnModelCreating)) + await using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using (var context = new BlogContextKeySequence(testStore.Name, OnModelCreating)) { context.Database.EnsureCreatedResiliently(); @@ -110,7 +110,7 @@ public async Task Insert_with_key_sequence() context.SaveChanges(); } - using (var context = new BlogContextKeySequence(testStore.Name, OnModelCreating)) + await using (var context = new BlogContextKeySequence(testStore.Name, OnModelCreating)) { var blogs = context.Blogs.OrderBy(e => e.Id).ToList(); @@ -142,8 +142,8 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) [ConditionalFact] public async Task Insert_with_non_key_sequence() { - using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); - using (var context = new BlogContextNonKeySequence(testStore.Name, OnModelCreating)) + await using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using (var context = new BlogContextNonKeySequence(testStore.Name, OnModelCreating)) { context.Database.EnsureCreatedResiliently(); @@ -152,7 +152,7 @@ public async Task Insert_with_non_key_sequence() context.SaveChanges(); } - using (var context = new BlogContextNonKeySequence(testStore.Name, OnModelCreating)) + await using (var context = new BlogContextNonKeySequence(testStore.Name, OnModelCreating)) { var blogs = context.Blogs.OrderBy(e => e.Id).ToList(); @@ -181,8 +181,8 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) [ConditionalFact] public async Task Insert_with_default_value_from_sequence() { - using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); - using (var context = new BlogContextDefaultValue(testStore.Name, OnModelCreating)) + await using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using (var context = new BlogContextDefaultValue(testStore.Name, OnModelCreating)) { context.Database.EnsureCreatedResiliently(); @@ -191,7 +191,7 @@ public async Task Insert_with_default_value_from_sequence() context.SaveChanges(); } - using (var context = new BlogContextDefaultValue(testStore.Name, OnModelCreating)) + await using (var context = new BlogContextDefaultValue(testStore.Name, OnModelCreating)) { var blogs = context.Blogs.OrderBy(e => e.Id).ToList(); @@ -199,14 +199,14 @@ public async Task Insert_with_default_value_from_sequence() Assert.Equal(1, blogs[1].Id); } - using (var context = new BlogContextDefaultValueNoMigrations(testStore.Name, OnModelCreating)) + await using (var context = new BlogContextDefaultValueNoMigrations(testStore.Name, OnModelCreating)) { context.AddRange(CreateBlog("One Unicorn"), CreateBlog("Two Unicorns")); context.SaveChanges(); } - using (var context = new BlogContextDefaultValueNoMigrations(testStore.Name, OnModelCreating)) + await using (var context = new BlogContextDefaultValueNoMigrations(testStore.Name, OnModelCreating)) { var blogs = context.Blogs.OrderBy(e => e.Id).ToList(); @@ -251,8 +251,8 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) [ConditionalFact] public async Task Insert_with_default_string_value_from_sequence() { - using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); - using (var context = new BlogContextStringDefaultValue(testStore.Name, OnModelCreating, StringSentinel)) + await using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using (var context = new BlogContextStringDefaultValue(testStore.Name, OnModelCreating, StringSentinel)) { context.Database.EnsureCreatedResiliently(); @@ -263,7 +263,7 @@ public async Task Insert_with_default_string_value_from_sequence() context.SaveChanges(); } - using (var context = new BlogContextStringDefaultValue(testStore.Name, OnModelCreating, StringSentinel)) + await using (var context = new BlogContextStringDefaultValue(testStore.Name, OnModelCreating, StringSentinel)) { var blogs = context.StringyBlogs.OrderBy(e => e.Id).ToList(); @@ -304,8 +304,8 @@ public class BlogWithStringKey [ConditionalFact] public async Task Insert_with_key_default_value_from_sequence() { - using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); - using (var context = new BlogContextKeyColumnWithDefaultValue(testStore.Name, OnModelCreating)) + await using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using (var context = new BlogContextKeyColumnWithDefaultValue(testStore.Name, OnModelCreating)) { context.Database.EnsureCreatedResiliently(); @@ -314,7 +314,7 @@ public async Task Insert_with_key_default_value_from_sequence() context.SaveChanges(); } - using (var context = new BlogContextKeyColumnWithDefaultValue(testStore.Name, OnModelCreating)) + await using (var context = new BlogContextKeyColumnWithDefaultValue(testStore.Name, OnModelCreating)) { var blogs = context.Blogs.OrderBy(e => e.Id).ToList(); @@ -345,8 +345,8 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) [ConditionalFact] public async Task Insert_uint_to_Identity_column_using_value_converter() { - using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); - using (var context = new BlogContextUIntToIdentityUsingValueConverter(testStore.Name, OnModelCreating, UIntSentinel)) + await using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using (var context = new BlogContextUIntToIdentityUsingValueConverter(testStore.Name, OnModelCreating, UIntSentinel)) { context.Database.EnsureCreatedResiliently(); @@ -357,7 +357,7 @@ public async Task Insert_uint_to_Identity_column_using_value_converter() context.SaveChanges(); } - using (var context = new BlogContextUIntToIdentityUsingValueConverter(testStore.Name, OnModelCreating, UIntSentinel)) + await using (var context = new BlogContextUIntToIdentityUsingValueConverter(testStore.Name, OnModelCreating, UIntSentinel)) { var blogs = context.UnsignedBlogs.OrderBy(e => e.Id).ToList(); @@ -394,8 +394,8 @@ public class BlogWithUIntKey [ConditionalFact] public async Task Insert_int_enum_to_Identity_column() { - using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); - using (var context = new BlogContextIntEnumToIdentity(testStore.Name, OnModelCreating, IntKeySentinel)) + await using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using (var context = new BlogContextIntEnumToIdentity(testStore.Name, OnModelCreating, IntKeySentinel)) { context.Database.EnsureCreatedResiliently(); @@ -406,7 +406,7 @@ public async Task Insert_int_enum_to_Identity_column() context.SaveChanges(); } - using (var context = new BlogContextIntEnumToIdentity(testStore.Name, OnModelCreating, IntKeySentinel)) + await using (var context = new BlogContextIntEnumToIdentity(testStore.Name, OnModelCreating, IntKeySentinel)) { var blogs = context.EnumBlogs.OrderBy(e => e.Id).ToList(); @@ -450,8 +450,8 @@ public enum IntKey [ConditionalFact] public async Task Insert_ulong_enum_to_Identity_column() { - using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); - using (var context = new BlogContextULongEnumToIdentity(testStore.Name, OnModelCreating, ULongKeySentinel)) + await using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using (var context = new BlogContextULongEnumToIdentity(testStore.Name, OnModelCreating, ULongKeySentinel)) { context.Database.EnsureCreatedResiliently(); @@ -462,7 +462,7 @@ public async Task Insert_ulong_enum_to_Identity_column() context.SaveChanges(); } - using (var context = new BlogContextULongEnumToIdentity(testStore.Name, OnModelCreating, ULongKeySentinel)) + await using (var context = new BlogContextULongEnumToIdentity(testStore.Name, OnModelCreating, ULongKeySentinel)) { var blogs = context.EnumBlogs.OrderBy(e => e.Id).ToList(); @@ -505,8 +505,8 @@ public enum ULongKey : ulong [ConditionalFact] public async Task Insert_string_to_Identity_column_using_value_converter() { - using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); - using (var context = new BlogContextStringToIdentityUsingValueConverter(testStore.Name, OnModelCreating, StringSentinel)) + await using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using (var context = new BlogContextStringToIdentityUsingValueConverter(testStore.Name, OnModelCreating, StringSentinel)) { context.Database.EnsureCreatedResiliently(); @@ -517,7 +517,7 @@ public async Task Insert_string_to_Identity_column_using_value_converter() context.SaveChanges(); } - using (var context = new BlogContextStringToIdentityUsingValueConverter(testStore.Name, OnModelCreating, StringSentinel)) + await using (var context = new BlogContextStringToIdentityUsingValueConverter(testStore.Name, OnModelCreating, StringSentinel)) { var blogs = context.StringyBlogs.OrderBy(e => e.Id).ToList(); @@ -555,8 +555,8 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) [ConditionalFact] public async Task Insert_with_explicit_non_default_keys() { - using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); - using (var context = new BlogContextNoKeyGeneration(testStore.Name, OnModelCreating)) + await using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using (var context = new BlogContextNoKeyGeneration(testStore.Name, OnModelCreating)) { context.Database.EnsureCreatedResiliently(); @@ -566,7 +566,7 @@ public async Task Insert_with_explicit_non_default_keys() context.SaveChanges(); } - using (var context = new BlogContextNoKeyGeneration(testStore.Name, OnModelCreating)) + await using (var context = new BlogContextNoKeyGeneration(testStore.Name, OnModelCreating)) { var blogs = context.Blogs.OrderBy(e => e.Id).ToList(); @@ -592,8 +592,8 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) [ConditionalFact] public async Task Insert_with_explicit_with_default_keys() { - using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); - using (var context = new BlogContextNoKeyGenerationNullableKey(testStore.Name, OnModelCreating, NullableIntSentinel)) + await using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using (var context = new BlogContextNoKeyGenerationNullableKey(testStore.Name, OnModelCreating, NullableIntSentinel)) { context.Database.EnsureCreatedResiliently(); @@ -604,7 +604,7 @@ public async Task Insert_with_explicit_with_default_keys() context.SaveChanges(); } - using (var context = new BlogContextNoKeyGenerationNullableKey(testStore.Name, OnModelCreating, NullableIntSentinel)) + await using (var context = new BlogContextNoKeyGenerationNullableKey(testStore.Name, OnModelCreating, NullableIntSentinel)) { var blogs = context.NullableKeyBlogs.OrderBy(e => e.Id).ToList(); @@ -633,9 +633,9 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) [ConditionalFact] public async Task Insert_with_non_key_default_value() { - using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); - using (var context = new BlogContextNonKeyDefaultValue(testStore.Name, OnModelCreating)) + await using (var context = new BlogContextNonKeyDefaultValue(testStore.Name, OnModelCreating)) { context.Database.EnsureCreatedResiliently(); @@ -666,7 +666,7 @@ public async Task Insert_with_non_key_default_value() Assert.Equal(111, blogs[1].NeedsConverter.Value); } - using (var context = new BlogContextNonKeyDefaultValue(testStore.Name, OnModelCreating)) + await using (var context = new BlogContextNonKeyDefaultValue(testStore.Name, OnModelCreating)) { var blogs = context.Blogs.OrderBy(e => e.Name).ToList(); Assert.Equal(3, blogs.Count); @@ -686,7 +686,7 @@ public async Task Insert_with_non_key_default_value() context.SaveChanges(); } - using (var context = new BlogContextNonKeyDefaultValue(testStore.Name, OnModelCreating)) + await using (var context = new BlogContextNonKeyDefaultValue(testStore.Name, OnModelCreating)) { var blogs = context.Blogs.OrderBy(e => e.Name).ToList(); Assert.Equal(3, blogs.Count); @@ -703,9 +703,9 @@ public async Task Insert_with_non_key_default_value() [SqlServerCondition(SqlServerCondition.SupportsSqlClr)] public async Task Insert_with_non_key_default_spatial_value() { - using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); - using (var context = new BlogContextNonKeyDefaultSpatialValue(testStore.Name, OnModelCreating)) + await using (var context = new BlogContextNonKeyDefaultSpatialValue(testStore.Name, OnModelCreating)) { context.Database.EnsureCreatedResiliently(); @@ -735,7 +735,7 @@ public async Task Insert_with_non_key_default_spatial_value() Assert.Equal(3, point.Y); } - using (var context = new BlogContextNonKeyDefaultSpatialValue(testStore.Name, OnModelCreating)) + await using (var context = new BlogContextNonKeyDefaultSpatialValue(testStore.Name, OnModelCreating)) { var blogs = context.SpatialBlogs.OrderBy(e => e.Name).ToList(); Assert.Equal(3, blogs.Count); @@ -754,7 +754,7 @@ public async Task Insert_with_non_key_default_spatial_value() context.SaveChanges(); } - using (var context = new BlogContextNonKeyDefaultSpatialValue(testStore.Name, OnModelCreating)) + await using (var context = new BlogContextNonKeyDefaultSpatialValue(testStore.Name, OnModelCreating)) { var blogs = context.SpatialBlogs.OrderBy(e => e.Name).ToList(); Assert.Equal(3, blogs.Count); @@ -820,8 +820,8 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) [ConditionalFact] public async Task Insert_with_non_key_default_value_readonly() { - using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); - using (var context = new BlogContextNonKeyReadOnlyDefaultValue(testStore.Name, OnModelCreating, IntSentinel, DateTimeSentinel)) + await using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using (var context = new BlogContextNonKeyReadOnlyDefaultValue(testStore.Name, OnModelCreating, IntSentinel, DateTimeSentinel)) { context.Database.EnsureCreatedResiliently(); @@ -846,7 +846,7 @@ public async Task Insert_with_non_key_default_value_readonly() DateTime dateTime0; - using (var context = new BlogContextNonKeyReadOnlyDefaultValue(testStore.Name, OnModelCreating, IntSentinel, DateTimeSentinel)) + await using (var context = new BlogContextNonKeyReadOnlyDefaultValue(testStore.Name, OnModelCreating, IntSentinel, DateTimeSentinel)) { var blogs = context.Blogs.OrderBy(e => e.Id).ToList(); @@ -861,7 +861,7 @@ public async Task Insert_with_non_key_default_value_readonly() context.SaveChanges(); } - using (var context = new BlogContextNonKeyReadOnlyDefaultValue(testStore.Name, OnModelCreating, IntSentinel, DateTimeSentinel)) + await using (var context = new BlogContextNonKeyReadOnlyDefaultValue(testStore.Name, OnModelCreating, IntSentinel, DateTimeSentinel)) { var blogs = context.Blogs.OrderBy(e => e.Id).ToList(); @@ -897,8 +897,8 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) [ConditionalFact] public async Task Insert_and_update_with_computed_column() { - using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); - using (var context = new BlogContextComputedColumn(testStore.Name, OnModelCreating, IntSentinel, StringSentinel)) + await using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using (var context = new BlogContextComputedColumn(testStore.Name, OnModelCreating, IntSentinel, StringSentinel)) { context.Database.EnsureCreatedResiliently(); @@ -916,7 +916,7 @@ public async Task Insert_and_update_with_computed_column() Assert.Equal("One Unicorn", blog.FullName); } - using (var context = new BlogContextComputedColumn(testStore.Name, OnModelCreating, IntSentinel, StringSentinel)) + await using (var context = new BlogContextComputedColumn(testStore.Name, OnModelCreating, IntSentinel, StringSentinel)) { var blog = context.FullNameBlogs.Single(); @@ -974,8 +974,8 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) [ConditionalFact] public async Task Insert_and_update_with_computed_column_with_function() { - using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); - using (var context = new BlogContextComputedColumnWithFunction(testStore.Name, OnModelCreating, IntSentinel, StringSentinel)) + await using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using (var context = new BlogContextComputedColumnWithFunction(testStore.Name, OnModelCreating, IntSentinel, StringSentinel)) { context.Database.ExecuteSqlRaw ( @@ -986,7 +986,7 @@ public async Task Insert_and_update_with_computed_column_with_function() context.GetService().CreateTables(); } - using (var context = new BlogContextComputedColumnWithFunction(testStore.Name, OnModelCreating, IntSentinel, StringSentinel)) + await using (var context = new BlogContextComputedColumnWithFunction(testStore.Name, OnModelCreating, IntSentinel, StringSentinel)) { var blog = context.Add( new FullNameBlog @@ -1002,7 +1002,7 @@ public async Task Insert_and_update_with_computed_column_with_function() Assert.Equal("OneUnicorn", blog.FullName); } - using (var context = new BlogContextComputedColumnWithFunction(testStore.Name, OnModelCreating, IntSentinel, StringSentinel)) + await using (var context = new BlogContextComputedColumnWithFunction(testStore.Name, OnModelCreating, IntSentinel, StringSentinel)) { var blog = context.FullNameBlogs.Single(); @@ -1136,7 +1136,10 @@ RETURN @FullName DatabaseName, OnModelCreating, IntSentinel, StringSentinel); context.Database.ExecuteSqlRaw("ALTER TABLE dbo.FullNameBlogs DROP COLUMN FullName;"); context.Database.ExecuteSqlRaw("DROP FUNCTION [dbo].[GetFullName];"); - testStore?.Dispose(); + if (testStore is not null) + { + await testStore.DisposeAsync(); + } } } @@ -1144,8 +1147,8 @@ RETURN @FullName [MemberData(nameof(IsAsyncData))] public async Task Insert_with_computed_column_with_function_without_metadata_configuration(bool async) { - using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); - using (var context = new BlogContextComputedColumn(testStore.Name, OnModelCreating, IntSentinel, StringSentinel)) + await using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using (var context = new BlogContextComputedColumn(testStore.Name, OnModelCreating, IntSentinel, StringSentinel)) { context.GetService().CreateTables(); @@ -1165,7 +1168,7 @@ RETURN @FullName try { - using (var context = new BlogContextComputedColumn(testStore.Name, OnModelCreating, IntSentinel, StringSentinel)) + await using (var context = new BlogContextComputedColumn(testStore.Name, OnModelCreating, IntSentinel, StringSentinel)) { await context.AddAsync(new FullNameBlog { Id = IntSentinel, FullName = StringSentinel }); @@ -1181,7 +1184,7 @@ RETURN @FullName } finally { - using var context = new BlogContextComputedColumnWithTriggerMetadata( + await using var context = new BlogContextComputedColumnWithTriggerMetadata( testStore.Name, OnModelCreating, IntSentinel, StringSentinel); context.Database.ExecuteSqlRaw("ALTER TABLE dbo.FullNameBlogs DROP COLUMN FullName;"); context.Database.ExecuteSqlRaw("DROP FUNCTION [dbo].[GetFullName];"); @@ -1194,8 +1197,8 @@ public async Task Insert_with_trigger_without_metadata_configuration(bool async) { // Execute an insert against a table which has a trigger, but which haven't identified as such in our metadata. // This causes a specialized exception to be thrown, directing users to the relevant docs. - using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); - using (var context = new BlogContextComputedColumn(testStore.Name, OnModelCreating, IntSentinel, StringSentinel)) + await using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using (var context = new BlogContextComputedColumn(testStore.Name, OnModelCreating, IntSentinel, StringSentinel)) { context.GetService().CreateTables(); @@ -1211,7 +1214,7 @@ ON [FullNameBlogs] try { - using (var context = new BlogContextComputedColumn(testStore.Name, OnModelCreating, IntSentinel, StringSentinel)) + await using (var context = new BlogContextComputedColumn(testStore.Name, OnModelCreating, IntSentinel, StringSentinel)) { await context.AddAsync(new FullNameBlog { Id = IntSentinel, FullName = StringSentinel }); @@ -1227,7 +1230,7 @@ ON [FullNameBlogs] } finally { - using var context = new BlogContextComputedColumn(testStore.Name, OnModelCreating, IntSentinel, StringSentinel); + await using var context = new BlogContextComputedColumn(testStore.Name, OnModelCreating, IntSentinel, StringSentinel); context.Database.ExecuteSqlRaw("DROP TRIGGER [FullNameBlogs_Trigger]"); } } @@ -1235,9 +1238,9 @@ ON [FullNameBlogs] [ConditionalFact] public async Task Insert_with_client_generated_GUID_key() { - using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); Guid afterSave; - using (var context = new BlogContextClientGuidKey(testStore.Name, OnModelCreating, GuidSentinel)) + await using (var context = new BlogContextClientGuidKey(testStore.Name, OnModelCreating, GuidSentinel)) { context.Database.EnsureCreatedResiliently(); @@ -1264,7 +1267,7 @@ public async Task Insert_with_client_generated_GUID_key() Assert.Equal(beforeSaveNotId, afterSaveNotId); } - using (var context = new BlogContextClientGuidKey(testStore.Name, OnModelCreating, GuidSentinel)) + await using (var context = new BlogContextClientGuidKey(testStore.Name, OnModelCreating, GuidSentinel)) { Assert.Equal(afterSave, context.GuidBlogs.Single().Id); } @@ -1293,8 +1296,8 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) [SqlServerCondition(SqlServerCondition.IsNotSqlAzure)] public async Task Insert_with_ValueGeneratedOnAdd_GUID_nonkey_property_throws() { - using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); - using var context = new BlogContextClientGuidNonKey(testStore.Name, OnModelCreating, GuidSentinel); + await using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using var context = new BlogContextClientGuidNonKey(testStore.Name, OnModelCreating, GuidSentinel); context.Database.EnsureCreatedResiliently(); var blog = context.Add( @@ -1333,9 +1336,9 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) [ConditionalFact] public async Task Insert_with_server_generated_GUID_key() { - using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); Guid afterSave; - using (var context = new BlogContextServerGuidKey(testStore.Name, OnModelCreating, GuidSentinel)) + await using (var context = new BlogContextServerGuidKey(testStore.Name, OnModelCreating, GuidSentinel)) { context.Database.EnsureCreatedResiliently(); @@ -1364,7 +1367,7 @@ public async Task Insert_with_server_generated_GUID_key() Assert.NotEqual(beforeSaveNotId, afterSaveNotId); } - using (var context = new BlogContextServerGuidKey(testStore.Name, OnModelCreating, GuidSentinel)) + await using (var context = new BlogContextServerGuidKey(testStore.Name, OnModelCreating, GuidSentinel)) { Assert.Equal(afterSave, context.GuidBlogs.Single().Id); } @@ -1393,8 +1396,8 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) [ConditionalFact] public async Task Insert_with_explicit_non_default_keys_by_default() { - using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); - using var context = new BlogContext(testStore.Name, OnModelCreating); + await using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using var context = new BlogContext(testStore.Name, OnModelCreating); context.Database.EnsureCreatedResiliently(); context.AddRange( @@ -1410,8 +1413,8 @@ public async Task Insert_with_explicit_non_default_keys_by_default() [ConditionalFact] public async Task Insert_with_explicit_default_keys() { - using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); - using var context = new BlogContext(testStore.Name, OnModelCreating); + await using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using var context = new BlogContext(testStore.Name, OnModelCreating); context.Database.EnsureCreatedResiliently(); context.AddRange( @@ -1430,8 +1433,8 @@ public class BlogContext(string databaseName, Action modelBuilder) [ConditionalFact] public async Task Insert_with_implicit_default_keys() { - using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); - using (var context = new BlogContextSpecifyKeysUsingDefault(testStore.Name, OnModelCreating, IntSentinel)) + await using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using (var context = new BlogContextSpecifyKeysUsingDefault(testStore.Name, OnModelCreating, IntSentinel)) { context.Database.EnsureCreatedResiliently(); @@ -1441,7 +1444,7 @@ public async Task Insert_with_implicit_default_keys() context.SaveChanges(); } - using (var context = new BlogContextSpecifyKeysUsingDefault(testStore.Name, OnModelCreating, IntSentinel)) + await using (var context = new BlogContextSpecifyKeysUsingDefault(testStore.Name, OnModelCreating, IntSentinel)) { var blogs = context.Blogs.OrderBy(e => e.Id).ToList(); @@ -1470,8 +1473,8 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) [ConditionalFact] public async Task Insert_explicit_value_throws_when_readonly_sequence_before_save() { - using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); - using var context = new BlogContextReadOnlySequenceKeyColumnWithDefaultValue(testStore.Name, OnModelCreating, IntSentinel); + await using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using var context = new BlogContextReadOnlySequenceKeyColumnWithDefaultValue(testStore.Name, OnModelCreating, IntSentinel); context.Database.EnsureCreatedResiliently(); context.AddRange( @@ -1508,8 +1511,8 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) [ConditionalFact] public async Task Insert_explicit_value_throws_when_readonly_before_save() { - using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); - using var context = new BlogContextNonKeyReadOnlyDefaultValue(testStore.Name, OnModelCreating, IntSentinel, DateTimeSentinel); + await using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using var context = new BlogContextNonKeyReadOnlyDefaultValue(testStore.Name, OnModelCreating, IntSentinel, DateTimeSentinel); context.Database.EnsureCreatedResiliently(); context.AddRange( @@ -1536,8 +1539,8 @@ public async Task Insert_explicit_value_throws_when_readonly_before_save() [ConditionalFact] public async Task Insert_explicit_value_into_computed_column() { - using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); - using var context = new BlogContextComputedColumn(testStore.Name, OnModelCreating, IntSentinel, StringSentinel); + await using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using var context = new BlogContextComputedColumn(testStore.Name, OnModelCreating, IntSentinel, StringSentinel); context.Database.EnsureCreatedResiliently(); context.Add( @@ -1559,8 +1562,8 @@ public async Task Insert_explicit_value_into_computed_column() [ConditionalFact] public async Task Update_explicit_value_in_computed_column() { - using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); - using (var context = new BlogContextComputedColumn(testStore.Name, OnModelCreating, IntSentinel, StringSentinel)) + await using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using (var context = new BlogContextComputedColumn(testStore.Name, OnModelCreating, IntSentinel, StringSentinel)) { context.Database.EnsureCreatedResiliently(); @@ -1576,7 +1579,7 @@ public async Task Update_explicit_value_in_computed_column() context.SaveChanges(); } - using (var context = new BlogContextComputedColumn(testStore.Name, OnModelCreating, IntSentinel, StringSentinel)) + await using (var context = new BlogContextComputedColumn(testStore.Name, OnModelCreating, IntSentinel, StringSentinel)) { var blog = context.FullNameBlogs.Single(); @@ -1594,8 +1597,8 @@ public async Task Update_explicit_value_in_computed_column() [ConditionalFact] public async Task Resolve_concurrency() { - using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); - using var context = new BlogContextConcurrencyWithRowversion(testStore.Name, OnModelCreating, IntSentinel, TimestampSentinel); + await using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + await using var context = new BlogContextConcurrencyWithRowversion(testStore.Name, OnModelCreating, IntSentinel, TimestampSentinel); context.Database.EnsureCreatedResiliently(); var blog = context.Add( @@ -1608,7 +1611,7 @@ public async Task Resolve_concurrency() context.SaveChanges(); - using var innerContext = new BlogContextConcurrencyWithRowversion(testStore.Name, OnModelCreating, IntSentinel, TimestampSentinel); + await using var innerContext = new BlogContextConcurrencyWithRowversion(testStore.Name, OnModelCreating, IntSentinel, TimestampSentinel); var updatedBlog = innerContext.ConcurrentBlogs.Single(); updatedBlog.Name = "One Pegasus"; innerContext.SaveChanges(); diff --git a/test/EFCore.SqlServer.FunctionalTests/TestUtilities/SqlServerTestStore.cs b/test/EFCore.SqlServer.FunctionalTests/TestUtilities/SqlServerTestStore.cs index ca1122a1b78..5cc5dc08056 100644 --- a/test/EFCore.SqlServer.FunctionalTests/TestUtilities/SqlServerTestStore.cs +++ b/test/EFCore.SqlServer.FunctionalTests/TestUtilities/SqlServerTestStore.cs @@ -86,7 +86,7 @@ public async Task InitializeSqlServerAsync( protected override async Task InitializeAsync(Func createContext, Func? seed, Func? clean) { - if (await CreateDatabase(clean)) + if (await CreateDatabaseAsync(clean)) { if (_scriptPath != null) { @@ -116,43 +116,39 @@ public override DbContextOptionsBuilder AddProviderOptions(DbContextOptionsBuild : builder.UseSqlServer(Connection, b => b.ApplyConfiguration())) .ConfigureWarnings(b => b.Ignore(SqlServerEventId.SavepointsDisabledBecauseOfMARS)); - private async Task CreateDatabase(Func? clean) + private async Task CreateDatabaseAsync(Func? clean) { - using (var master = new SqlConnection(CreateConnectionString("master", fileName: null, multipleActiveResultSets: false))) + await using var master = new SqlConnection(CreateConnectionString("master", fileName: null, multipleActiveResultSets: false)); + + if (ExecuteScalar(master, $"SELECT COUNT(*) FROM sys.databases WHERE name = N'{Name}'") > 0) { - if (ExecuteScalar(master, $"SELECT COUNT(*) FROM sys.databases WHERE name = N'{Name}'") > 0) + // Only reseed scripted databases during CI runs + if (_scriptPath != null && !TestEnvironment.IsCI) { - // Only reseed scripted databases during CI runs - if (_scriptPath != null && !TestEnvironment.IsCI) - { - return false; - } + return false; + } + + if (_fileName == null) + { + await using var context = new DbContext( + AddProviderOptions(new DbContextOptionsBuilder().EnableServiceProviderCaching(false)).Options); + await CleanAsync(context); - if (_fileName == null) + if (clean != null) { - using var context = new DbContext( - AddProviderOptions( - new DbContextOptionsBuilder() - .EnableServiceProviderCaching(false)) - .Options); - await CleanAsync(context); - - if (clean != null) - { - await clean(context); - } - - return true; + await clean(context); } - // Delete the database to ensure it's recreated with the correct file path - DeleteDatabase(); + return true; } - ExecuteNonQuery(master, GetCreateDatabaseStatement(Name, _fileName)); - WaitForExists((SqlConnection)Connection); + // Delete the database to ensure it's recreated with the correct file path + await DeleteDatabaseAsync(); } + await ExecuteNonQueryAsync(master, GetCreateDatabaseStatement(Name, _fileName)); + await WaitForExistsAsync((SqlConnection)Connection); + return true; } @@ -177,10 +173,10 @@ public void ExecuteScript(string script) return 0; }, ""); - private static void WaitForExists(SqlConnection connection) - => new TestSqlServerRetryingExecutionStrategy().Execute(connection, WaitForExistsImplementation); + private static Task WaitForExistsAsync(SqlConnection connection) + => new TestSqlServerRetryingExecutionStrategy().ExecuteAsync(connection, WaitForExistsImplementation); - private static void WaitForExistsImplementation(SqlConnection connection) + private static async Task WaitForExistsImplementation(SqlConnection connection) { var retryCount = 0; while (true) @@ -189,13 +185,13 @@ private static void WaitForExistsImplementation(SqlConnection connection) { if (connection.State != ConnectionState.Closed) { - connection.Close(); + await connection.CloseAsync(); } SqlConnection.ClearPool(connection); - connection.Open(); - connection.Close(); + await connection.OpenAsync(); + await connection.CloseAsync(); return; } catch (SqlException e) @@ -206,7 +202,7 @@ private static void WaitForExistsImplementation(SqlConnection connection) throw; } - Thread.Sleep(100); + await Task.Delay(100); } } } @@ -237,16 +233,19 @@ private static string GetCreateDatabaseStatement(string name, string? fileName) return result; } - public void DeleteDatabase() + public async Task DeleteDatabaseAsync() { - using var master = new SqlConnection(CreateConnectionString("master")); - ExecuteNonQuery( + await using var master = new SqlConnection(CreateConnectionString("master")); + + await ExecuteNonQueryAsync( master, string.Format( - @"IF EXISTS (SELECT * FROM sys.databases WHERE name = N'{0}') - BEGIN - ALTER DATABASE [{0}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; - DROP DATABASE [{0}]; - END", Name)); + """ +IF EXISTS (SELECT * FROM sys.databases WHERE name = N'{0}') +BEGIN + ALTER DATABASE [{0}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; + DROP DATABASE [{0}]; +END +""", Name)); SqlConnection.ClearAllPools(); } @@ -444,14 +443,14 @@ private static DbCommand CreateCommand( return command; } - public override void Dispose() + public override async ValueTask DisposeAsync() { - base.Dispose(); + await base.DisposeAsync(); if (_fileName != null // Clean up the database using a local file, as it might get deleted later || (TestEnvironment.IsSqlAzure && !Shared)) { - DeleteDatabase(); + await DeleteDatabaseAsync(); } } diff --git a/test/EFCore.SqlServer.FunctionalTests/Update/MismatchedKeyTypesSqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/Update/MismatchedKeyTypesSqlServerTest.cs index 621d1edc673..9013bbabdf6 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Update/MismatchedKeyTypesSqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Update/MismatchedKeyTypesSqlServerTest.cs @@ -796,11 +796,8 @@ public async Task InitializeAsync() await SeedAsync(); } - public Task DisposeAsync() - { - Store.Dispose(); - return Task.CompletedTask; - } + public async Task DisposeAsync() + => await Store.DisposeAsync(); } private class TemporaryByteValueGenerator : ValueGenerator diff --git a/test/EFCore.Sqlite.FunctionalTests/SqliteDatabaseCreatorTest.cs b/test/EFCore.Sqlite.FunctionalTests/SqliteDatabaseCreatorTest.cs index 4e4ccb8f3c3..91d626f43c6 100644 --- a/test/EFCore.Sqlite.FunctionalTests/SqliteDatabaseCreatorTest.cs +++ b/test/EFCore.Sqlite.FunctionalTests/SqliteDatabaseCreatorTest.cs @@ -36,7 +36,7 @@ public async Task Exists_returns_false_when_database_doesnt_exist(bool async, bo [InlineData(true)] public async Task HasTables_returns_false_when_database_is_empty(bool async) { - using var testStore = await SqliteTestStore.GetOrCreateInitializedAsync("Empty"); + await using var testStore = await SqliteTestStore.GetOrCreateInitializedAsync("Empty"); var context = CreateContext(testStore.ConnectionString); var creator = context.GetService(); @@ -48,7 +48,7 @@ public async Task HasTables_returns_false_when_database_is_empty(bool async) [InlineData(true)] public async Task HasTables_returns_true_when_database_is_not_empty(bool async) { - using var testStore = await SqliteTestStore.GetOrCreateInitializedAsync($"HasATable{(async ? 'A' : 'S')}"); + await using var testStore = await SqliteTestStore.GetOrCreateInitializedAsync($"HasATable{(async ? 'A' : 'S')}"); var context = CreateContext(testStore.ConnectionString); context.Database.ExecuteSqlRaw("CREATE TABLE Dummy (Foo INTEGER)"); @@ -63,7 +63,7 @@ public async Task HasTables_returns_true_when_database_is_not_empty(bool async) [InlineData(true, true)] public async Task Exists_returns_true_when_database_exists(bool async, bool useCanConnect) { - using var testStore = await SqliteTestStore.GetOrCreateInitializedAsync("Empty"); + await using var testStore = await SqliteTestStore.GetOrCreateInitializedAsync("Empty"); var context = CreateContext(testStore.ConnectionString); if (useCanConnect) @@ -82,7 +82,7 @@ public async Task Exists_returns_true_when_database_exists(bool async, bool useC [InlineData(true)] public async Task Create_sets_journal_mode_to_wal(bool async) { - using var testStore = SqliteTestStore.GetOrCreate("Create"); + await using var testStore = SqliteTestStore.GetOrCreate("Create"); using var context = CreateContext(testStore.ConnectionString); var creator = context.GetService();