diff --git a/src/EFCore.Cosmos/Diagnostics/CosmosEventId.cs b/src/EFCore.Cosmos/Diagnostics/CosmosEventId.cs index 238d18324a1..c1580503337 100644 --- a/src/EFCore.Cosmos/Diagnostics/CosmosEventId.cs +++ b/src/EFCore.Cosmos/Diagnostics/CosmosEventId.cs @@ -25,6 +25,7 @@ public static class CosmosEventId private enum Id { // Database events + SyncNotSupported = CoreEventId.ProviderBaseId, // Command events ExecutingSqlQuery = CoreEventId.ProviderBaseId + 100, @@ -36,6 +37,19 @@ private enum Id ExecutedDeleteItem } + private static readonly string DatabasePrefix = DbLoggerCategory.Database.Name + "."; + + /// + /// Azure Cosmos DB does not support synchronous I/O. Make sure to use and correctly await only async + /// methods when using Entity Framework Core to access Azure Cosmos DB. + /// See https://aka.ms/ef-cosmos-nosync for more information. + /// + /// + /// This event is in the category. + /// + public static readonly EventId SyncNotSupported + = new((int)Id.SyncNotSupported, DatabasePrefix + Id.SyncNotSupported); + private static readonly string CommandPrefix = DbLoggerCategory.Database.Command.Name + "."; /// diff --git a/src/EFCore.Cosmos/Diagnostics/Internal/CosmosLoggerExtensions.cs b/src/EFCore.Cosmos/Diagnostics/Internal/CosmosLoggerExtensions.cs index 2048ca35836..75834a6465c 100644 --- a/src/EFCore.Cosmos/Diagnostics/Internal/CosmosLoggerExtensions.cs +++ b/src/EFCore.Cosmos/Diagnostics/Internal/CosmosLoggerExtensions.cs @@ -19,6 +19,32 @@ namespace Microsoft.EntityFrameworkCore.Cosmos.Diagnostics.Internal; /// public static class CosmosLoggerExtensions { + /// + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// + public static void SyncNotSupported( + this IDiagnosticsLogger diagnostics) + { + var definition = CosmosResources.LogSyncNotSupported(diagnostics); + + if (diagnostics.ShouldLog(definition)) + { + definition.Log(diagnostics); + } + + if (diagnostics.NeedsEventData(definition, out var diagnosticSourceEnabled, out var simpleLogEnabled)) + { + var eventData = new EventData( + definition, + (d, p) => ((EventDefinition)d).GenerateMessage()); + + diagnostics.DispatchEventData(definition, eventData, diagnosticSourceEnabled, simpleLogEnabled); + } + } + /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in diff --git a/src/EFCore.Cosmos/Diagnostics/Internal/CosmosLoggingDefinitions.cs b/src/EFCore.Cosmos/Diagnostics/Internal/CosmosLoggingDefinitions.cs index 168765dbccc..79cda1d0bea 100644 --- a/src/EFCore.Cosmos/Diagnostics/Internal/CosmosLoggingDefinitions.cs +++ b/src/EFCore.Cosmos/Diagnostics/Internal/CosmosLoggingDefinitions.cs @@ -66,4 +66,12 @@ public class CosmosLoggingDefinitions : LoggingDefinitions /// doing so can result in application failures when updating to a new Entity Framework Core release. /// public EventDefinitionBase? LogExecutedDeleteItem; + + /// + /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to + /// the same compatibility standards as public APIs. It may be changed or removed without notice in + /// any release. You should only use it directly in your code with extreme caution and knowing that + /// doing so can result in application failures when updating to a new Entity Framework Core release. + /// + public EventDefinitionBase? LogSyncNotSupported; } diff --git a/src/EFCore.Cosmos/Extensions/CosmosDbContextOptionsExtensions.cs b/src/EFCore.Cosmos/Extensions/CosmosDbContextOptionsExtensions.cs index 6abe47427c8..3824a31fc4d 100644 --- a/src/EFCore.Cosmos/Extensions/CosmosDbContextOptionsExtensions.cs +++ b/src/EFCore.Cosmos/Extensions/CosmosDbContextOptionsExtensions.cs @@ -52,6 +52,8 @@ public static DbContextOptionsBuilder UseCosmos( Check.NotNull(optionsBuilder, nameof(optionsBuilder)); Check.NotNull(cosmosOptionsAction, nameof(cosmosOptionsAction)); + ConfigureWarnings(optionsBuilder); + cosmosOptionsAction.Invoke(new CosmosDbContextOptionsBuilder(optionsBuilder)); return optionsBuilder; @@ -118,6 +120,8 @@ public static DbContextOptionsBuilder UseCosmos( .WithAccountKey(accountKey) .WithDatabaseName(databaseName); + ConfigureWarnings(optionsBuilder); + ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(extension); cosmosOptionsAction?.Invoke(new CosmosDbContextOptionsBuilder(optionsBuilder)); @@ -186,6 +190,8 @@ public static DbContextOptionsBuilder UseCosmos( .WithTokenCredential(tokenCredential) .WithDatabaseName(databaseName); + ConfigureWarnings(optionsBuilder); + ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(extension); cosmosOptionsAction?.Invoke(new CosmosDbContextOptionsBuilder(optionsBuilder)); @@ -247,10 +253,25 @@ public static DbContextOptionsBuilder UseCosmos( .WithConnectionString(connectionString) .WithDatabaseName(databaseName); + ConfigureWarnings(optionsBuilder); + ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(extension); cosmosOptionsAction?.Invoke(new CosmosDbContextOptionsBuilder(optionsBuilder)); return optionsBuilder; } + + private static void ConfigureWarnings(DbContextOptionsBuilder optionsBuilder) + { + var coreOptionsExtension + = optionsBuilder.Options.FindExtension() + ?? new CoreOptionsExtension(); + + coreOptionsExtension = coreOptionsExtension.WithWarningsConfiguration( + coreOptionsExtension.WarningsConfiguration.TryWithExplicit( + CosmosEventId.SyncNotSupported, WarningBehavior.Throw)); + + ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(coreOptionsExtension); + } } diff --git a/src/EFCore.Cosmos/Properties/CosmosStrings.Designer.cs b/src/EFCore.Cosmos/Properties/CosmosStrings.Designer.cs index 773f416d117..e7561a9f10a 100644 --- a/src/EFCore.Cosmos/Properties/CosmosStrings.Designer.cs +++ b/src/EFCore.Cosmos/Properties/CosmosStrings.Designer.cs @@ -586,5 +586,30 @@ public static FallbackEventDefinition LogExecutedReadNext(IDiagnosticsLogger log return (EventDefinition)definition; } + + /// + /// Azure Cosmos DB does not support synchronous I/O. Make sure to use and correctly await only async methods when using Entity Framework Core to access Azure Cosmos DB. See https://aka.ms/ef-cosmos-nosync for more information. + /// + public static EventDefinition LogSyncNotSupported(IDiagnosticsLogger logger) + { + var definition = ((Diagnostics.Internal.CosmosLoggingDefinitions)logger.Definitions).LogSyncNotSupported; + if (definition == null) + { + definition = NonCapturingLazyInitializer.EnsureInitialized( + ref ((Diagnostics.Internal.CosmosLoggingDefinitions)logger.Definitions).LogSyncNotSupported, + logger, + static logger => new EventDefinition( + logger.Options, + CosmosEventId.SyncNotSupported, + LogLevel.Error, + "CosmosEventId.SyncNotSupported", + level => LoggerMessage.Define( + level, + CosmosEventId.SyncNotSupported, + _resourceManager.GetString("LogSyncNotSupported")!))); + } + + return (EventDefinition)definition; + } } } diff --git a/src/EFCore.Cosmos/Properties/CosmosStrings.resx b/src/EFCore.Cosmos/Properties/CosmosStrings.resx index e4494aa5e7f..e5815bbdd9b 100644 --- a/src/EFCore.Cosmos/Properties/CosmosStrings.resx +++ b/src/EFCore.Cosmos/Properties/CosmosStrings.resx @@ -1,17 +1,17 @@  - @@ -187,6 +187,10 @@ Executing SQL query for container '{containerId}' in partition '{partitionKey}' [Parameters=[{parameters}]]{newLine}{commandText} Information CosmosEventId.ExecutingSqlQuery string string? string string string + + Azure Cosmos DB does not support synchronous I/O. Make sure to use and correctly await only async methods when using Entity Framework Core to access Azure Cosmos DB. See https://aka.ms/ef-cosmos-nosync for more information. + Error CosmosEventId.SyncNotSupported + 'Reverse' could not be translated to the server because there is no ordering on the server side. diff --git a/src/EFCore.Cosmos/Storage/Internal/CosmosClientWrapper.cs b/src/EFCore.Cosmos/Storage/Internal/CosmosClientWrapper.cs index 3bd43272772..1c1fbfb30fa 100644 --- a/src/EFCore.Cosmos/Storage/Internal/CosmosClientWrapper.cs +++ b/src/EFCore.Cosmos/Storage/Internal/CosmosClientWrapper.cs @@ -41,6 +41,7 @@ public class CosmosClientWrapper : ICosmosClientWrapper private readonly string _databaseId; private readonly IExecutionStrategy _executionStrategy; private readonly IDiagnosticsLogger _commandLogger; + private readonly IDiagnosticsLogger _databaseLogger; private readonly bool? _enableContentResponseOnWrite; static CosmosClientWrapper() @@ -61,7 +62,8 @@ public CosmosClientWrapper( ISingletonCosmosClientWrapper singletonWrapper, IDbContextOptions dbContextOptions, IExecutionStrategy executionStrategy, - IDiagnosticsLogger commandLogger) + IDiagnosticsLogger commandLogger, + IDiagnosticsLogger databaseLogger) { var options = dbContextOptions.FindExtension(); @@ -69,6 +71,7 @@ public CosmosClientWrapper( _databaseId = options!.DatabaseName; _executionStrategy = executionStrategy; _commandLogger = commandLogger; + _databaseLogger = databaseLogger; _enableContentResponseOnWrite = options.EnableContentResponseOnWrite; } @@ -82,7 +85,11 @@ private CosmosClient Client /// doing so can result in application failures when updating to a new Entity Framework Core release. /// public virtual bool CreateDatabaseIfNotExists(ThroughputProperties? throughput) - => _executionStrategy.Execute((throughput, this), CreateDatabaseIfNotExistsOnce, null); + { + _databaseLogger.SyncNotSupported(); + + return _executionStrategy.Execute((throughput, this), CreateDatabaseIfNotExistsOnce, null); + } private static bool CreateDatabaseIfNotExistsOnce( DbContext? context, @@ -121,7 +128,11 @@ private static async Task CreateDatabaseIfNotExistsOnceAsync( /// doing so can result in application failures when updating to a new Entity Framework Core release. /// public virtual bool DeleteDatabase() - => _executionStrategy.Execute(this, DeleteDatabaseOnce, null); + { + _databaseLogger.SyncNotSupported(); + + return _executionStrategy.Execute(this, DeleteDatabaseOnce, null); + } private static bool DeleteDatabaseOnce( DbContext? context, @@ -162,7 +173,11 @@ private static async Task DeleteDatabaseOnceAsync( /// doing so can result in application failures when updating to a new Entity Framework Core release. /// public virtual bool CreateContainerIfNotExists(ContainerProperties properties) - => _executionStrategy.Execute((properties, this), CreateContainerIfNotExistsOnce, null); + { + _databaseLogger.SyncNotSupported(); + + return _executionStrategy.Execute((properties, this), CreateContainerIfNotExistsOnce, null); + } private static bool CreateContainerIfNotExistsOnce( DbContext context, @@ -215,7 +230,11 @@ public virtual bool CreateItem( string containerId, JToken document, IUpdateEntry entry) - => _executionStrategy.Execute((containerId, document, entry, this), CreateItemOnce, null); + { + _databaseLogger.SyncNotSupported(); + + return _executionStrategy.Execute((containerId, document, entry, this), CreateItemOnce, null); + } private static bool CreateItemOnce( DbContext context, @@ -286,7 +305,11 @@ public virtual bool ReplaceItem( string documentId, JObject document, IUpdateEntry entry) - => _executionStrategy.Execute((collectionId, documentId, document, entry, this), ReplaceItemOnce, null); + { + _databaseLogger.SyncNotSupported(); + + return _executionStrategy.Execute((collectionId, documentId, document, entry, this), ReplaceItemOnce, null); + } private static bool ReplaceItemOnce( DbContext context, @@ -358,7 +381,11 @@ public virtual bool DeleteItem( string containerId, string documentId, IUpdateEntry entry) - => _executionStrategy.Execute((containerId, documentId, entry, this), DeleteItemOnce, null); + { + _databaseLogger.SyncNotSupported(); + + return _executionStrategy.Execute((containerId, documentId, entry, this), DeleteItemOnce, null); + } private static bool DeleteItemOnce( DbContext context, @@ -508,6 +535,8 @@ public virtual IEnumerable ExecuteSqlQuery( string? partitionKey, CosmosSqlQuery query) { + _databaseLogger.SyncNotSupported(); + _commandLogger.ExecutingSqlQuery(containerId, partitionKey, query); return new DocumentEnumerable(this, containerId, partitionKey, query); @@ -540,6 +569,8 @@ public virtual IAsyncEnumerable ExecuteSqlQueryAsync( string? partitionKey, string resourceId) { + _databaseLogger.SyncNotSupported(); + _commandLogger.ExecutingReadItem(containerId, partitionKey, resourceId); var response = _executionStrategy.Execute((containerId, partitionKey, resourceId, this), CreateSingleItemQuery, null); diff --git a/test/EFCore.AspNet.Specification.Tests/GrpcTestBase.cs b/test/EFCore.AspNet.Specification.Tests/GrpcTestBase.cs index 72cb364cf5c..772d861bc5c 100644 --- a/test/EFCore.AspNet.Specification.Tests/GrpcTestBase.cs +++ b/test/EFCore.AspNet.Specification.Tests/GrpcTestBase.cs @@ -137,7 +137,7 @@ public abstract class GrpcFixtureBase : SharedStoreFixtureBase protected override string StoreName => "GrpcTest"; - protected override void Seed(GrpcContext context) + protected override Task SeedAsync(GrpcContext context) { var post = new Post { @@ -153,7 +153,7 @@ protected override void Seed(GrpcContext context) context.Add(post); - context.SaveChanges(); + return context.SaveChangesAsync(); } } } diff --git a/test/EFCore.Cosmos.FunctionalTests/BuiltInDataTypesCosmosTest.cs b/test/EFCore.Cosmos.FunctionalTests/BuiltInDataTypesCosmosTest.cs index 35542bf2885..3f495ae7291 100644 --- a/test/EFCore.Cosmos.FunctionalTests/BuiltInDataTypesCosmosTest.cs +++ b/test/EFCore.Cosmos.FunctionalTests/BuiltInDataTypesCosmosTest.cs @@ -7,7 +7,8 @@ namespace Microsoft.EntityFrameworkCore; #nullable disable -public class BuiltInDataTypesCosmosTest(BuiltInDataTypesCosmosTest.BuiltInDataTypesCosmosFixture fixture) : BuiltInDataTypesTestBase(fixture) +public class BuiltInDataTypesCosmosTest(BuiltInDataTypesCosmosTest.BuiltInDataTypesCosmosFixture fixture) + : BuiltInDataTypesTestBase(fixture) { [ConditionalTheory(Skip = "Issue #17246 No Explicit Convert")] public override Task Can_filter_projection_with_inline_enum_variable(bool async) @@ -18,33 +19,32 @@ public override Task Can_filter_projection_with_captured_enum_variable(bool asyn => base.Can_filter_projection_with_captured_enum_variable(async); [ConditionalFact(Skip = "Issue #17246 No Explicit Convert")] - public override void Can_query_with_null_parameters_using_any_nullable_data_type() + public override Task Can_query_with_null_parameters_using_any_nullable_data_type() => base.Can_query_with_null_parameters_using_any_nullable_data_type(); [ConditionalFact(Skip = "Issue #16920")] - public override void Can_insert_and_read_back_with_string_key() + public override Task Can_insert_and_read_back_with_string_key() => base.Can_insert_and_read_back_with_string_key(); [ConditionalFact(Skip = "Issue #16920")] - public override void Can_insert_and_read_back_with_binary_key() + public override Task Can_insert_and_read_back_with_binary_key() => base.Can_insert_and_read_back_with_binary_key(); - public override void Can_perform_query_with_max_length() - { + public override Task Can_perform_query_with_max_length() // TODO: Better translation of sequential equality #17246 - } + => Task.CompletedTask; [ConditionalFact(Skip = "Issue #17670")] - public override void Can_read_back_mapped_enum_from_collection_first_or_default() + public override Task Can_read_back_mapped_enum_from_collection_first_or_default() => base.Can_read_back_mapped_enum_from_collection_first_or_default(); [ConditionalFact(Skip = "Issue #17246")] - public override void Can_read_back_bool_mapped_as_int_through_navigation() + public override Task Can_read_back_bool_mapped_as_int_through_navigation() => base.Can_read_back_bool_mapped_as_int_through_navigation(); - public override void Object_to_string_conversion() + public override async Task Object_to_string_conversion() { - base.Object_to_string_conversion(); + await base.Object_to_string_conversion(); AssertSql( """ diff --git a/test/EFCore.Cosmos.FunctionalTests/ConcurrencyDetectorDisabledCosmosTest.cs b/test/EFCore.Cosmos.FunctionalTests/ConcurrencyDetectorDisabledCosmosTest.cs index 1e89a8cb57f..24b7cc8f91e 100644 --- a/test/EFCore.Cosmos.FunctionalTests/ConcurrencyDetectorDisabledCosmosTest.cs +++ b/test/EFCore.Cosmos.FunctionalTests/ConcurrencyDetectorDisabledCosmosTest.cs @@ -5,13 +5,35 @@ namespace Microsoft.EntityFrameworkCore; #nullable disable -public class ConcurrencyDetectorDisabledCosmosTest(ConcurrencyDetectorDisabledCosmosTest.ConcurrencyDetectorCosmosFixture fixture) : ConcurrencyDetectorDisabledTestBase< - ConcurrencyDetectorDisabledCosmosTest.ConcurrencyDetectorCosmosFixture>(fixture) +public class ConcurrencyDetectorDisabledCosmosTest(ConcurrencyDetectorDisabledCosmosTest.ConcurrencyDetectorCosmosFixture fixture) + : ConcurrencyDetectorDisabledTestBase< + ConcurrencyDetectorDisabledCosmosTest.ConcurrencyDetectorCosmosFixture>(fixture) { [ConditionalTheory(Skip = "Issue #17246")] public override Task Any(bool async) => base.Any(async); + public override Task SaveChanges(bool async) + => CosmosTestHelpers.Instance.NoSyncTest(async, a => base.SaveChanges(a)); + + public override Task Count(bool async) + => CosmosTestHelpers.Instance.NoSyncTest(async, a => base.Count(a)); + + public override Task Find(bool async) + => CosmosTestHelpers.Instance.NoSyncTest(async, a => base.Find(a)); + + public override Task First(bool async) + => CosmosTestHelpers.Instance.NoSyncTest(async, a => base.First(a)); + + public override Task Last(bool async) + => CosmosTestHelpers.Instance.NoSyncTest(async, a => base.Last(a)); + + public override Task Single(bool async) + => CosmosTestHelpers.Instance.NoSyncTest(async, a => base.Single(a)); + + public override Task ToList(bool async) + => CosmosTestHelpers.Instance.NoSyncTest(async, a => base.ToList(a)); + public class ConcurrencyDetectorCosmosFixture : ConcurrencyDetectorFixtureBase { protected override ITestStoreFactory TestStoreFactory diff --git a/test/EFCore.Cosmos.FunctionalTests/ConfigPatternsCosmosTest.cs b/test/EFCore.Cosmos.FunctionalTests/ConfigPatternsCosmosTest.cs index 2ba3d4e129f..344cbbe1f50 100644 --- a/test/EFCore.Cosmos.FunctionalTests/ConfigPatternsCosmosTest.cs +++ b/test/EFCore.Cosmos.FunctionalTests/ConfigPatternsCosmosTest.cs @@ -8,7 +8,8 @@ namespace Microsoft.EntityFrameworkCore; #nullable disable -public class ConfigPatternsCosmosTest(ConfigPatternsCosmosTest.CosmosFixture fixture) : IClassFixture +public class ConfigPatternsCosmosTest(ConfigPatternsCosmosTest.CosmosFixture fixture) + : IClassFixture { private const string DatabaseName = "ConfigPatternsCosmos"; @@ -17,7 +18,7 @@ public class ConfigPatternsCosmosTest(ConfigPatternsCosmosTest.CosmosFixture fix [ConditionalFact] public async Task Cosmos_client_instance_is_shared_between_contexts() { - await using var testDatabase = CosmosTestStore.CreateInitialized(DatabaseName); + await using var testDatabase = await CosmosTestStore.CreateInitializedAsync(DatabaseName); var options = CreateOptions(testDatabase); CosmosClient client; @@ -34,7 +35,7 @@ public async Task Cosmos_client_instance_is_shared_between_contexts() Assert.Same(client, context.Database.GetCosmosClient()); } - await using var testDatabase2 = CosmosTestStore.CreateInitialized(DatabaseName, o => o.Region(Regions.AustraliaCentral)); + await using var testDatabase2 = await CosmosTestStore.CreateInitializedAsync(DatabaseName, o => o.Region(Regions.AustraliaCentral)); options = CreateOptions(testDatabase2); using (var context = new CustomerContext(options)) @@ -48,13 +49,13 @@ public async Task Should_not_throw_if_specified_region_is_right() { var regionName = Regions.AustraliaCentral; - await using var testDatabase = CosmosTestStore.CreateInitialized(DatabaseName, o => o.Region(regionName)); + await using var testDatabase = await CosmosTestStore.CreateInitializedAsync(DatabaseName, o => o.Region(regionName)); var options = CreateOptions(testDatabase); var customer = new Customer { Id = 42, Name = "Theon" }; using var context = new CustomerContext(options); - context.Database.EnsureCreated(); + await context.Database.EnsureCreatedAsync(); await context.AddAsync(customer); @@ -67,13 +68,13 @@ public async Task Should_throw_if_specified_region_is_wrong() var exception = await Assert.ThrowsAsync( async () => { - await using var testDatabase = CosmosTestStore.CreateInitialized(DatabaseName, o => o.Region("FakeRegion")); + await using var testDatabase = await CosmosTestStore.CreateInitializedAsync(DatabaseName, o => o.Region("FakeRegion")); var options = CreateOptions(testDatabase); var customer = new Customer { Id = 42, Name = "Theon" }; using var context = new CustomerContext(options); - context.Database.EnsureCreated(); + await context.Database.EnsureCreatedAsync(); await context.AddAsync(customer); @@ -90,13 +91,13 @@ public async Task Should_not_throw_if_specified_connection_mode_is_right() { var connectionMode = ConnectionMode.Direct; - await using var testDatabase = CosmosTestStore.CreateInitialized(DatabaseName, o => o.ConnectionMode(connectionMode)); + await using var testDatabase = await CosmosTestStore.CreateInitializedAsync(DatabaseName, o => o.ConnectionMode(connectionMode)); var options = CreateOptions(testDatabase); var customer = new Customer { Id = 42, Name = "Theon" }; using var context = new CustomerContext(options); - context.Database.EnsureCreated(); + await context.Database.EnsureCreatedAsync(); await context.AddAsync(customer); @@ -109,14 +110,14 @@ public async Task Should_throw_if_specified_connection_mode_is_wrong() var exception = await Assert.ThrowsAsync( async () => { - await using var testDatabase = CosmosTestStore.CreateInitialized( + await using var testDatabase = await CosmosTestStore.CreateInitializedAsync( DatabaseName, o => o.ConnectionMode((ConnectionMode)123456)); var options = CreateOptions(testDatabase); var customer = new Customer { Id = 42, Name = "Theon" }; using var context = new CustomerContext(options); - context.Database.EnsureCreated(); + await context.Database.EnsureCreatedAsync(); await context.AddAsync(customer); diff --git a/test/EFCore.Cosmos.FunctionalTests/CosmosConcurrencyTest.cs b/test/EFCore.Cosmos.FunctionalTests/CosmosConcurrencyTest.cs index d60aff58720..5e04d803e0c 100644 --- a/test/EFCore.Cosmos.FunctionalTests/CosmosConcurrencyTest.cs +++ b/test/EFCore.Cosmos.FunctionalTests/CosmosConcurrencyTest.cs @@ -14,33 +14,43 @@ public class CosmosConcurrencyTest(CosmosConcurrencyTest.CosmosFixture fixture) [ConditionalFact] public virtual Task Adding_the_same_entity_twice_results_in_DbUpdateException() => ConcurrencyTestAsync( - ctx => ctx.Customers.Add( - new Customer - { - Id = "1", Name = "CreatedTwice", - })); + ctx => + { + ctx.Customers.Add( + new Customer + { + Id = "1", Name = "CreatedTwice", + }); + return Task.CompletedTask; + }); [ConditionalFact] public virtual Task Updating_then_deleting_the_same_entity_results_in_DbUpdateConcurrencyException() => ConcurrencyTestAsync( - ctx => ctx.Customers.Add( - new Customer - { - Id = "2", Name = "Added", - }), - ctx => ctx.Customers.Single(c => c.Id == "2").Name = "Updated", - ctx => ctx.Customers.Remove(ctx.Customers.Single(c => c.Id == "2"))); + ctx => + { + ctx.Customers.Add( + new Customer + { + Id = "2", Name = "Added", + }); + return Task.CompletedTask; + }, async ctx => (await ctx.Customers.SingleAsync(c => c.Id == "2")).Name = "Updated", + async ctx => ctx.Customers.Remove(await ctx.Customers.SingleAsync(c => c.Id == "2"))); [ConditionalFact] public virtual Task Updating_then_updating_the_same_entity_results_in_DbUpdateConcurrencyException() => ConcurrencyTestAsync( - ctx => ctx.Customers.Add( - new Customer - { - Id = "3", Name = "Added", - }), - ctx => ctx.Customers.Single(c => c.Id == "3").Name = "Updated", - ctx => ctx.Customers.Single(c => c.Id == "3").Name = "Updated"); + ctx => + { + ctx.Customers.Add( + new Customer + { + Id = "3", Name = "Added", + }); + return Task.CompletedTask; + }, async ctx => (await ctx.Customers.SingleAsync(c => c.Id == "3")).Name = "Updated", + async ctx => (await ctx.Customers.SingleAsync(c => c.Id == "3")).Name = "Updated"); [ConditionalTheory] [InlineData(null)] @@ -49,13 +59,14 @@ public virtual Task Updating_then_updating_the_same_entity_results_in_DbUpdateCo public async Task Etag_is_updated_in_entity_after_SaveChanges(bool? contentResponseOnWriteEnabled) { var options = new DbContextOptionsBuilder(Fixture.CreateOptions()) - .UseCosmos(o => - { - if (contentResponseOnWriteEnabled != null) + .UseCosmos( + o => { - o.ContentResponseOnWriteEnabled(contentResponseOnWriteEnabled.Value); - } - }) + if (contentResponseOnWriteEnabled != null) + { + o.ContentResponseOnWriteEnabled(contentResponseOnWriteEnabled.Value); + } + }) .Options; var customer = new Customer @@ -114,7 +125,7 @@ public async Task Etag_is_updated_in_entity_after_SaveChanges(bool? contentRespo /// the database at the end of the process can be validated. /// protected virtual Task ConcurrencyTestAsync( - Action change) + Func change) where TException : DbUpdateException => ConcurrencyTestAsync( null, change, change); @@ -128,21 +139,33 @@ protected virtual Task ConcurrencyTestAsync( /// the database at the end of the process can be validated. /// protected virtual async Task ConcurrencyTestAsync( - Action seedAction, - Action storeChange, - Action clientChange) + Func seedAction, + Func storeChange, + Func clientChange) where TException : DbUpdateException { using var outerContext = CreateContext(); await Fixture.TestStore.CleanAsync(outerContext); - seedAction?.Invoke(outerContext); + + if (seedAction != null) + { + await seedAction(outerContext); + } + await outerContext.SaveChangesAsync(); - clientChange?.Invoke(outerContext); + if (clientChange != null) + { + await clientChange(outerContext); + } using (var innerContext = CreateContext()) { - storeChange?.Invoke(innerContext); + if (storeChange != null) + { + await storeChange(innerContext); + } + await innerContext.SaveChangesAsync(); } diff --git a/test/EFCore.Cosmos.FunctionalTests/CustomConvertersCosmosTest.cs b/test/EFCore.Cosmos.FunctionalTests/CustomConvertersCosmosTest.cs index e70e4518e6d..d1c24275fa3 100644 --- a/test/EFCore.Cosmos.FunctionalTests/CustomConvertersCosmosTest.cs +++ b/test/EFCore.Cosmos.FunctionalTests/CustomConvertersCosmosTest.cs @@ -24,53 +24,53 @@ public override Task Can_filter_projection_with_captured_enum_variable(bool asyn => base.Can_filter_projection_with_captured_enum_variable(async); [ConditionalFact(Skip = "Issue #17246 No Explicit Convert")] - public override void Can_query_with_null_parameters_using_any_nullable_data_type() + public override Task Can_query_with_null_parameters_using_any_nullable_data_type() => base.Can_query_with_null_parameters_using_any_nullable_data_type(); [ConditionalFact(Skip = "Issue #16920")] - public override void Can_insert_and_read_back_with_string_key() + public override Task Can_insert_and_read_back_with_string_key() => base.Can_insert_and_read_back_with_string_key(); [ConditionalFact(Skip = "Issue #17246 No Explicit Convert")] - public override void Can_query_and_update_with_conversion_for_custom_type() + public override Task Can_query_and_update_with_conversion_for_custom_type() => base.Can_query_and_update_with_conversion_for_custom_type(); [ConditionalFact(Skip = "Issue #16920")] - public override void Can_query_and_update_with_nullable_converter_on_primary_key() + public override Task Can_query_and_update_with_nullable_converter_on_primary_key() => base.Can_query_and_update_with_nullable_converter_on_primary_key(); [ConditionalFact(Skip = "Issue #16920")] - public override void Can_insert_and_read_back_with_binary_key() + public override Task Can_insert_and_read_back_with_binary_key() => base.Can_insert_and_read_back_with_binary_key(); [ConditionalFact(Skip = "Issue #16920")] - public override void Can_insert_and_read_back_with_case_insensitive_string_key() + public override Task Can_insert_and_read_back_with_case_insensitive_string_key() => base.Can_insert_and_read_back_with_case_insensitive_string_key(); [ConditionalFact(Skip = "Issue #17246 No Explicit Convert")] - public override void Can_insert_and_query_struct_to_string_converter_for_pk() + public override Task Can_insert_and_query_struct_to_string_converter_for_pk() => base.Can_insert_and_query_struct_to_string_converter_for_pk(); [ConditionalFact(Skip = "Issue #17670")] - public override void Can_read_back_mapped_enum_from_collection_first_or_default() + public override Task Can_read_back_mapped_enum_from_collection_first_or_default() => base.Can_read_back_mapped_enum_from_collection_first_or_default(); [ConditionalFact(Skip = "Issue #17246")] - public override void Can_read_back_bool_mapped_as_int_through_navigation() + public override Task Can_read_back_bool_mapped_as_int_through_navigation() => base.Can_read_back_bool_mapped_as_int_through_navigation(); [ConditionalFact(Skip = "Issue #17246")] - public override void Value_conversion_is_appropriately_used_for_join_condition() + public override Task Value_conversion_is_appropriately_used_for_join_condition() => base.Value_conversion_is_appropriately_used_for_join_condition(); [ConditionalFact(Skip = "Issue #17246")] - public override void Value_conversion_is_appropriately_used_for_left_join_condition() + public override Task Value_conversion_is_appropriately_used_for_left_join_condition() => base.Value_conversion_is_appropriately_used_for_left_join_condition(); [ConditionalFact] - public override void Where_bool_gets_converted_to_equality_when_value_conversion_is_used() + public override async Task Where_bool_gets_converted_to_equality_when_value_conversion_is_used() { - base.Where_bool_gets_converted_to_equality_when_value_conversion_is_used(); + await base.Where_bool_gets_converted_to_equality_when_value_conversion_is_used(); AssertSql( """ @@ -81,9 +81,9 @@ FROM root c } [ConditionalFact] - public override void Where_negated_bool_gets_converted_to_equality_when_value_conversion_is_used() + public override async Task Where_negated_bool_gets_converted_to_equality_when_value_conversion_is_used() { - base.Where_negated_bool_gets_converted_to_equality_when_value_conversion_is_used(); + await base.Where_negated_bool_gets_converted_to_equality_when_value_conversion_is_used(); AssertSql( """ @@ -94,9 +94,9 @@ FROM root c } [ConditionalFact] - public override void Where_bool_gets_converted_to_equality_when_value_conversion_is_used_using_EFProperty() + public override async Task Where_bool_gets_converted_to_equality_when_value_conversion_is_used_using_EFProperty() { - base.Where_bool_gets_converted_to_equality_when_value_conversion_is_used_using_EFProperty(); + await base.Where_bool_gets_converted_to_equality_when_value_conversion_is_used_using_EFProperty(); AssertSql( """ @@ -107,9 +107,9 @@ FROM root c } [ConditionalFact] - public override void Where_bool_gets_converted_to_equality_when_value_conversion_is_used_using_indexer() + public override async Task Where_bool_gets_converted_to_equality_when_value_conversion_is_used_using_indexer() { - base.Where_bool_gets_converted_to_equality_when_value_conversion_is_used_using_indexer(); + await base.Where_bool_gets_converted_to_equality_when_value_conversion_is_used_using_indexer(); AssertSql( """ @@ -136,6 +136,9 @@ public override void GroupBy_converted_enum() public override void Infer_type_mapping_from_in_subquery_to_item() => Assert.Throws(() => base.Infer_type_mapping_from_in_subquery_to_item()); + public override Task Can_query_custom_type_not_mapped_by_default_equality(bool async) + => CosmosTestHelpers.Instance.NoSyncTest(async, a => base.Can_query_custom_type_not_mapped_by_default_equality(a)); + private void AssertSql(params string[] expected) => Fixture.TestSqlLoggerFactory.AssertBaseline(expected); diff --git a/test/EFCore.Cosmos.FunctionalTests/EmbeddedDocumentsTest.cs b/test/EFCore.Cosmos.FunctionalTests/EmbeddedDocumentsTest.cs index b745c1a85ec..bd9f333f820 100644 --- a/test/EFCore.Cosmos.FunctionalTests/EmbeddedDocumentsTest.cs +++ b/test/EFCore.Cosmos.FunctionalTests/EmbeddedDocumentsTest.cs @@ -25,7 +25,7 @@ public EmbeddedDocumentsTest(CosmosFixture fixture, ITestOutputHelper testOutput [ConditionalFact(Skip = "Issue #17670")] public virtual async Task Can_update_dependents() { - var options = Fixture.CreateOptions(); + var options = await Fixture.CreateOptions(); Operator firstOperator; Engine firstEngine; using (var context = new EmbeddedTransportationContext(options)) @@ -53,11 +53,11 @@ public virtual async Task Can_update_dependents() [ConditionalFact] public virtual async Task Can_update_owner_with_dependents() { - var options = Fixture.CreateOptions(); + var options = await Fixture.CreateOptions(); Operator firstOperator; using (var context = new EmbeddedTransportationContext(options)) { - firstOperator = context.Set().OrderBy(o => o.Name).First().Operator; + firstOperator = (await context.Set().OrderBy(o => o.Name).FirstAsync()).Operator; firstOperator.Name += "1"; await context.SaveChangesAsync(); @@ -73,7 +73,7 @@ public virtual async Task Can_update_owner_with_dependents() [ConditionalFact] public virtual async Task Can_attach_owner_with_dependents() { - var options = Fixture.CreateOptions(); + var options = await Fixture.CreateOptions(); Vehicle firstVehicle; using (var context = new EmbeddedTransportationContext(options)) { @@ -104,15 +104,16 @@ public virtual async Task Can_attach_owner_with_dependents() [InlineData(true)] public virtual async Task Can_manipulate_embedded_collections(bool useIds) { - var options = Fixture.CreateOptions(seed: false); - var swappedOptions = Fixture.CreateOptions(modelBuilder => modelBuilder.Entity( + var options = await Fixture.CreateOptions(seed: false); + var swappedOptions = await Fixture.CreateOptions( + modelBuilder => modelBuilder.Entity( eb => eb.OwnsMany( v => v.Addresses, b => { b.OwnsMany(a => a.Notes).ToJsonProperty("IdNotes"); b.OwnsMany(a => a.IdNotes).ToJsonProperty("Notes"); })), - seed: false); + seed: false); Address existingAddress1Person2; Address existingAddress1Person3; @@ -318,6 +319,7 @@ async Task AssertState(EmbeddedTransportationContext context, bool useIds) Assert.Equal(1, notes.First().Id); Assert.Equal(2, notes.Last().Id); } + Assert.Equal("First note", notes.First().Content); Assert.Equal("Second note", notes.Last().Content); } @@ -390,38 +392,34 @@ async Task AssertState(EmbeddedTransportationContext context, bool useIds) [ConditionalFact] public virtual async Task Old_still_works() { - var options = Fixture.CreateOptions(seed: false); - var swappedOptions = Fixture.CreateOptions(modelBuilder => modelBuilder.Entity( + var options = await Fixture.CreateOptions(seed: false); + var swappedOptions = await Fixture.CreateOptions( + modelBuilder => modelBuilder.Entity( eb => eb.OwnsMany( v => v.Addresses, b => { b.OwnsMany(a => a.Notes).ToJsonProperty("IdNotes"); b.OwnsMany(a => a.IdNotes).ToJsonProperty("Notes"); })), - seed: false); + seed: false); using (var context = new EmbeddedTransportationContext(options)) { - await context.AddAsync(new Person - { - Id = 1, - Addresses = new List
+ await context.AddAsync( + new Person { - new() + Id = 1, + Addresses = new List
{ - Street = "Second", - City = "Village", - Notes = new List - { - new() { Content = "First note" } - }, - IdNotes = new List + new() { - new() { Id = 3, Content = "Second note" } + Street = "Second", + City = "Village", + Notes = new List { new() { Content = "First note" } }, + IdNotes = new List { new() { Id = 3, Content = "Second note" } } } } - } - }); + }); await context.SaveChangesAsync(); } @@ -459,7 +457,7 @@ public record struct CosmosPage(List Results, string ContinuationToken); [ConditionalFact] public virtual async Task Properties_on_owned_types_can_be_client_generated() { - var options = Fixture.CreateOptions(seed: false); + var options = await Fixture.CreateOptions(seed: false); using (var context = new EmbeddedTransportationContext(options)) { @@ -483,7 +481,7 @@ public virtual async Task Properties_on_owned_types_can_be_client_generated() [ConditionalFact] public virtual async Task Can_use_non_int_keys_for_embedded_entities() { - var options = Fixture.CreateOptions( + var options = await Fixture.CreateOptions( modelBuilder => { modelBuilder.Entity( @@ -529,10 +527,10 @@ public virtual async Task Can_use_non_int_keys_for_embedded_entities() [ConditionalFact] public virtual async Task Can_query_and_modify_nested_embedded_types() { - var options = Fixture.CreateOptions(); + var options = await Fixture.CreateOptions(); using (var context = new EmbeddedTransportationContext(options)) { - var missile = context.Set().First(v => v.Name == "AIM-9M Sidewinder"); + var missile = await context.Set().FirstAsync(v => v.Name == "AIM-9M Sidewinder"); Assert.Equal("Heat-seeking", missile.Operator.Details.Type); @@ -543,7 +541,7 @@ public virtual async Task Can_query_and_modify_nested_embedded_types() using (var context = new EmbeddedTransportationContext(options)) { - var missile = context.Set().First(v => v.Name == "AIM-9M Sidewinder"); + var missile = await context.Set().FirstAsync(v => v.Name == "AIM-9M Sidewinder"); Assert.Equal("IR", missile.Operator.Details.Type); } @@ -552,7 +550,7 @@ public virtual async Task Can_query_and_modify_nested_embedded_types() [ConditionalFact] public virtual async Task Can_query_just_embedded_reference() { - var options = Fixture.CreateOptions(); + var options = await Fixture.CreateOptions(); using var context = new EmbeddedTransportationContext(options); var firstOperator = await context.Set().OrderBy(o => o.Name).Select(v => v.Operator) .AsNoTracking().FirstAsync(); @@ -564,7 +562,7 @@ public virtual async Task Can_query_just_embedded_reference() [ConditionalFact] public virtual async Task Can_query_just_embedded_collection() { - var options = Fixture.CreateOptions(seed: false); + var options = await Fixture.CreateOptions(seed: false); using (var context = new EmbeddedTransportationContext(options)) { @@ -592,7 +590,7 @@ await context.AddAsync( [ConditionalFact] public virtual async Task Inserting_dependent_without_principal_throws() { - var options = Fixture.CreateOptions(seed: false); + var options = await Fixture.CreateOptions(seed: false); using var context = new EmbeddedTransportationContext(options); await context.AddAsync( new LicensedOperator @@ -611,7 +609,7 @@ await context.AddAsync( [ConditionalFact] public virtual async Task Can_change_nested_instance_non_derived() { - var options = Fixture.CreateOptions(); + var options = await Fixture.CreateOptions(); using (var context = new EmbeddedTransportationContext(options)) { var bike = await context.Vehicles.SingleAsync(v => v.Name == "Trek Pro Fit Madone 6 Series"); @@ -636,7 +634,7 @@ public virtual async Task Can_change_nested_instance_non_derived() [ConditionalFact] public virtual async Task Can_change_principal_instance_non_derived() { - var options = Fixture.CreateOptions(); + var options = await Fixture.CreateOptions(); using (var context = new EmbeddedTransportationContext(options)) { var bike = await context.Vehicles.SingleAsync(v => v.Name == "Trek Pro Fit Madone 6 Series"); @@ -685,18 +683,18 @@ protected override ITestStoreFactory TestStoreFactory public virtual CosmosTestStore TestStore { get; } - public EmbeddedTransportationContextOptions CreateOptions( + public async Task CreateOptions( Action onModelCreating = null, bool seed = true) { var options = CreateOptions(TestStore); var embeddedOptions = new EmbeddedTransportationContextOptions(options, onModelCreating); - TestStore.Initialize( - ServiceProvider, () => new EmbeddedTransportationContext(embeddedOptions), c => + await TestStore.InitializeAsync( + ServiceProvider, () => new EmbeddedTransportationContext(embeddedOptions), async c => { if (seed) { - ((TransportationContext)c).Seed(); + await ((TransportationContext)c).SeedAsync(); } }); @@ -710,7 +708,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con protected override object GetAdditionalModelCacheKey(DbContext context) { var options = ((EmbeddedTransportationContext)context).Options; - return options.OnModelCreating == null + return options.OnModelCreating == null ? null : options; } diff --git a/test/EFCore.Cosmos.FunctionalTests/EndToEndCosmosTest.cs b/test/EFCore.Cosmos.FunctionalTests/EndToEndCosmosTest.cs index f818a133d33..8d052c48581 100644 --- a/test/EFCore.Cosmos.FunctionalTests/EndToEndCosmosTest.cs +++ b/test/EFCore.Cosmos.FunctionalTests/EndToEndCosmosTest.cs @@ -12,41 +12,44 @@ namespace Microsoft.EntityFrameworkCore; #nullable disable -public class EndToEndCosmosTest(EndToEndCosmosTest.CosmosFixture fixture) : IClassFixture +public class EndToEndCosmosTest : NonSharedModelTestBase { - private const string DatabaseName = "CosmosEndToEndTest"; - - protected CosmosFixture Fixture { get; } = fixture; - [ConditionalFact] - public void Can_add_update_delete_end_to_end() + public async Task Can_add_update_delete_end_to_end() { - var options = Fixture.CreateOptions(); + var contextFactory = await InitializeAsync( + b => b.Entity(), + shouldLogCategory: _ => true, + onConfiguring: o => o.ConfigureWarnings(w => w.Log(CosmosEventId.SyncNotSupported))); var customer = new Customer { Id = 42, Name = "Theon" }; - using (var context = new CustomerContext(options)) + using (var context = contextFactory.CreateContext()) { + ListLoggerFactory.Clear(); context.Database.EnsureCreated(); context.Add(customer); context.SaveChanges(); - var logEntry = TestSqlLoggerFactory.Log.Single(); + var logEntry = ListLoggerFactory.Log.Single(e => e.Id == CosmosEventId.ExecutedCreateItem); Assert.Equal(LogLevel.Information, logEntry.Level); Assert.Contains("CreateItem", logEntry.Message); + + Assert.Equal(3, ListLoggerFactory.Log.Count(l => l.Id == CosmosEventId.SyncNotSupported)); } - using (var context = new CustomerContext(options)) + using (var context = contextFactory.CreateContext()) { - TestSqlLoggerFactory.Clear(); + ListLoggerFactory.Clear(); var customerFromStore = context.Set().Single(); - var logEntry = TestSqlLoggerFactory.Log.Last(); + var logEntry = ListLoggerFactory.Log.Single(e => e.Id == CosmosEventId.ExecutedReadNext); Assert.Equal(LogLevel.Information, logEntry.Level); Assert.Contains("ReadNext", logEntry.Message); - TestSqlLoggerFactory.Clear(); + Assert.Single(ListLoggerFactory.Log.Where(l => l.Id == CosmosEventId.SyncNotSupported)); + ListLoggerFactory.Clear(); Assert.Equal(42, customerFromStore.Id); Assert.Equal("Theon", customerFromStore.Name); @@ -55,20 +58,23 @@ public void Can_add_update_delete_end_to_end() context.SaveChanges(); - logEntry = TestSqlLoggerFactory.Log.Single(); + logEntry = ListLoggerFactory.Log.Single(e => e.Id == CosmosEventId.ExecutedReplaceItem); Assert.Equal(LogLevel.Information, logEntry.Level); Assert.Contains("ReplaceItem", logEntry.Message); + + Assert.Single(ListLoggerFactory.Log.Where(l => l.Id == CosmosEventId.SyncNotSupported)); } - using (var context = new CustomerContext(options)) + using (var context = contextFactory.CreateContext()) { - TestSqlLoggerFactory.Clear(); + ListLoggerFactory.Clear(); var customerFromStore = context.Find(42); - var logEntry = TestSqlLoggerFactory.Log.Last(); + var logEntry = ListLoggerFactory.Log.Single(e => e.Id == CosmosEventId.ExecutedReadItem); Assert.Equal(LogLevel.Information, logEntry.Level); Assert.Contains("ReadItem", logEntry.Message); - TestSqlLoggerFactory.Clear(); + Assert.Single(ListLoggerFactory.Log.Where(l => l.Id == CosmosEventId.SyncNotSupported)); + ListLoggerFactory.Clear(); Assert.Equal(42, customerFromStore.Id); Assert.Equal("Theon Greyjoy", customerFromStore.Name); @@ -77,25 +83,33 @@ public void Can_add_update_delete_end_to_end() context.SaveChanges(); - logEntry = TestSqlLoggerFactory.Log.Single(); + logEntry = ListLoggerFactory.Log.Single(e => e.Id == CosmosEventId.ExecutedDeleteItem); Assert.Equal(LogLevel.Information, logEntry.Level); Assert.Contains("DeleteItem", logEntry.Message); + + Assert.Single(ListLoggerFactory.Log.Where(l => l.Id == CosmosEventId.SyncNotSupported)); } - using (var context = new CustomerContext(options)) + using (var context = contextFactory.CreateContext()) { + ListLoggerFactory.Clear(); Assert.Empty(context.Set().ToList()); + + Assert.Single(ListLoggerFactory.Log.Where(l => l.Id == CosmosEventId.SyncNotSupported)); } } [ConditionalFact] public async Task Can_add_update_delete_end_to_end_async() { - var options = Fixture.CreateOptions(); + var contextFactory = await InitializeAsync( + b => b.Entity(), + shouldLogCategory: _ => true, + onConfiguring: o => o.ConfigureWarnings(w => w.Log(CosmosEventId.SyncNotSupported))); var customer = new Customer { Id = 42, Name = "Theon" }; - using (var context = new CustomerContext(options)) + using (var context = contextFactory.CreateContext()) { await context.Database.EnsureCreatedAsync(); @@ -103,19 +117,22 @@ public async Task Can_add_update_delete_end_to_end_async() await context.SaveChangesAsync(); - var logEntry = TestSqlLoggerFactory.Log.Single(); + var logEntry = ListLoggerFactory.Log.Single(e => e.Id == CosmosEventId.ExecutedCreateItem); Assert.Equal(LogLevel.Information, logEntry.Level); Assert.Contains("CreateItem", logEntry.Message); + + Assert.Empty(ListLoggerFactory.Log.Where(l => l.Id == CosmosEventId.SyncNotSupported)); } - using (var context = new CustomerContext(options)) + using (var context = contextFactory.CreateContext()) { var customerFromStore = await context.Set().SingleAsync(); - var logEntry = TestSqlLoggerFactory.Log.Last(); + var logEntry = ListLoggerFactory.Log.Single(e => e.Id == CosmosEventId.ExecutedReadNext); Assert.Equal(LogLevel.Information, logEntry.Level); Assert.Contains("ReadNext", logEntry.Message); - TestSqlLoggerFactory.Clear(); + Assert.Empty(ListLoggerFactory.Log.Where(l => l.Id == CosmosEventId.SyncNotSupported)); + ListLoggerFactory.Clear(); Assert.Equal(42, customerFromStore.Id); Assert.Equal("Theon", customerFromStore.Name); @@ -124,19 +141,21 @@ public async Task Can_add_update_delete_end_to_end_async() await context.SaveChangesAsync(); - logEntry = TestSqlLoggerFactory.Log.Single(); + logEntry = ListLoggerFactory.Log.Single(e => e.Id == CosmosEventId.ExecutedReplaceItem); Assert.Equal(LogLevel.Information, logEntry.Level); Assert.Contains("ReplaceItem", logEntry.Message); + Assert.Empty(ListLoggerFactory.Log.Where(l => l.Id == CosmosEventId.SyncNotSupported)); } - using (var context = new CustomerContext(options)) + using (var context = contextFactory.CreateContext()) { var customerFromStore = await context.FindAsync(42); - var logEntry = TestSqlLoggerFactory.Log.Last(); + var logEntry = ListLoggerFactory.Log.Single(e => e.Id == CosmosEventId.ExecutedReadItem); Assert.Equal(LogLevel.Information, logEntry.Level); Assert.Contains("ReadItem", logEntry.Message); - TestSqlLoggerFactory.Clear(); + Assert.Empty(ListLoggerFactory.Log.Where(l => l.Id == CosmosEventId.SyncNotSupported)); + ListLoggerFactory.Clear(); Assert.Equal(42, customerFromStore.Id); Assert.Equal("Theon Greyjoy", customerFromStore.Name); @@ -145,25 +164,30 @@ public async Task Can_add_update_delete_end_to_end_async() await context.SaveChangesAsync(); - logEntry = TestSqlLoggerFactory.Log.Single(); + logEntry = ListLoggerFactory.Log.Single(e => e.Id == CosmosEventId.ExecutedDeleteItem); Assert.Equal(LogLevel.Information, logEntry.Level); Assert.Contains("DeleteItem", logEntry.Message); + Assert.Empty(ListLoggerFactory.Log.Where(l => l.Id == CosmosEventId.SyncNotSupported)); } - using (var context = new CustomerContext(options)) + using (var context = contextFactory.CreateContext()) { Assert.Empty(await context.Set().ToListAsync()); + Assert.Empty(ListLoggerFactory.Log.Where(l => l.Id == CosmosEventId.SyncNotSupported)); } } [ConditionalFact] public async Task Can_add_update_delete_detached_entity_end_to_end_async() { - var options = Fixture.CreateOptions(); + var contextFactory = await InitializeAsync( + b => b.Entity(), + shouldLogCategory: _ => true, + onConfiguring: o => o.ConfigureWarnings(w => w.Log(CosmosEventId.SyncNotSupported))); var customer = new Customer { Id = 42, Name = "Theon" }; string storeId = null; - using (var context = new CustomerContext(options)) + using (var context = contextFactory.CreateContext()) { await context.Database.EnsureCreatedAsync(); @@ -174,19 +198,23 @@ public async Task Can_add_update_delete_detached_entity_end_to_end_async() await context.AddAsync(customer); storeId = entry.Property(StoreKeyConvention.DefaultIdPropertyName).CurrentValue; + + Assert.Empty(ListLoggerFactory.Log.Where(l => l.Id == CosmosEventId.SyncNotSupported)); } Assert.Equal("Customer|42", storeId); - using (var context = new CustomerContext(options)) + using (var context = contextFactory.CreateContext()) { var customerFromStore = await context.Set().SingleAsync(); Assert.Equal(42, customerFromStore.Id); Assert.Equal("Theon", customerFromStore.Name); + + Assert.Empty(ListLoggerFactory.Log.Where(l => l.Id == CosmosEventId.SyncNotSupported)); } - using (var context = new CustomerContext(options)) + using (var context = contextFactory.CreateContext()) { customer.Name = "Theon Greyjoy"; @@ -196,39 +224,49 @@ public async Task Can_add_update_delete_detached_entity_end_to_end_async() entry.State = EntityState.Modified; await context.SaveChangesAsync(); + + Assert.Empty(ListLoggerFactory.Log.Where(l => l.Id == CosmosEventId.SyncNotSupported)); } - using (var context = new CustomerContext(options)) + using (var context = contextFactory.CreateContext()) { - var customerFromStore = context.Set().Single(); + var customerFromStore = await context.Set().SingleAsync(); Assert.Equal(42, customerFromStore.Id); Assert.Equal("Theon Greyjoy", customerFromStore.Name); + + Assert.Empty(ListLoggerFactory.Log.Where(l => l.Id == CosmosEventId.SyncNotSupported)); } - using (var context = new CustomerContext(options)) + using (var context = contextFactory.CreateContext()) { var entry = context.Entry(customer); entry.Property(StoreKeyConvention.DefaultIdPropertyName).CurrentValue = storeId; entry.State = EntityState.Deleted; await context.SaveChangesAsync(); + + Assert.Empty(ListLoggerFactory.Log.Where(l => l.Id == CosmosEventId.SyncNotSupported)); } - using (var context = new CustomerContext(options)) + using (var context = contextFactory.CreateContext()) { Assert.Empty(await context.Set().ToListAsync()); + Assert.Empty(ListLoggerFactory.Log.Where(l => l.Id == CosmosEventId.SyncNotSupported)); } } [ConditionalFact] - public void Can_add_update_untracked_properties() + public async Task Can_add_update_untracked_properties() { - var options = Fixture.CreateOptions(); + var contextFactory = await InitializeAsync( + b => b.Entity(), + shouldLogCategory: _ => true, + onConfiguring: o => o.ConfigureWarnings(w => w.Log(CosmosEventId.SyncNotSupported))); var customer = new Customer { Id = 42, Name = "Theon" }; - using (var context = new CustomerContext(options)) + using (var context = contextFactory.CreateContext()) { context.Database.EnsureCreated(); @@ -243,9 +281,11 @@ public void Can_add_update_untracked_properties() context.Remove(customer); context.SaveChanges(); + + Assert.Equal(4, ListLoggerFactory.Log.Count(l => l.Id == CosmosEventId.SyncNotSupported)); } - using (var context = new CustomerContext(options)) + using (var context = contextFactory.CreateContext()) { Assert.Empty(context.Set().ToList()); @@ -263,9 +303,11 @@ public void Can_add_update_untracked_properties() document["key2"] = "value2"; entry.State = EntityState.Modified; context.SaveChanges(); + + Assert.Equal(7, ListLoggerFactory.Log.Count(l => l.Id == CosmosEventId.SyncNotSupported)); } - using (var context = new CustomerContext(options)) + using (var context = contextFactory.CreateContext()) { var customerFromStore = context.Set().Single(); @@ -281,9 +323,11 @@ public void Can_add_update_untracked_properties() customerFromStore.Name = "Theon Greyjoy"; context.SaveChanges(); + + Assert.Equal(9, ListLoggerFactory.Log.Count(l => l.Id == CosmosEventId.SyncNotSupported)); } - using (var context = new CustomerContext(options)) + using (var context = contextFactory.CreateContext()) { var customerFromStore = context.Set().Single(); @@ -297,22 +341,28 @@ public void Can_add_update_untracked_properties() context.Remove(customerFromStore); context.SaveChanges(); + + Assert.Equal(11, ListLoggerFactory.Log.Count(l => l.Id == CosmosEventId.SyncNotSupported)); } - using (var context = new CustomerContext(options)) + using (var context = contextFactory.CreateContext()) { Assert.Empty(context.Set().ToList()); + Assert.Equal(12, ListLoggerFactory.Log.Count(l => l.Id == CosmosEventId.SyncNotSupported)); } } [ConditionalFact] public async Task Can_add_update_untracked_properties_async() { - var options = Fixture.CreateOptions(); + var contextFactory = await InitializeAsync( + b => b.Entity(), + shouldLogCategory: _ => true, + onConfiguring: o => o.ConfigureWarnings(w => w.Log(CosmosEventId.SyncNotSupported))); var customer = new Customer { Id = 42, Name = "Theon" }; - using (var context = new CustomerContext(options)) + using (var context = contextFactory.CreateContext()) { await context.Database.EnsureCreatedAsync(); @@ -327,9 +377,11 @@ public async Task Can_add_update_untracked_properties_async() context.Remove(customer); await context.SaveChangesAsync(); + + Assert.Empty(ListLoggerFactory.Log.Where(l => l.Id == CosmosEventId.SyncNotSupported)); } - using (var context = new CustomerContext(options)) + using (var context = contextFactory.CreateContext()) { Assert.Empty(await context.Set().ToListAsync()); @@ -347,9 +399,11 @@ public async Task Can_add_update_untracked_properties_async() document["key2"] = "value2"; entry.State = EntityState.Modified; await context.SaveChangesAsync(); + + Assert.Empty(ListLoggerFactory.Log.Where(l => l.Id == CosmosEventId.SyncNotSupported)); } - using (var context = new CustomerContext(options)) + using (var context = contextFactory.CreateContext()) { var customerFromStore = await context.Set().SingleAsync(); @@ -365,9 +419,11 @@ public async Task Can_add_update_untracked_properties_async() customerFromStore.Name = "Theon Greyjoy"; await context.SaveChangesAsync(); + + Assert.Empty(ListLoggerFactory.Log.Where(l => l.Id == CosmosEventId.SyncNotSupported)); } - using (var context = new CustomerContext(options)) + using (var context = contextFactory.CreateContext()) { var customerFromStore = await context.Set().SingleAsync(); @@ -381,18 +437,30 @@ public async Task Can_add_update_untracked_properties_async() context.Remove(customerFromStore); await context.SaveChangesAsync(); + + Assert.Empty(ListLoggerFactory.Log.Where(l => l.Id == CosmosEventId.SyncNotSupported)); } - using (var context = new CustomerContext(options)) + using (var context = contextFactory.CreateContext()) { Assert.Empty(await context.Set().ToListAsync()); + Assert.Empty(ListLoggerFactory.Log.Where(l => l.Id == CosmosEventId.SyncNotSupported)); } } [ConditionalFact] public async Task Can_add_update_delete_end_to_end_with_Guid_async() { - var options = Fixture.CreateOptions(); + var contextFactory = await InitializeAsync( + b => b.Entity( + b => + { + b.Property(c => c.Id).ToJsonProperty("id"); + b.Property(c => c.PartitionKey).HasConversion().ToJsonProperty("pk"); + b.HasPartitionKey(c => c.PartitionKey); + }), + shouldLogCategory: _ => true, + onConfiguring: o => o.ConfigureWarnings(w => w.Log(CosmosEventId.SyncNotSupported))); var customer = new CustomerGuid { @@ -401,16 +469,18 @@ public async Task Can_add_update_delete_end_to_end_with_Guid_async() PartitionKey = 42 }; - using (var context = new CustomerContextGuid(options)) + using (var context = contextFactory.CreateContext()) { await context.Database.EnsureCreatedAsync(); await context.AddAsync(customer); await context.SaveChangesAsync(); + + Assert.Empty(ListLoggerFactory.Log.Where(l => l.Id == CosmosEventId.SyncNotSupported)); } - using (var context = new CustomerContextGuid(options)) + using (var context = contextFactory.CreateContext()) { var customerFromStore = await context.Set().SingleAsync(); @@ -420,9 +490,11 @@ public async Task Can_add_update_delete_end_to_end_with_Guid_async() customerFromStore.Name = "Theon Greyjoy"; await context.SaveChangesAsync(); + + Assert.Empty(ListLoggerFactory.Log.Where(l => l.Id == CosmosEventId.SyncNotSupported)); } - using (var context = new CustomerContextGuid(options)) + using (var context = contextFactory.CreateContext()) { var customerFromStore = await context.Set().SingleAsync(); @@ -432,18 +504,31 @@ public async Task Can_add_update_delete_end_to_end_with_Guid_async() context.Remove(customerFromStore); await context.SaveChangesAsync(); + + Assert.Empty(ListLoggerFactory.Log.Where(l => l.Id == CosmosEventId.SyncNotSupported)); } - using (var context = new CustomerContextGuid(options)) + using (var context = contextFactory.CreateContext()) { Assert.Empty(await context.Set().ToListAsync()); + Assert.Empty(ListLoggerFactory.Log.Where(l => l.Id == CosmosEventId.SyncNotSupported)); } } [ConditionalFact] public async Task Can_add_update_delete_end_to_end_with_DateTime_async() { - var options = Fixture.CreateOptions(); + var contextFactory = await InitializeAsync( + b => b.Entity( + b => + { + b.Property(c => c.Id); + b.Property(c => c.PartitionKey).HasConversion(); + b.HasPartitionKey(c => c.PartitionKey); + b.HasKey(c => new { c.Id, c.Name }); + }), + shouldLogCategory: _ => true, + onConfiguring: o => o.ConfigureWarnings(w => w.Log(CosmosEventId.SyncNotSupported))); var customer = new CustomerDateTime { @@ -452,7 +537,7 @@ public async Task Can_add_update_delete_end_to_end_with_DateTime_async() PartitionKey = 42 }; - using (var context = new CustomerContextDateTime(options)) + using (var context = contextFactory.CreateContext()) { await context.Database.EnsureCreatedAsync(); @@ -461,9 +546,11 @@ public async Task Can_add_update_delete_end_to_end_with_DateTime_async() Assert.Equal("CustomerDateTime|0001-01-01T00:00:00.0000000|Theon^2F^5C^23^5C^5C^3F", entry.CurrentValues["__id"]); await context.SaveChangesAsync(); + + Assert.Empty(ListLoggerFactory.Log.Where(l => l.Id == CosmosEventId.SyncNotSupported)); } - using (var context = new CustomerContextDateTime(options)) + using (var context = contextFactory.CreateContext()) { var customerFromStore = await context.Set().SingleAsync(); @@ -473,9 +560,11 @@ public async Task Can_add_update_delete_end_to_end_with_DateTime_async() customerFromStore.Value = 23; await context.SaveChangesAsync(); + + Assert.Empty(ListLoggerFactory.Log.Where(l => l.Id == CosmosEventId.SyncNotSupported)); } - using (var context = new CustomerContextDateTime(options)) + using (var context = contextFactory.CreateContext()) { var customerFromStore = await context.Set().SingleAsync(); @@ -485,11 +574,14 @@ public async Task Can_add_update_delete_end_to_end_with_DateTime_async() context.Remove(customerFromStore); await context.SaveChangesAsync(); + + Assert.Empty(ListLoggerFactory.Log.Where(l => l.Id == CosmosEventId.SyncNotSupported)); } - using (var context = new CustomerContextDateTime(options)) + using (var context = contextFactory.CreateContext()) { Assert.Empty(await context.Set().ToListAsync()); + Assert.Empty(ListLoggerFactory.Log.Where(l => l.Id == CosmosEventId.SyncNotSupported)); } } @@ -528,61 +620,35 @@ private class CustomerNoPartitionKey public string Name { get; set; } } - private class CustomerContext(DbContextOptions dbContextOptions) : DbContext(dbContextOptions) - { - protected override void OnModelCreating(ModelBuilder modelBuilder) - => modelBuilder.Entity(); - } - - private class CustomerContextGuid(DbContextOptions dbContextOptions) : DbContext(dbContextOptions) - { - protected override void OnModelCreating(ModelBuilder modelBuilder) - => modelBuilder.Entity( - cb => - { - cb.Property(c => c.Id).ToJsonProperty("id"); - cb.Property(c => c.PartitionKey).HasConversion().ToJsonProperty("pk"); - cb.HasPartitionKey(c => c.PartitionKey); - }); - } - - private class CustomerContextDateTime(DbContextOptions dbContextOptions) : DbContext(dbContextOptions) - { - protected override void OnModelCreating(ModelBuilder modelBuilder) - => modelBuilder.Entity( - cb => - { - cb.Property(c => c.Id); - cb.Property(c => c.PartitionKey).HasConversion(); - cb.HasPartitionKey(c => c.PartitionKey); - cb.HasKey(c => new { c.Id, c.Name }); - }); - } - [ConditionalFact] public async Task Can_add_update_delete_with_dateTime_string_end_to_end_async() { - var options = Fixture.CreateOptions(); + var contextFactory = await InitializeAsync( + b => b.Entity(), + shouldLogCategory: _ => true, + onConfiguring: o => o.ConfigureWarnings(w => w.Log(CosmosEventId.SyncNotSupported))); var customer = new Customer { Id = 42, Name = "2021-08-23T06:23:40+00:00" }; - using (var context = new CustomerContext(options)) + using (var context = contextFactory.CreateContext()) { await context.Database.EnsureCreatedAsync(); await context.AddAsync(customer); await context.SaveChangesAsync(); + + Assert.Empty(ListLoggerFactory.Log.Where(l => l.Id == CosmosEventId.SyncNotSupported)); } - using (var context = new CustomerContext(options)) + using (var context = contextFactory.CreateContext()) { var customerFromStore = await context.Set().SingleAsync(); - var logEntry = TestSqlLoggerFactory.Log.Last(); + var logEntry = ListLoggerFactory.Log.Single(e => e.Id == CosmosEventId.ExecutedReadNext); Assert.Equal(LogLevel.Information, logEntry.Level); Assert.Contains("ReadNext", logEntry.Message); - TestSqlLoggerFactory.Clear(); + ListLoggerFactory.Clear(); Assert.Equal(42, customerFromStore.Id); Assert.Equal("2021-08-23T06:23:40+00:00", customerFromStore.Name); @@ -590,9 +656,11 @@ public async Task Can_add_update_delete_with_dateTime_string_end_to_end_async() customerFromStore.Name = "2021-08-23T06:23:40+02:00"; await context.SaveChangesAsync(); + + Assert.Empty(ListLoggerFactory.Log.Where(l => l.Id == CosmosEventId.SyncNotSupported)); } - using (var context = new CustomerContext(options)) + using (var context = contextFactory.CreateContext()) { var customerFromStore = await context.FindAsync(42); @@ -602,19 +670,26 @@ public async Task Can_add_update_delete_with_dateTime_string_end_to_end_async() context.Remove(customerFromStore); await context.SaveChangesAsync(); + + Assert.Empty(ListLoggerFactory.Log.Where(l => l.Id == CosmosEventId.SyncNotSupported)); } - using (var context = new CustomerContext(options)) + using (var context = contextFactory.CreateContext()) { Assert.Empty(await context.Set().ToListAsync()); + Assert.Empty(ListLoggerFactory.Log.Where(l => l.Id == CosmosEventId.SyncNotSupported)); } } + [ConditionalFact] public async Task Entities_with_null_PK_can_be_added_with_normal_use_of_DbContext_methods_and_have_id_shadow_value_and_PK_created() { - await using var testDatabase = CosmosTestStore.Create("IdentifierShadowValuePresenceTest"); - using var context = new IdentifierShadowValuePresenceTestContext(testDatabase); + var contextFactory = await InitializeAsync( + usePooling: false, + shouldLogCategory: _ => true, + onConfiguring: o => o.ConfigureWarnings(w => w.Log(CosmosEventId.SyncNotSupported))); + var context = contextFactory.CreateContext(); var item = new GItem(); Assert.Null(item.Id); @@ -634,8 +709,12 @@ public async Task Entities_with_null_PK_can_be_added_with_normal_use_of_DbContex public async Task Entities_can_be_tracked_with_normal_use_of_DbContext_methods_and_have_correct_resultant_state_and_id_shadow_value() { - await using var testDatabase = CosmosTestStore.Create("IdentifierShadowValuePresenceTest"); - using var context = new IdentifierShadowValuePresenceTestContext(testDatabase); + var contextFactory = await InitializeAsync( + usePooling: false, + shouldLogCategory: _ => true, + onConfiguring: o => o.ConfigureWarnings(w => w.Log(CosmosEventId.SyncNotSupported))); + + var context = contextFactory.CreateContext(); var item = new Item { Id = 1337 }; var entry = context.Attach(item); @@ -656,26 +735,9 @@ public async Task Assert.Equal(EntityState.Deleted, entry.State); } - protected class IdentifierShadowValuePresenceTestContext(CosmosTestStore testStore) : DbContext + protected class IdentifierShadowValuePresenceTestContext(DbContextOptions dbContextOptions) : DbContext(dbContextOptions) { - private readonly string _connectionUri = testStore.ConnectionUri; - private readonly string _authToken = testStore.AuthToken; - private readonly string _name = testStore.Name; - - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - => optionsBuilder - .UseCosmos( - _connectionUri, - _authToken, - _name, - b => b.ApplyConfiguration()); - - protected override void OnModelCreating(ModelBuilder modelBuilder) - { - } - public DbSet GItems { get; set; } - public DbSet Items { get; set; } } @@ -875,7 +937,10 @@ private async Task Can_add_update_delete_with_collection( Action onModelBuilder = null) where TCollection : class { - var options = Fixture.CreateOptions(); + var contextFactory = await InitializeAsync>( + shouldLogCategory: _ => true, + onModelCreating: onModelBuilder, + onConfiguring: o => o.ConfigureWarnings(w => w.Log(CosmosEventId.SyncNotSupported))); var customer = new CustomerWithCollection { @@ -884,7 +949,7 @@ private async Task Can_add_update_delete_with_collection( Collection = initialValue }; - using (var context = new CollectionCustomerContext(options, onModelBuilder)) + using (var context = contextFactory.CreateContext()) { await context.Database.EnsureCreatedAsync(); @@ -893,7 +958,7 @@ private async Task Can_add_update_delete_with_collection( await context.SaveChangesAsync(); } - using (var context = new CollectionCustomerContext(options)) + using (var context = contextFactory.CreateContext()) { var customerFromStore = await context.Customers.SingleAsync(); @@ -905,7 +970,7 @@ private async Task Can_add_update_delete_with_collection( await context.SaveChangesAsync(); } - using (var context = new CollectionCustomerContext(options)) + using (var context = contextFactory.CreateContext()) { var customerFromStore = await context.Customers.SingleAsync(); @@ -917,7 +982,7 @@ private async Task Can_add_update_delete_with_collection( await context.SaveChangesAsync(); } - using (var context = new CollectionCustomerContext(options)) + using (var context = contextFactory.CreateContext()) { var customerFromStore = await context.Customers.SingleAsync(); @@ -933,21 +998,23 @@ private class CustomerWithCollection public TCollection Collection { get; set; } } - private class CollectionCustomerContext(DbContextOptions dbContextOptions, Action onModelBuilder = null) : DbContext(dbContextOptions) + private class CollectionCustomerContext(DbContextOptions dbContextOptions, Action onModelBuilder = null) + : DbContext(dbContextOptions) { - private readonly Action _onModelBuilder = onModelBuilder; - // ReSharper disable once UnusedAutoPropertyAccessor.Local public DbSet> Customers { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) - => _onModelBuilder?.Invoke(modelBuilder); + => onModelBuilder?.Invoke(modelBuilder); } [ConditionalFact] public async Task Can_read_with_find_with_resource_id_async() { - var options = Fixture.CreateOptions(); + var contextFactory = await InitializeAsync( + shouldLogCategory: _ => true, + onConfiguring: o => o.ConfigureWarnings(w => w.Log(CosmosEventId.SyncNotSupported))); + const int pk1 = 1; const int pk2 = 2; @@ -958,7 +1025,7 @@ public async Task Can_read_with_find_with_resource_id_async() PartitionKey = pk1 }; - await using (var context = new PartitionKeyContextWithResourceId(options)) + await using (var context = contextFactory.CreateContext()) { await context.Database.EnsureCreatedAsync(); @@ -978,7 +1045,7 @@ await context.AddAsync( await context.SaveChangesAsync(); } - await using (var context = new PartitionKeyContextWithResourceId(options)) + await using (var context = contextFactory.CreateContext()) { var customerFromStore = await context.Set() .FindAsync(pk1, "42"); @@ -993,7 +1060,7 @@ await context.AddAsync( await context.SaveChangesAsync(); } - await using (var context = new PartitionKeyContextWithResourceId(options)) + await using (var context = contextFactory.CreateContext()) { var customerFromStore = await context.Set() .WithPartitionKey(partitionKey: pk1.ToString()) @@ -1006,9 +1073,12 @@ await context.AddAsync( } [ConditionalFact] - public void Can_read_with_find_with_resource_id() + public async Task Can_read_with_find_with_resource_id() { - var options = Fixture.CreateOptions(); + var contextFactory = await InitializeAsync( + shouldLogCategory: _ => true, + onConfiguring: o => o.ConfigureWarnings(w => w.Log(CosmosEventId.SyncNotSupported))); + const int pk1 = 1; const int pk2 = 2; @@ -1019,7 +1089,7 @@ public void Can_read_with_find_with_resource_id() PartitionKey = pk1 }; - using (var context = new PartitionKeyContextWithResourceId(options)) + using (var context = contextFactory.CreateContext()) { context.Database.EnsureCreated(); @@ -1035,7 +1105,7 @@ public void Can_read_with_find_with_resource_id() context.SaveChanges(); } - using (var context = new PartitionKeyContextWithResourceId(options)) + using (var context = contextFactory.CreateContext()) { var customerFromStore = context.Set() .Find(pk1, "42"); @@ -1050,7 +1120,7 @@ public void Can_read_with_find_with_resource_id() context.SaveChanges(); } - using (var context = new PartitionKeyContextWithResourceId(options)) + using (var context = contextFactory.CreateContext()) { var customerFromStore = context.Set() .WithPartitionKey(partitionKey: pk1.ToString()) @@ -1063,10 +1133,13 @@ public void Can_read_with_find_with_resource_id() } [ConditionalFact] - public void Find_with_empty_resource_id_throws() + public async Task Find_with_empty_resource_id_throws() { - var options = Fixture.CreateOptions(); - using (var context = new PartitionKeyContextWithResourceId(options)) + var contextFactory = await InitializeAsync( + shouldLogCategory: _ => true, + onConfiguring: o => o.ConfigureWarnings(w => w.Log(CosmosEventId.SyncNotSupported))); + + using (var context = contextFactory.CreateContext()) { context.Database.EnsureCreated(); @@ -1079,7 +1152,10 @@ public void Find_with_empty_resource_id_throws() [ConditionalFact] public async Task Can_read_with_find_with_partition_key_and_value_generator_async() { - var options = Fixture.CreateOptions(); + var contextFactory = await InitializeAsync( + shouldLogCategory: _ => true, + onConfiguring: o => o.ConfigureWarnings(w => w.Log(CosmosEventId.SyncNotSupported))); + const int pk1 = 1; const int pk2 = 2; @@ -1090,7 +1166,7 @@ public async Task Can_read_with_find_with_partition_key_and_value_generator_asyn PartitionKey = pk1 }; - await using (var context = new PartitionKeyContextCustomValueGenerator(options)) + await using (var context = contextFactory.CreateContext()) { await context.Database.EnsureCreatedAsync(); @@ -1106,7 +1182,7 @@ await context.AddAsync( await context.SaveChangesAsync(); } - await using (var context = new PartitionKeyContextCustomValueGenerator(options)) + await using (var context = contextFactory.CreateContext()) { var customerFromStore = await context.Set() .FindAsync(pk1, 42); @@ -1120,7 +1196,7 @@ await context.AddAsync( await context.SaveChangesAsync(); } - await using (var context = new PartitionKeyContextCustomValueGenerator(options)) + await using (var context = contextFactory.CreateContext()) { var customerFromStore = await context.Set() .WithPartitionKey(partitionKey: pk1.ToString()) @@ -1133,9 +1209,12 @@ await context.AddAsync( } [ConditionalFact] - public void Can_read_with_find_with_partition_key_and_value_generator() + public async Task Can_read_with_find_with_partition_key_and_value_generator() { - var options = Fixture.CreateOptions(); + var contextFactory = await InitializeAsync( + shouldLogCategory: _ => true, + onConfiguring: o => o.ConfigureWarnings(w => w.Log(CosmosEventId.SyncNotSupported))); + const int pk1 = 1; const int pk2 = 2; @@ -1146,7 +1225,7 @@ public void Can_read_with_find_with_partition_key_and_value_generator() PartitionKey = pk1 }; - using (var context = new PartitionKeyContextCustomValueGenerator(options)) + using (var context = contextFactory.CreateContext()) { context.Database.EnsureCreated(); @@ -1162,7 +1241,7 @@ public void Can_read_with_find_with_partition_key_and_value_generator() context.SaveChanges(); } - using (var context = new PartitionKeyContextCustomValueGenerator(options)) + using (var context = contextFactory.CreateContext()) { var customerFromStore = context.Set() .Find(pk1, 42); @@ -1177,7 +1256,7 @@ public void Can_read_with_find_with_partition_key_and_value_generator() context.SaveChanges(); } - using (var context = new PartitionKeyContextCustomValueGenerator(options)) + using (var context = contextFactory.CreateContext()) { var customerFromStore = context.Set() .WithPartitionKey(partitionKey: pk1.ToString()) @@ -1190,9 +1269,12 @@ public void Can_read_with_find_with_partition_key_and_value_generator() } [ConditionalFact] - public void Can_read_with_find_with_partition_key_without_value_generator() + public async Task Can_read_with_find_with_partition_key_without_value_generator() { - var options = Fixture.CreateOptions(); + var contextFactory = await InitializeAsync( + shouldLogCategory: _ => true, + onConfiguring: o => o.ConfigureWarnings(w => w.Log(CosmosEventId.SyncNotSupported))); + const int pk1 = 1; var customer = new Customer @@ -1202,7 +1284,7 @@ public void Can_read_with_find_with_partition_key_without_value_generator() PartitionKey = pk1 }; - using (var context = new PartitionKeyContextNoValueGenerator(options)) + using (var context = contextFactory.CreateContext()) { context.Database.EnsureCreated(); @@ -1213,7 +1295,7 @@ public void Can_read_with_find_with_partition_key_without_value_generator() context.SaveChanges(); } - using (var context = new PartitionKeyContextNoValueGenerator(options)) + using (var context = contextFactory.CreateContext()) { var customerFromStore = context.Set() .Find(pk1, 42); @@ -1237,7 +1319,7 @@ OFFSET 0 LIMIT 1 context.SaveChanges(); } - using (var context = new PartitionKeyContextNoValueGenerator(options)) + using (var context = contextFactory.CreateContext()) { var customerFromStore = context.Set() .WithPartitionKey(partitionKey: pk1.ToString()) @@ -1252,7 +1334,9 @@ OFFSET 0 LIMIT 1 [ConditionalFact] public async Task Can_read_with_find_with_partition_key_not_part_of_primary_key() { - var options = Fixture.CreateOptions(); + var contextFactory = await InitializeAsync( + shouldLogCategory: _ => true, + onConfiguring: o => o.ConfigureWarnings(w => w.Log(CosmosEventId.SyncNotSupported))); var customer = new Customer { @@ -1261,7 +1345,7 @@ public async Task Can_read_with_find_with_partition_key_not_part_of_primary_key( PartitionKey = 1 }; - await using (var context = new PartitionKeyContextNonPrimaryKey(options)) + using (var context = contextFactory.CreateContext()) { await context.Database.EnsureCreatedAsync(); @@ -1270,7 +1354,7 @@ public async Task Can_read_with_find_with_partition_key_not_part_of_primary_key( await context.SaveChangesAsync(); } - await using (var context = new PartitionKeyContextNonPrimaryKey(options)) + using (var context = contextFactory.CreateContext()) { var customerFromStore = context.Set().Find(42); @@ -1283,11 +1367,13 @@ public async Task Can_read_with_find_with_partition_key_not_part_of_primary_key( [ConditionalFact] public async Task Can_read_with_find_without_partition_key() { - var options = Fixture.CreateOptions(); + var contextFactory = await InitializeAsync( + shouldLogCategory: _ => true, + onConfiguring: o => o.ConfigureWarnings(w => w.Log(CosmosEventId.SyncNotSupported))); var customer = new CustomerNoPartitionKey { Id = 42, Name = "Theon" }; - await using (var context = new PartitionKeyContextEntityWithNoPartitionKey(options)) + await using (var context = contextFactory.CreateContext()) { await context.Database.EnsureCreatedAsync(); @@ -1296,7 +1382,7 @@ public async Task Can_read_with_find_without_partition_key() await context.SaveChangesAsync(); } - await using (var context = new PartitionKeyContextEntityWithNoPartitionKey(options)) + await using (var context = contextFactory.CreateContext()) { var customerFromStore = context.Set().Find(42); @@ -1309,11 +1395,13 @@ public async Task Can_read_with_find_without_partition_key() [ConditionalFact] public async Task Can_read_with_find_with_PK_partition_key() { - var options = Fixture.CreateOptions(); + var contextFactory = await InitializeAsync( + shouldLogCategory: _ => true, + onConfiguring: o => o.ConfigureWarnings(w => w.Log(CosmosEventId.SyncNotSupported))); var customer = new CustomerGuid { Id = Guid.NewGuid(), Name = "Theon" }; - await using (var context = new PartitionKeyContextPrimaryKey(options)) + await using (var context = contextFactory.CreateContext()) { await context.Database.EnsureCreatedAsync(); @@ -1322,7 +1410,7 @@ public async Task Can_read_with_find_with_PK_partition_key() await context.SaveChangesAsync(); } - await using (var context = new PartitionKeyContextPrimaryKey(options)) + await using (var context = contextFactory.CreateContext()) { var customerFromStore = context.Set().Find(customer.Id); @@ -1335,11 +1423,13 @@ public async Task Can_read_with_find_with_PK_partition_key() [ConditionalFact] public async Task Can_read_with_find_with_PK_resource_id() { - var options = Fixture.CreateOptions(); + var contextFactory = await InitializeAsync( + shouldLogCategory: _ => true, + onConfiguring: o => o.ConfigureWarnings(w => w.Log(CosmosEventId.SyncNotSupported))); var customer = new CustomerWithResourceId { id = "42", Name = "Theon" }; - await using (var context = new PartitionKeyContextWithPrimaryKeyResourceId(options)) + await using (var context = contextFactory.CreateContext()) { await context.Database.EnsureCreatedAsync(); @@ -1348,7 +1438,7 @@ public async Task Can_read_with_find_with_PK_resource_id() await context.SaveChangesAsync(); } - await using (var context = new PartitionKeyContextWithPrimaryKeyResourceId(options)) + await using (var context = contextFactory.CreateContext()) { var customerFromStore = context.Set().Find("42"); @@ -1461,11 +1551,13 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) [ConditionalFact] public async Task Can_use_detached_entities_without_discriminators() { - var options = Fixture.CreateOptions(); + var contextFactory = await InitializeAsync( + shouldLogCategory: _ => true, + onConfiguring: o => o.ConfigureWarnings(w => w.Log(CosmosEventId.SyncNotSupported))); var customer = new Customer { Id = 42, Name = "Theon" }; - using (var context = new NoDiscriminatorCustomerContext(options)) + using (var context = contextFactory.CreateContext()) { await context.Database.EnsureCreatedAsync(); @@ -1474,7 +1566,7 @@ public async Task Can_use_detached_entities_without_discriminators() await context.SaveChangesAsync(); } - using (var context = new NoDiscriminatorCustomerContext(options)) + using (var context = contextFactory.CreateContext()) { (await context.AddAsync(customer)).State = EntityState.Modified; @@ -1483,7 +1575,7 @@ public async Task Can_use_detached_entities_without_discriminators() await context.SaveChangesAsync(); } - using (var context = new NoDiscriminatorCustomerContext(options)) + using (var context = contextFactory.CreateContext()) { var customerFromStore = context.Set().AsNoTracking().Single(); @@ -1495,26 +1587,28 @@ public async Task Can_use_detached_entities_without_discriminators() await context.SaveChangesAsync(); } - using (var context = new NoDiscriminatorCustomerContext(options)) + using (var context = contextFactory.CreateContext()) { Assert.Empty(await context.Set().ToListAsync()); } } - private class NoDiscriminatorCustomerContext(DbContextOptions dbContextOptions) : CustomerContext(dbContextOptions) + private class NoDiscriminatorCustomerContext(DbContextOptions dbContextOptions) : DbContext(dbContextOptions) { protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity().HasNoDiscriminator(); } [ConditionalFact] - public void Can_update_unmapped_properties() + public async Task Can_update_unmapped_properties() { - var options = Fixture.CreateOptions(); + var contextFactory = await InitializeAsync( + shouldLogCategory: _ => true, + onConfiguring: o => o.ConfigureWarnings(w => w.Log(CosmosEventId.SyncNotSupported))); var customer = new Customer { Id = 42, Name = "Theon" }; - using (var context = new ExtraCustomerContext(options)) + using (var context = contextFactory.CreateContext()) { context.Database.EnsureCreated(); @@ -1524,7 +1618,7 @@ public void Can_update_unmapped_properties() context.SaveChanges(); } - using (var context = new ExtraCustomerContext(options)) + using (var context = contextFactory.CreateContext()) { var customerFromStore = context.Set().Single(); @@ -1536,7 +1630,7 @@ public void Can_update_unmapped_properties() context.SaveChanges(); } - using (var context = new ExtraCustomerContext(options)) + using (var context = contextFactory.CreateContext()) { var customerFromStore = context.Set().Single(); @@ -1554,29 +1648,28 @@ public void Can_update_unmapped_properties() context.SaveChanges(); } - using (var context = new ExtraCustomerContext(options)) + using (var context = contextFactory.CreateContext()) { Assert.Empty(context.Set().ToList()); } } - private class ExtraCustomerContext(DbContextOptions dbContextOptions) : CustomerContext(dbContextOptions) + private class ExtraCustomerContext(DbContextOptions dbContextOptions) : DbContext(dbContextOptions) { protected override void OnModelCreating(ModelBuilder modelBuilder) - { - modelBuilder.HasDefaultContainer(nameof(CustomerContext)); - modelBuilder.Entity().Property("EMail").ToJsonProperty("e-mail"); - } + => modelBuilder.Entity().Property("EMail").ToJsonProperty("e-mail"); } [ConditionalFact] public async Task Can_use_non_persisted_properties() { - var options = Fixture.CreateOptions(); + var contextFactory = await InitializeAsync( + shouldLogCategory: _ => true, + onConfiguring: o => o.ConfigureWarnings(w => w.Log(CosmosEventId.SyncNotSupported))); var customer = new Customer { Id = 42, Name = "Theon" }; - using (var context = new UnmappedCustomerContext(options)) + using (var context = contextFactory.CreateContext()) { await context.Database.EnsureCreatedAsync(); @@ -1586,7 +1679,7 @@ public async Task Can_use_non_persisted_properties() Assert.Equal("Theon", customer.Name); } - using (var context = new UnmappedCustomerContext(options)) + using (var context = contextFactory.CreateContext()) { var customerFromStore = await context.Set().SingleAsync(); @@ -1599,7 +1692,7 @@ public async Task Can_use_non_persisted_properties() } } - private class UnmappedCustomerContext(DbContextOptions dbContextOptions) : CustomerContext(dbContextOptions) + private class UnmappedCustomerContext(DbContextOptions dbContextOptions) : DbContext(dbContextOptions) { protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity().Property(c => c.Name).ToJsonProperty(""); @@ -1608,11 +1701,14 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) [ConditionalFact] public async Task Add_update_delete_query_throws_if_no_container() { - await using var testDatabase = CosmosTestStore.CreateInitialized(DatabaseName + "Empty"); - var options = Fixture.CreateOptions(testDatabase); + await using var testDatabase = await CosmosTestStore.CreateInitializedAsync("EndToEndEmpty"); + + var options = new DbContextOptionsBuilder() + .UseCosmos(testDatabase.ConnectionString, "EndToEndEmpty") + .Options; var customer = new Customer { Id = 42, Name = "Theon" }; - using (var context = new CustomerContext(options)) + using (var context = new EndToEndEmptyContext(options)) { await context.AddAsync(customer); @@ -1621,7 +1717,7 @@ public async Task Add_update_delete_query_throws_if_no_container() (await Assert.ThrowsAsync(() => context.SaveChangesAsync())).InnerException!.Message); } - using (var context = new CustomerContext(options)) + using (var context = new EndToEndEmptyContext(options)) { (await context.AddAsync(customer)).State = EntityState.Modified; @@ -1630,7 +1726,7 @@ public async Task Add_update_delete_query_throws_if_no_container() (await Assert.ThrowsAsync(() => context.SaveChangesAsync())).InnerException!.Message); } - using (var context = new CustomerContext(options)) + using (var context = new EndToEndEmptyContext(options)) { (await context.AddAsync(customer)).State = EntityState.Deleted; @@ -1639,7 +1735,7 @@ public async Task Add_update_delete_query_throws_if_no_container() (await Assert.ThrowsAsync(() => context.SaveChangesAsync())).InnerException!.Message); } - using (var context = new CustomerContext(options)) + using (var context = new EndToEndEmptyContext(options)) { Assert.StartsWith( "Response status code does not indicate success: NotFound (404); Substatus: 0", @@ -1647,12 +1743,21 @@ public async Task Add_update_delete_query_throws_if_no_container() } } + private class EndToEndEmptyContext(DbContextOptions options) : DbContext(options) + { + public DbSet Customers + => Set(); + } + [ConditionalFact] public async Task Using_a_conflicting_incompatible_id_throws() { - var options = Fixture.CreateOptions(); + var contextFactory = await InitializeAsync( + shouldLogCategory: _ => true, + onConfiguring: o => o.ConfigureWarnings(w => w.Log(CosmosEventId.SyncNotSupported))); + + using var context = contextFactory.CreateContext(); - using var context = new ConflictingIncompatibleIdContext(options); await Assert.ThrowsAnyAsync( async () => { @@ -1680,11 +1785,13 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) [ConditionalFact] public async Task Can_add_update_delete_end_to_end_with_conflicting_id() { - var options = Fixture.CreateOptions(); + var contextFactory = await InitializeAsync( + shouldLogCategory: _ => true, + onConfiguring: o => o.ConfigureWarnings(w => w.Log(CosmosEventId.SyncNotSupported))); var entity = new ConflictingId { id = "42", Name = "Theon" }; - using (var context = new ConflictingIdContext(options)) + using (var context = contextFactory.CreateContext()) { await context.Database.EnsureCreatedAsync(); @@ -1693,7 +1800,7 @@ public async Task Can_add_update_delete_end_to_end_with_conflicting_id() await context.SaveChangesAsync(); } - using (var context = new ConflictingIdContext(options)) + using (var context = contextFactory.CreateContext()) { var entityFromStore = context.Set().Single(); @@ -1701,7 +1808,7 @@ public async Task Can_add_update_delete_end_to_end_with_conflicting_id() Assert.Equal("Theon", entityFromStore.Name); } - using (var context = new ConflictingIdContext(options)) + using (var context = contextFactory.CreateContext()) { entity.Name = "Theon Greyjoy"; @@ -1710,7 +1817,7 @@ public async Task Can_add_update_delete_end_to_end_with_conflicting_id() await context.SaveChangesAsync(); } - using (var context = new ConflictingIdContext(options)) + using (var context = contextFactory.CreateContext()) { var entityFromStore = context.Set().Single(); @@ -1718,14 +1825,14 @@ public async Task Can_add_update_delete_end_to_end_with_conflicting_id() Assert.Equal("Theon Greyjoy", entityFromStore.Name); } - using (var context = new ConflictingIdContext(options)) + using (var context = contextFactory.CreateContext()) { context.Remove(entity); await context.SaveChangesAsync(); } - using (var context = new ConflictingIdContext(options)) + using (var context = contextFactory.CreateContext()) { Assert.Empty(context.Set().ToList()); } @@ -1748,7 +1855,24 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) [InlineData(false)] public async Task Can_have_non_string_property_named_Discriminator(bool useDiscriminator) { - using var context = new NonStringDiscriminatorContext(Fixture.CreateOptions(), useDiscriminator); + var contextFactory = await InitializeAsync( + shouldLogCategory: _ => true, + onModelCreating: b => + { + if (useDiscriminator) + { + b.Entity() + .HasDiscriminator(m => m.Discriminator) + .HasValue(EntityType.Base); + } + else + { + b.Entity(); + } + }, + onConfiguring: o => o.ConfigureWarnings(w => w.Log(CosmosEventId.SyncNotSupported))); + + using var context = contextFactory.CreateContext(); context.Database.EnsureCreated(); var entry = await context.AddAsync(new NonStringDiscriminator { Id = 1 }); @@ -1764,8 +1888,8 @@ public async Task Can_have_non_string_property_named_Discriminator(bool useDiscr if (useDiscriminator) { AssertSql( - context, - """ + context, + """ SELECT c FROM root c WHERE (c["Discriminator"] = 0) @@ -1785,15 +1909,16 @@ OFFSET 0 LIMIT 1 """); } - Fixture.ListLoggerFactory.Clear(); - Assert.Equal(baseEntity, await context.Set() + ListLoggerFactory.Clear(); + Assert.Equal( + baseEntity, await context.Set() .Where(e => e.Discriminator == EntityType.Base).OrderBy(e => e.Id).FirstOrDefaultAsync()); if (useDiscriminator) { AssertSql( - context, - """ + context, + """ SELECT c FROM root c WHERE ((c["Discriminator"] = 0) AND (c["Discriminator"] = 0)) @@ -1804,8 +1929,8 @@ OFFSET 0 LIMIT 1 else { AssertSql( - context, - """ + context, + """ SELECT c FROM root c WHERE (c["Discriminator"] = 0) @@ -1814,15 +1939,16 @@ OFFSET 0 LIMIT 1 """); } - Fixture.ListLoggerFactory.Clear(); - Assert.Equal(baseEntity, await context.Set() + ListLoggerFactory.Clear(); + Assert.Equal( + baseEntity, await context.Set() .Where(e => e.GetType() == typeof(NonStringDiscriminator)).OrderBy(e => e.Id).FirstOrDefaultAsync()); if (useDiscriminator) { AssertSql( - context, - """ + context, + """ SELECT c FROM root c WHERE (c["Discriminator"] = 0) @@ -1833,8 +1959,8 @@ OFFSET 0 LIMIT 1 else { AssertSql( - context, - """ + context, + """ SELECT c FROM root c ORDER BY c["Id"] @@ -1842,15 +1968,16 @@ OFFSET 0 LIMIT 1 """); } - Fixture.ListLoggerFactory.Clear(); - Assert.Equal(baseEntity, await context.Set() + ListLoggerFactory.Clear(); + Assert.Equal( + baseEntity, await context.Set() .Where(e => e is NonStringDiscriminator).OrderBy(e => e.Id).FirstOrDefaultAsync()); if (useDiscriminator) { AssertSql( - context, - """ + context, + """ SELECT c FROM root c WHERE (c["Discriminator"] = 0) @@ -1861,8 +1988,8 @@ OFFSET 0 LIMIT 1 else { AssertSql( - context, - """ + context, + """ SELECT c FROM root c ORDER BY c["Id"] @@ -1883,68 +2010,35 @@ private enum EntityType Derived } - public class NonStringDiscriminatorContext(DbContextOptions dbContextOptions, bool useDiscriminator) : DbContext(dbContextOptions) - { - public bool UseDiscriminator { get; } = useDiscriminator; - - protected override void OnModelCreating(ModelBuilder modelBuilder) - { - modelBuilder.Entity(); - if (UseDiscriminator) - { - modelBuilder.Entity() - .HasDiscriminator(m => m.Discriminator) - .HasValue(EntityType.Base); - } - } - } - private void AssertSql(DbContext context, params string[] expected) { var logger = (TestSqlLoggerFactory)context.GetService(); logger.AssertBaseline(expected); } - protected TestSqlLoggerFactory TestSqlLoggerFactory - => (TestSqlLoggerFactory)Fixture.ListLoggerFactory; - - protected void AssertSql(params string[] expected) - => TestSqlLoggerFactory.AssertBaseline(expected); - - protected void AssertContainsSql(params string[] expected) - => TestSqlLoggerFactory.AssertBaseline(expected, assertOrder: false); - protected ListLoggerFactory LoggerFactory { get; } - public class CosmosFixture : ServiceProviderFixtureBase, IAsyncLifetime - { - public CosmosFixture() - { - TestStore = CosmosTestStore.Create(DatabaseName); - } - - protected override ITestStoreFactory TestStoreFactory - => CosmosTestStoreFactory.Instance; - - public virtual CosmosTestStore TestStore { get; } + protected override string StoreName + => nameof(EndToEndCosmosTest); - public DbContextOptions CreateOptions() - { - TestStore.Initialize(null, (Func)null); - ListLoggerFactory.Clear(); - return CreateOptions(TestStore); - } - - protected override bool ShouldLogCategory(string logCategory) - => logCategory == DbLoggerCategory.Database.Command.Name; + protected override ITestStoreFactory TestStoreFactory + => CosmosTestStoreFactory.Instance; - protected override object GetAdditionalModelCacheKey(DbContext context) - => (context as NonStringDiscriminatorContext)?.UseDiscriminator; + protected ContextFactory ContextFactory { get; private set; } - public Task InitializeAsync() - => Task.CompletedTask; - - public Task DisposeAsync() - => TestStore.DisposeAsync(); - } + protected async Task InitializeAsync( + Action onModelCreating, + Func onConfiguring = null, + Func seed = null, + bool sensitiveLogEnabled = true) + => ContextFactory = await InitializeAsync( + onModelCreating, + seed: seed, + shouldLogCategory: _ => true, + onConfiguring: options => + { + options.ConfigureWarnings(w => w.Log(CosmosEventId.SyncNotSupported)).EnableSensitiveDataLogging(sensitiveLogEnabled); + onConfiguring?.Invoke(options); + } + ); } diff --git a/test/EFCore.Cosmos.FunctionalTests/FindCosmosTest.cs b/test/EFCore.Cosmos.FunctionalTests/FindCosmosTest.cs index 1906ee1fc5c..2bfef6105d8 100644 --- a/test/EFCore.Cosmos.FunctionalTests/FindCosmosTest.cs +++ b/test/EFCore.Cosmos.FunctionalTests/FindCosmosTest.cs @@ -27,6 +27,51 @@ public override void Find_derived_using_base_set_type_from_store() { } public override Task Find_derived_using_base_set_type_from_store_async(CancellationType cancellationType) => Task.CompletedTask; + public override void Find_int_key_from_store() + => CosmosTestHelpers.Instance.NoSyncTest(() => base.Find_int_key_from_store()); + + public override void Returns_null_for_int_key_not_in_store() + => CosmosTestHelpers.Instance.NoSyncTest(() => base.Returns_null_for_int_key_not_in_store()); + + public override void Find_nullable_int_key_from_store() + => CosmosTestHelpers.Instance.NoSyncTest(() => base.Find_nullable_int_key_from_store()); + + public override void Returns_null_for_nullable_int_key_not_in_store() + => CosmosTestHelpers.Instance.NoSyncTest(() => base.Returns_null_for_nullable_int_key_not_in_store()); + + public override void Find_string_key_from_store() + => CosmosTestHelpers.Instance.NoSyncTest(() => base.Find_string_key_from_store()); + + public override void Returns_null_for_string_key_not_in_store() + => CosmosTestHelpers.Instance.NoSyncTest(() => base.Returns_null_for_string_key_not_in_store()); + + public override void Find_composite_key_from_store() + => CosmosTestHelpers.Instance.NoSyncTest(() => base.Find_composite_key_from_store()); + + public override void Returns_null_for_composite_key_not_in_store() + => CosmosTestHelpers.Instance.NoSyncTest(() => base.Returns_null_for_composite_key_not_in_store()); + + public override void Find_base_type_from_store() + => CosmosTestHelpers.Instance.NoSyncTest(() => base.Find_base_type_from_store()); + + public override void Returns_null_for_base_type_not_in_store() + => CosmosTestHelpers.Instance.NoSyncTest(() => base.Returns_null_for_base_type_not_in_store()); + + public override void Find_derived_type_from_store() + => CosmosTestHelpers.Instance.NoSyncTest(() => base.Find_derived_type_from_store()); + + public override void Returns_null_for_derived_type_not_in_store() + => CosmosTestHelpers.Instance.NoSyncTest(() => base.Returns_null_for_derived_type_not_in_store()); + + public override void Find_base_type_using_derived_set_from_store() + => CosmosTestHelpers.Instance.NoSyncTest(() => base.Find_base_type_using_derived_set_from_store()); + + public override void Find_shadow_key_from_store() + => CosmosTestHelpers.Instance.NoSyncTest(() => base.Find_shadow_key_from_store()); + + public override void Returns_null_for_shadow_key_not_in_store() + => CosmosTestHelpers.Instance.NoSyncTest(() => base.Returns_null_for_shadow_key_not_in_store()); + public class FindCosmosTestSet(FindCosmosFixture fixture) : FindCosmosTest(fixture) { protected override TestFinder Finder { get; } = new FindViaSetFinder(); diff --git a/test/EFCore.Cosmos.FunctionalTests/JsonTypesCosmosTest.cs b/test/EFCore.Cosmos.FunctionalTests/JsonTypesCosmosTest.cs index 2abc333e2cf..0de9b43cc0c 100644 --- a/test/EFCore.Cosmos.FunctionalTests/JsonTypesCosmosTest.cs +++ b/test/EFCore.Cosmos.FunctionalTests/JsonTypesCosmosTest.cs @@ -9,320 +9,321 @@ public class JsonTypesCosmosTest : JsonTypesTestBase { // #25765 - the Cosmos type mapping source doesn't support primitive collections, so we end up with a Property // that has no ElementType; that causes the assertion on the element nullability to fail. - public override void Can_read_write_collection_of_string_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_string_JSON_values); + public override Task Can_read_write_collection_of_string_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_string_JSON_values); // #25765 - the Cosmos type mapping source doesn't support primitive collections, so we end up with a Property // that has no ElementType; that causes the assertion on the element nullability to fail. - public override void Can_read_write_collection_of_binary_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_binary_JSON_values); + public override Task Can_read_write_collection_of_binary_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_binary_JSON_values); // #25765 - the Cosmos type mapping source doesn't support primitive collections, so we end up with a Property // that has no ElementType; that causes the assertion on the element nullability to fail. - public override void Can_read_write_collection_of_nullable_string_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_nullable_string_JSON_values); + public override Task Can_read_write_collection_of_nullable_string_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_nullable_string_JSON_values); - public override void Can_read_write_binary_as_collection() - => Assert.Throws(base.Can_read_write_binary_as_collection); + public override Task Can_read_write_binary_as_collection() + => Assert.ThrowsAsync(base.Can_read_write_binary_as_collection); - public override void Can_read_write_collection_of_bool_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_bool_JSON_values); + public override Task Can_read_write_collection_of_bool_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_bool_JSON_values); - public override void Can_read_write_collection_of_byte_enum_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_byte_enum_JSON_values); + public override Task Can_read_write_collection_of_byte_enum_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_byte_enum_JSON_values); - public override void Can_read_write_collection_of_byte_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_byte_JSON_values); + public override Task Can_read_write_collection_of_byte_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_byte_JSON_values); - public override void Can_read_write_collection_of_char_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_char_JSON_values); + public override Task Can_read_write_collection_of_char_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_char_JSON_values); - public override void Can_read_write_collection_of_DateOnly_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_DateOnly_JSON_values); + public override Task Can_read_write_collection_of_DateOnly_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_DateOnly_JSON_values); - public override void Can_read_write_collection_of_DateTime_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_DateTime_JSON_values); + public override Task Can_read_write_collection_of_DateTime_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_DateTime_JSON_values); - public override void Can_read_write_collection_of_DateTimeOffset_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_DateTimeOffset_JSON_values); + public override Task Can_read_write_collection_of_DateTimeOffset_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_DateTimeOffset_JSON_values); - public override void Can_read_write_collection_of_decimal_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_decimal_JSON_values); + public override Task Can_read_write_collection_of_decimal_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_decimal_JSON_values); - public override void Can_read_write_collection_of_decimal_with_precision_and_scale_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_decimal_with_precision_and_scale_JSON_values); + public override Task Can_read_write_collection_of_decimal_with_precision_and_scale_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_decimal_with_precision_and_scale_JSON_values); - public override void Can_read_write_collection_of_double_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_double_JSON_values); + public override Task Can_read_write_collection_of_double_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_double_JSON_values); - public override void Can_read_write_collection_of_float_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_float_JSON_values); + public override Task Can_read_write_collection_of_float_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_float_JSON_values); - public override void Can_read_write_collection_of_Guid_converted_to_bytes_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_Guid_converted_to_bytes_JSON_values); + public override Task Can_read_write_collection_of_Guid_converted_to_bytes_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_Guid_converted_to_bytes_JSON_values); - public override void Can_read_write_collection_of_GUID_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_GUID_JSON_values); + public override Task Can_read_write_collection_of_GUID_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_GUID_JSON_values); - public override void Can_read_write_collection_of_int_enum_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_int_enum_JSON_values); + public override Task Can_read_write_collection_of_int_enum_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_int_enum_JSON_values); - public override void Can_read_write_collection_of_int_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_int_JSON_values); + public override Task Can_read_write_collection_of_int_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_int_JSON_values); - public override void Can_read_write_collection_of_int_with_converter_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_int_with_converter_JSON_values); + public override Task Can_read_write_collection_of_int_with_converter_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_int_with_converter_JSON_values); - public override void Can_read_write_collection_of_long_enum_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_long_enum_JSON_values); + public override Task Can_read_write_collection_of_long_enum_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_long_enum_JSON_values); - public override void Can_read_write_collection_of_long_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_long_JSON_values); + public override Task Can_read_write_collection_of_long_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_long_JSON_values); - public override void Can_read_write_collection_of_nullable_binary_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_nullable_binary_JSON_values); + public override Task Can_read_write_collection_of_nullable_binary_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_nullable_binary_JSON_values); - public override void Can_read_write_collection_of_nullable_bool_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_nullable_bool_JSON_values); + public override Task Can_read_write_collection_of_nullable_bool_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_nullable_bool_JSON_values); - public override void Can_read_write_collection_of_nullable_byte_enum_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_nullable_byte_enum_JSON_values); + public override Task Can_read_write_collection_of_nullable_byte_enum_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_nullable_byte_enum_JSON_values); - public override void Can_read_write_collection_of_nullable_byte_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_nullable_byte_JSON_values); + public override Task Can_read_write_collection_of_nullable_byte_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_nullable_byte_JSON_values); - public override void Can_read_write_collection_of_nullable_char_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_nullable_char_JSON_values); + public override Task Can_read_write_collection_of_nullable_char_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_nullable_char_JSON_values); - public override void Can_read_write_collection_of_nullable_DateOnly_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_nullable_DateOnly_JSON_values); + public override Task Can_read_write_collection_of_nullable_DateOnly_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_nullable_DateOnly_JSON_values); - public override void Can_read_write_collection_of_nullable_DateTime_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_nullable_DateTime_JSON_values); + public override Task Can_read_write_collection_of_nullable_DateTime_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_nullable_DateTime_JSON_values); - public override void Can_read_write_collection_of_nullable_DateTimeOffset_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_nullable_DateTimeOffset_JSON_values); + public override Task Can_read_write_collection_of_nullable_DateTimeOffset_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_nullable_DateTimeOffset_JSON_values); - public override void Can_read_write_collection_of_nullable_decimal_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_nullable_decimal_JSON_values); + public override Task Can_read_write_collection_of_nullable_decimal_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_nullable_decimal_JSON_values); - public override void Can_read_write_collection_of_nullable_double_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_nullable_double_JSON_values); + public override Task Can_read_write_collection_of_nullable_double_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_nullable_double_JSON_values); - public override void Can_read_write_collection_of_nullable_float_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_nullable_float_JSON_values); + public override Task Can_read_write_collection_of_nullable_float_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_nullable_float_JSON_values); - public override void Can_read_write_collection_of_nullable_GUID_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_nullable_GUID_JSON_values); + public override Task Can_read_write_collection_of_nullable_GUID_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_nullable_GUID_JSON_values); - public override void Can_read_write_collection_of_nullable_int_enum_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_nullable_int_enum_JSON_values); + public override Task Can_read_write_collection_of_nullable_int_enum_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_nullable_int_enum_JSON_values); - public override void Can_read_write_collection_of_nullable_int_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_nullable_int_JSON_values); + public override Task Can_read_write_collection_of_nullable_int_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_nullable_int_JSON_values); - public override void Can_read_write_collection_of_ushort_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_ushort_JSON_values); + public override Task Can_read_write_collection_of_ushort_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_ushort_JSON_values); - public override void Can_read_write_collection_of_ushort_enum_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_ushort_enum_JSON_values); + public override Task Can_read_write_collection_of_ushort_enum_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_ushort_enum_JSON_values); - public override void Can_read_write_collection_of_URI_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_URI_JSON_values); + public override Task Can_read_write_collection_of_URI_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_URI_JSON_values); - public override void Can_read_write_collection_of_ulong_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_ulong_JSON_values); + public override Task Can_read_write_collection_of_ulong_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_ulong_JSON_values); - public override void Can_read_write_collection_of_ulong_enum_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_ulong_enum_JSON_values); + public override Task Can_read_write_collection_of_ulong_enum_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_ulong_enum_JSON_values); - public override void Can_read_write_collection_of_uint_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_uint_JSON_values); + public override Task Can_read_write_collection_of_uint_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_uint_JSON_values); - public override void Can_read_write_collection_of_uint_enum_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_uint_enum_JSON_values); + public override Task Can_read_write_collection_of_uint_enum_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_uint_enum_JSON_values); - public override void Can_read_write_collection_of_TimeSpan_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_TimeSpan_JSON_values); + public override Task Can_read_write_collection_of_TimeSpan_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_TimeSpan_JSON_values); - public override void Can_read_write_collection_of_TimeOnly_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_TimeOnly_JSON_values); + public override Task Can_read_write_collection_of_TimeOnly_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_TimeOnly_JSON_values); - public override void Can_read_write_collection_of_short_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_short_JSON_values); + public override Task Can_read_write_collection_of_short_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_short_JSON_values); - public override void Can_read_write_collection_of_short_enum_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_short_enum_JSON_values); + public override Task Can_read_write_collection_of_short_enum_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_short_enum_JSON_values); - public override void Can_read_write_collection_of_sbyte_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_sbyte_JSON_values); + public override Task Can_read_write_collection_of_sbyte_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_sbyte_JSON_values); - public override void Can_read_write_collection_of_sbyte_enum_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_sbyte_enum_JSON_values); + public override Task Can_read_write_collection_of_sbyte_enum_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_sbyte_enum_JSON_values); - public override void Can_read_write_collection_of_physical_address_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_physical_address_JSON_values); + public override Task Can_read_write_collection_of_physical_address_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_physical_address_JSON_values); - public override void Can_read_write_collection_of_nullable_ushort_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_nullable_ushort_JSON_values); + public override Task Can_read_write_collection_of_nullable_ushort_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_nullable_ushort_JSON_values); - public override void Can_read_write_collection_of_nullable_ushort_enum_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_nullable_ushort_enum_JSON_values); + public override Task Can_read_write_collection_of_nullable_ushort_enum_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_nullable_ushort_enum_JSON_values); - public override void Can_read_write_collection_of_nullable_URI_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_nullable_URI_JSON_values); + public override Task Can_read_write_collection_of_nullable_URI_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_nullable_URI_JSON_values); - public override void Can_read_write_collection_of_nullable_ulong_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_nullable_ulong_JSON_values); + public override Task Can_read_write_collection_of_nullable_ulong_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_nullable_ulong_JSON_values); - public override void Can_read_write_collection_of_nullable_ulong_enum_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_nullable_ulong_enum_JSON_values); + public override Task Can_read_write_collection_of_nullable_ulong_enum_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_nullable_ulong_enum_JSON_values); - public override void Can_read_write_collection_of_nullable_uint_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_nullable_uint_JSON_values); + public override Task Can_read_write_collection_of_nullable_uint_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_nullable_uint_JSON_values); - public override void Can_read_write_collection_of_nullable_uint_enum_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_nullable_uint_enum_JSON_values); + public override Task Can_read_write_collection_of_nullable_uint_enum_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_nullable_uint_enum_JSON_values); - public override void Can_read_write_collection_of_nullable_TimeSpan_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_nullable_TimeSpan_JSON_values); + public override Task Can_read_write_collection_of_nullable_TimeSpan_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_nullable_TimeSpan_JSON_values); - public override void Can_read_write_collection_of_nullable_TimeOnly_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_nullable_TimeOnly_JSON_values); + public override Task Can_read_write_collection_of_nullable_TimeOnly_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_nullable_TimeOnly_JSON_values); - public override void Can_read_write_collection_of_nullable_short_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_nullable_short_JSON_values); + public override Task Can_read_write_collection_of_nullable_short_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_nullable_short_JSON_values); - public override void Can_read_write_collection_of_nullable_short_enum_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_nullable_short_enum_JSON_values); + public override Task Can_read_write_collection_of_nullable_short_enum_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_nullable_short_enum_JSON_values); - public override void Can_read_write_collection_of_nullable_sbyte_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_nullable_sbyte_JSON_values); + public override Task Can_read_write_collection_of_nullable_sbyte_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_nullable_sbyte_JSON_values); - public override void Can_read_write_collection_of_nullable_sbyte_enum_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_nullable_sbyte_enum_JSON_values); + public override Task Can_read_write_collection_of_nullable_sbyte_enum_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_nullable_sbyte_enum_JSON_values); - public override void Can_read_write_collection_of_nullable_physical_address_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_nullable_physical_address_JSON_values); + public override Task Can_read_write_collection_of_nullable_physical_address_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_nullable_physical_address_JSON_values); - public override void Can_read_write_collection_of_nullable_long_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_nullable_long_JSON_values); + public override Task Can_read_write_collection_of_nullable_long_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_nullable_long_JSON_values); - public override void Can_read_write_collection_of_nullable_long_enum_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_nullable_long_enum_JSON_values); + public override Task Can_read_write_collection_of_nullable_long_enum_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_nullable_long_enum_JSON_values); - public override void Can_read_write_collection_of_nullable_IP_address_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_nullable_IP_address_JSON_values); + public override Task Can_read_write_collection_of_nullable_IP_address_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_nullable_IP_address_JSON_values); - public override void Can_read_write_collection_of_nullable_int_with_converter_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_nullable_int_with_converter_JSON_values); + public override Task Can_read_write_collection_of_nullable_int_with_converter_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_nullable_int_with_converter_JSON_values); - public override void Can_read_write_collection_of_IP_address_JSON_values() - => Assert.Throws(base.Can_read_write_collection_of_IP_address_JSON_values); + public override Task Can_read_write_collection_of_IP_address_JSON_values() + => Assert.ThrowsAsync(base.Can_read_write_collection_of_IP_address_JSON_values); - public override void Can_read_write_point() + public override Task Can_read_write_point() // No built-in JSON support for spatial types in the Cosmos provider - => Assert.Throws(base.Can_read_write_point); + => Assert.ThrowsAsync(base.Can_read_write_point); - public override void Can_read_write_point_with_Z() + public override Task Can_read_write_point_with_Z() // No built-in JSON support for spatial types in the Cosmos provider - => Assert.Throws(base.Can_read_write_point_with_Z); + => Assert.ThrowsAsync(base.Can_read_write_point_with_Z); - public override void Can_read_write_point_with_M() + public override Task Can_read_write_point_with_M() // No built-in JSON support for spatial types in the Cosmos provider - => Assert.Throws(base.Can_read_write_point_with_M); + => Assert.ThrowsAsync(base.Can_read_write_point_with_M); - public override void Can_read_write_point_with_Z_and_M() + public override Task Can_read_write_point_with_Z_and_M() // No built-in JSON support for spatial types in the Cosmos provider - => Assert.Throws(base.Can_read_write_point_with_Z_and_M); + => Assert.ThrowsAsync(base.Can_read_write_point_with_Z_and_M); - public override void Can_read_write_line_string() + public override Task Can_read_write_line_string() // No built-in JSON support for spatial types in the Cosmos provider - => Assert.Throws(base.Can_read_write_line_string); + => Assert.ThrowsAsync(base.Can_read_write_line_string); - public override void Can_read_write_multi_line_string() + public override Task Can_read_write_multi_line_string() // No built-in JSON support for spatial types in the Cosmos provider - => Assert.Throws(base.Can_read_write_multi_line_string); + => Assert.ThrowsAsync(base.Can_read_write_multi_line_string); - public override void Can_read_write_polygon() + public override Task Can_read_write_polygon() // No built-in JSON support for spatial types in the Cosmos provider - => Assert.Throws(base.Can_read_write_polygon); + => Assert.ThrowsAsync(base.Can_read_write_polygon); - public override void Can_read_write_polygon_typed_as_geometry() + public override Task Can_read_write_polygon_typed_as_geometry() // No built-in JSON support for spatial types in the Cosmos provider - => Assert.Throws(base.Can_read_write_polygon_typed_as_geometry); + => Assert.ThrowsAsync(base.Can_read_write_polygon_typed_as_geometry); - public override void Can_read_write_point_as_GeoJson() + public override Task Can_read_write_point_as_GeoJson() // No built-in JSON support for spatial types in the Cosmos provider - => Assert.Throws(base.Can_read_write_point_as_GeoJson); + => Assert.ThrowsAsync(base.Can_read_write_point_as_GeoJson); - public override void Can_read_write_point_with_Z_as_GeoJson() + public override Task Can_read_write_point_with_Z_as_GeoJson() // No built-in JSON support for spatial types in the Cosmos provider - => Assert.Throws(base.Can_read_write_point_with_Z_as_GeoJson); + => Assert.ThrowsAsync(base.Can_read_write_point_with_Z_as_GeoJson); - public override void Can_read_write_point_with_M_as_GeoJson() + public override Task Can_read_write_point_with_M_as_GeoJson() // No built-in JSON support for spatial types in the Cosmos provider - => Assert.Throws(base.Can_read_write_point_with_M_as_GeoJson); + => Assert.ThrowsAsync(base.Can_read_write_point_with_M_as_GeoJson); - public override void Can_read_write_point_with_Z_and_M_as_GeoJson() + public override Task Can_read_write_point_with_Z_and_M_as_GeoJson() // No built-in JSON support for spatial types in the Cosmos provider - => Assert.Throws(base.Can_read_write_point_with_Z_and_M_as_GeoJson); + => Assert.ThrowsAsync(base.Can_read_write_point_with_Z_and_M_as_GeoJson); - public override void Can_read_write_line_string_as_GeoJson() + public override Task Can_read_write_line_string_as_GeoJson() // No built-in JSON support for spatial types in the Cosmos provider - => Assert.Throws(base.Can_read_write_line_string_as_GeoJson); + => Assert.ThrowsAsync(base.Can_read_write_line_string_as_GeoJson); - public override void Can_read_write_multi_line_string_as_GeoJson() + public override Task Can_read_write_multi_line_string_as_GeoJson() // No built-in JSON support for spatial types in the Cosmos provider - => Assert.Throws(base.Can_read_write_multi_line_string_as_GeoJson); + => Assert.ThrowsAsync(base.Can_read_write_multi_line_string_as_GeoJson); - public override void Can_read_write_polygon_as_GeoJson() + public override Task Can_read_write_polygon_as_GeoJson() // No built-in JSON support for spatial types in the Cosmos provider - => Assert.Throws(base.Can_read_write_polygon_as_GeoJson); + => Assert.ThrowsAsync(base.Can_read_write_polygon_as_GeoJson); - public override void Can_read_write_polygon_typed_as_geometry_as_GeoJson() + public override Task Can_read_write_polygon_typed_as_geometry_as_GeoJson() // No built-in JSON support for spatial types in the Cosmos provider - => Assert.Throws(base.Can_read_write_polygon_typed_as_geometry_as_GeoJson); + => Assert.ThrowsAsync(base.Can_read_write_polygon_typed_as_geometry_as_GeoJson); - public override void Can_read_write_nullable_point() + public override Task Can_read_write_nullable_point() // No built-in JSON support for spatial types in the Cosmos provider - => Assert.Throws(base.Can_read_write_point); + => Assert.ThrowsAsync(base.Can_read_write_point); - public override void Can_read_write_nullable_line_string() + public override Task Can_read_write_nullable_line_string() // No built-in JSON support for spatial types in the Cosmos provider - => Assert.Throws(base.Can_read_write_line_string); + => Assert.ThrowsAsync(base.Can_read_write_line_string); - public override void Can_read_write_nullable_multi_line_string() + public override Task Can_read_write_nullable_multi_line_string() // No built-in JSON support for spatial types in the Cosmos provider - => Assert.Throws(base.Can_read_write_multi_line_string); + => Assert.ThrowsAsync(base.Can_read_write_multi_line_string); - public override void Can_read_write_nullable_polygon() + public override Task Can_read_write_nullable_polygon() // No built-in JSON support for spatial types in the Cosmos provider - => Assert.Throws(base.Can_read_write_polygon); + => Assert.ThrowsAsync(base.Can_read_write_polygon); - public override void Can_read_write_nullable_point_as_GeoJson() + public override Task Can_read_write_nullable_point_as_GeoJson() // No built-in JSON support for spatial types in the Cosmos provider - => Assert.Throws(base.Can_read_write_point_as_GeoJson); + => Assert.ThrowsAsync(base.Can_read_write_point_as_GeoJson); - public override void Can_read_write_nullable_line_string_as_GeoJson() + public override Task Can_read_write_nullable_line_string_as_GeoJson() // No built-in JSON support for spatial types in the Cosmos provider - => Assert.Throws(base.Can_read_write_line_string_as_GeoJson); + => Assert.ThrowsAsync(base.Can_read_write_line_string_as_GeoJson); - public override void Can_read_write_nullable_multi_line_string_as_GeoJson() + public override Task Can_read_write_nullable_multi_line_string_as_GeoJson() // No built-in JSON support for spatial types in the Cosmos provider - => Assert.Throws(base.Can_read_write_multi_line_string_as_GeoJson); + => Assert.ThrowsAsync(base.Can_read_write_multi_line_string_as_GeoJson); - public override void Can_read_write_nullable_polygon_as_GeoJson() + public override Task Can_read_write_nullable_polygon_as_GeoJson() // No built-in JSON support for spatial types in the Cosmos provider - => Assert.Throws(base.Can_read_write_polygon_as_GeoJson); + => Assert.ThrowsAsync(base.Can_read_write_polygon_as_GeoJson); - public override void Can_read_write_polygon_typed_as_nullable_geometry() + public override Task Can_read_write_polygon_typed_as_nullable_geometry() // No built-in JSON support for spatial types in the Cosmos provider - => Assert.Throws(base.Can_read_write_polygon_typed_as_nullable_geometry); + => Assert.ThrowsAsync(base.Can_read_write_polygon_typed_as_nullable_geometry); - public override void Can_read_write_polygon_typed_as_nullable_geometry_as_GeoJson() + public override Task Can_read_write_polygon_typed_as_nullable_geometry_as_GeoJson() // No built-in JSON support for spatial types in the Cosmos provider - => Assert.Throws(base.Can_read_write_polygon_typed_as_nullable_geometry_as_GeoJson); + => Assert.ThrowsAsync(base.Can_read_write_polygon_typed_as_nullable_geometry_as_GeoJson); - protected override ITestStoreFactory TestStoreFactory => CosmosTestStoreFactory.Instance; + protected override ITestStoreFactory TestStoreFactory + => CosmosTestStoreFactory.Instance; } diff --git a/test/EFCore.Cosmos.FunctionalTests/KeysWithConvertersCosmosTest.cs b/test/EFCore.Cosmos.FunctionalTests/KeysWithConvertersCosmosTest.cs index a004b5e3bf9..29140b79416 100644 --- a/test/EFCore.Cosmos.FunctionalTests/KeysWithConvertersCosmosTest.cs +++ b/test/EFCore.Cosmos.FunctionalTests/KeysWithConvertersCosmosTest.cs @@ -8,143 +8,143 @@ namespace Microsoft.EntityFrameworkCore; public class KeysWithConvertersCosmosTest(KeysWithConvertersCosmosTest.KeysWithConvertersCosmosFixture fixture) : KeysWithConvertersTestBase(fixture) { [ConditionalFact(Skip = "Issue=#16920 (Include)")] - public override void Can_insert_and_read_back_with_struct_key_and_optional_dependents() + public override Task Can_insert_and_read_back_with_struct_key_and_optional_dependents() => base.Can_insert_and_read_back_with_struct_key_and_optional_dependents(); [ConditionalFact(Skip = "Issue=#16920 (Include)")] - public override void Can_insert_and_read_back_with_comparable_struct_key_and_optional_dependents() + public override Task Can_insert_and_read_back_with_comparable_struct_key_and_optional_dependents() => base.Can_insert_and_read_back_with_comparable_struct_key_and_optional_dependents(); [ConditionalFact(Skip = "Issue=#16920 (Include)")] - public override void Can_insert_and_read_back_with_generic_comparable_struct_key_and_optional_dependents() + public override Task Can_insert_and_read_back_with_generic_comparable_struct_key_and_optional_dependents() => base.Can_insert_and_read_back_with_generic_comparable_struct_key_and_optional_dependents(); [ConditionalFact(Skip = "Issue=#16920 (Include)")] - public override void Can_insert_and_read_back_with_struct_key_and_required_dependents() + public override Task Can_insert_and_read_back_with_struct_key_and_required_dependents() => base.Can_insert_and_read_back_with_struct_key_and_required_dependents(); [ConditionalFact(Skip = "Issue=#16920 (Include)")] - public override void Can_insert_and_read_back_with_comparable_struct_key_and_required_dependents() + public override Task Can_insert_and_read_back_with_comparable_struct_key_and_required_dependents() => base.Can_insert_and_read_back_with_comparable_struct_key_and_required_dependents(); [ConditionalFact(Skip = "Issue=#16920 (Include)")] - public override void Can_insert_and_read_back_with_generic_comparable_struct_key_and_required_dependents() + public override Task Can_insert_and_read_back_with_generic_comparable_struct_key_and_required_dependents() => base.Can_insert_and_read_back_with_generic_comparable_struct_key_and_required_dependents(); [ConditionalFact(Skip = "Issue=#16920 (Include)")] - public override void Can_insert_and_read_back_with_class_key_and_optional_dependents() + public override Task Can_insert_and_read_back_with_class_key_and_optional_dependents() => base.Can_insert_and_read_back_with_class_key_and_optional_dependents(); [ConditionalFact(Skip = "Issue=#16920 (Include)")] - public override void Can_insert_and_read_back_with_comparable_class_key_and_optional_dependents() + public override Task Can_insert_and_read_back_with_comparable_class_key_and_optional_dependents() => base.Can_insert_and_read_back_with_comparable_class_key_and_optional_dependents(); [ConditionalFact(Skip = "Issue=#16920 (Include)")] - public override void Can_insert_and_read_back_with_comparable_struct_binary_key_and_optional_dependents() + public override Task Can_insert_and_read_back_with_comparable_struct_binary_key_and_optional_dependents() => base.Can_insert_and_read_back_with_comparable_struct_binary_key_and_optional_dependents(); [ConditionalFact(Skip = "Issue=#16920 (Include)")] - public override void Can_insert_and_read_back_with_comparable_struct_binary_key_and_required_dependents() + public override Task Can_insert_and_read_back_with_comparable_struct_binary_key_and_required_dependents() => base.Can_insert_and_read_back_with_comparable_struct_binary_key_and_required_dependents(); [ConditionalFact(Skip = "Issue=#16920 (Include)")] - public override void Can_insert_and_read_back_with_generic_comparable_struct_binary_key_and_optional_dependents() + public override Task Can_insert_and_read_back_with_generic_comparable_struct_binary_key_and_optional_dependents() => base.Can_insert_and_read_back_with_generic_comparable_struct_binary_key_and_optional_dependents(); [ConditionalFact(Skip = "Issue=#16920 (Include)")] - public override void Can_insert_and_read_back_with_generic_comparable_struct_binary_key_and_required_dependents() + public override Task Can_insert_and_read_back_with_generic_comparable_struct_binary_key_and_required_dependents() => base.Can_insert_and_read_back_with_generic_comparable_struct_binary_key_and_required_dependents(); [ConditionalFact(Skip = "Issue=#16920 (Include)")] - public override void Can_insert_and_read_back_with_structural_struct_binary_key_and_optional_dependents() + public override Task Can_insert_and_read_back_with_structural_struct_binary_key_and_optional_dependents() => base.Can_insert_and_read_back_with_structural_struct_binary_key_and_optional_dependents(); [ConditionalFact(Skip = "Issue=#16920 (Include)")] - public override void Can_insert_and_read_back_with_structural_struct_binary_key_and_required_dependents() + public override Task Can_insert_and_read_back_with_structural_struct_binary_key_and_required_dependents() => base.Can_insert_and_read_back_with_structural_struct_binary_key_and_required_dependents(); [ConditionalFact(Skip = "Issue=#16920 (Include)")] - public override void Can_insert_and_read_back_with_struct_binary_key_and_optional_dependents() + public override Task Can_insert_and_read_back_with_struct_binary_key_and_optional_dependents() => base.Can_insert_and_read_back_with_struct_binary_key_and_optional_dependents(); [ConditionalFact(Skip = "Issue=#16920 (Include)")] - public override void Can_insert_and_read_back_with_struct_binary_key_and_required_dependents() + public override Task Can_insert_and_read_back_with_struct_binary_key_and_required_dependents() => base.Can_insert_and_read_back_with_struct_binary_key_and_required_dependents(); [ConditionalFact(Skip = "Issue=#16920 (Include)")] - public override void Can_insert_and_read_back_with_comparable_struct_binary_key_and_optional_dependents_with_shadow_FK() + public override Task Can_insert_and_read_back_with_comparable_struct_binary_key_and_optional_dependents_with_shadow_FK() => base.Can_insert_and_read_back_with_comparable_struct_binary_key_and_optional_dependents_with_shadow_FK(); [ConditionalFact(Skip = "Issue=#16920 (Include)")] - public override void Can_insert_and_read_back_with_comparable_struct_binary_key_and_required_dependents_with_shadow_FK() + public override Task Can_insert_and_read_back_with_comparable_struct_binary_key_and_required_dependents_with_shadow_FK() => base.Can_insert_and_read_back_with_comparable_struct_binary_key_and_required_dependents_with_shadow_FK(); [ConditionalFact(Skip = "Issue=#16920 (Include)")] - public override void Can_insert_and_read_back_with_comparable_struct_key_and_optional_dependents_with_shadow_FK() + public override Task Can_insert_and_read_back_with_comparable_struct_key_and_optional_dependents_with_shadow_FK() => base.Can_insert_and_read_back_with_comparable_struct_key_and_optional_dependents_with_shadow_FK(); [ConditionalFact(Skip = "Issue=#16920 (Include)")] - public override void Can_insert_and_read_back_with_comparable_struct_key_and_required_dependents_with_shadow_FK() + public override Task Can_insert_and_read_back_with_comparable_struct_key_and_required_dependents_with_shadow_FK() => base.Can_insert_and_read_back_with_comparable_struct_key_and_required_dependents_with_shadow_FK(); [ConditionalFact(Skip = "Issue=#16920 (Include)")] - public override void Can_insert_and_read_back_with_generic_comparable_struct_binary_key_and_optional_dependents_with_shadow_FK() + public override Task Can_insert_and_read_back_with_generic_comparable_struct_binary_key_and_optional_dependents_with_shadow_FK() => base.Can_insert_and_read_back_with_generic_comparable_struct_binary_key_and_optional_dependents_with_shadow_FK(); [ConditionalFact(Skip = "Issue=#16920 (Include)")] - public override void Can_insert_and_read_back_with_generic_comparable_struct_binary_key_and_required_dependents_with_shadow_FK() + public override Task Can_insert_and_read_back_with_generic_comparable_struct_binary_key_and_required_dependents_with_shadow_FK() => base.Can_insert_and_read_back_with_generic_comparable_struct_binary_key_and_required_dependents_with_shadow_FK(); [ConditionalFact(Skip = "Issue=#16920 (Include)")] - public override void Can_insert_and_read_back_with_generic_comparable_struct_key_and_optional_dependents_with_shadow_FK() + public override Task Can_insert_and_read_back_with_generic_comparable_struct_key_and_optional_dependents_with_shadow_FK() => base.Can_insert_and_read_back_with_generic_comparable_struct_key_and_optional_dependents_with_shadow_FK(); [ConditionalFact(Skip = "Issue=#16920 (Include)")] - public override void Can_insert_and_read_back_with_generic_comparable_struct_key_and_required_dependents_with_shadow_FK() + public override Task Can_insert_and_read_back_with_generic_comparable_struct_key_and_required_dependents_with_shadow_FK() => base.Can_insert_and_read_back_with_generic_comparable_struct_key_and_required_dependents_with_shadow_FK(); [ConditionalFact(Skip = "Issue=#16920 (Include)")] - public override void Can_insert_and_read_back_with_struct_binary_key_and_optional_dependents_with_shadow_FK() + public override Task Can_insert_and_read_back_with_struct_binary_key_and_optional_dependents_with_shadow_FK() => base.Can_insert_and_read_back_with_struct_binary_key_and_optional_dependents_with_shadow_FK(); [ConditionalFact(Skip = "Issue=#16920 (Include)")] - public override void Can_insert_and_read_back_with_struct_key_and_optional_dependents_with_shadow_FK() + public override Task Can_insert_and_read_back_with_struct_key_and_optional_dependents_with_shadow_FK() => base.Can_insert_and_read_back_with_struct_key_and_optional_dependents_with_shadow_FK(); [ConditionalFact(Skip = "Issue=#16920 (Include)")] - public override void Can_insert_and_read_back_with_struct_binary_key_and_required_dependents_with_shadow_FK() + public override Task Can_insert_and_read_back_with_struct_binary_key_and_required_dependents_with_shadow_FK() => base.Can_insert_and_read_back_with_struct_binary_key_and_required_dependents_with_shadow_FK(); [ConditionalFact(Skip = "Issue=#16920 (Include)")] - public override void Can_insert_and_read_back_with_struct_key_and_required_dependents_with_shadow_FK() + public override Task Can_insert_and_read_back_with_struct_key_and_required_dependents_with_shadow_FK() => base.Can_insert_and_read_back_with_struct_key_and_required_dependents_with_shadow_FK(); [ConditionalFact(Skip = "Issue=#16920 (Include)")] - public override void Can_insert_and_read_back_with_structural_struct_binary_key_and_optional_dependents_with_shadow_FK() + public override Task Can_insert_and_read_back_with_structural_struct_binary_key_and_optional_dependents_with_shadow_FK() => base.Can_insert_and_read_back_with_structural_struct_binary_key_and_optional_dependents_with_shadow_FK(); [ConditionalFact(Skip = "Issue=#16920 (Include)")] - public override void Can_insert_and_read_back_with_structural_struct_binary_key_and_required_dependents_with_shadow_FK() + public override Task Can_insert_and_read_back_with_structural_struct_binary_key_and_required_dependents_with_shadow_FK() => base.Can_insert_and_read_back_with_structural_struct_binary_key_and_required_dependents_with_shadow_FK(); [ConditionalFact(Skip = "Issue=#26239")] - public override void Can_insert_and_read_back_with_bare_class_key_and_optional_dependents() + public override Task Can_insert_and_read_back_with_bare_class_key_and_optional_dependents() => base.Can_insert_and_read_back_with_bare_class_key_and_optional_dependents(); [ConditionalFact(Skip = "Issue=#26239")] - public override void Can_insert_and_read_back_with_class_key_and_optional_dependents_with_shadow_FK() + public override Task Can_insert_and_read_back_with_class_key_and_optional_dependents_with_shadow_FK() => base.Can_insert_and_read_back_with_class_key_and_optional_dependents_with_shadow_FK(); [ConditionalFact(Skip = "Issue=#26239")] - public override void Can_insert_and_read_back_with_bare_class_key_and_optional_dependents_with_shadow_FK() + public override Task Can_insert_and_read_back_with_bare_class_key_and_optional_dependents_with_shadow_FK() => base.Can_insert_and_read_back_with_bare_class_key_and_optional_dependents_with_shadow_FK(); [ConditionalFact(Skip = "Issue=#26239")] - public override void Can_insert_and_read_back_with_comparable_class_key_and_optional_dependents_with_shadow_FK() + public override Task Can_insert_and_read_back_with_comparable_class_key_and_optional_dependents_with_shadow_FK() => base.Can_insert_and_read_back_with_comparable_class_key_and_optional_dependents_with_shadow_FK(); [ConditionalFact(Skip = "Issue=#26239")] - public override void Can_insert_and_read_back_with_enumerable_class_key_and_optional_dependents() + public override Task Can_insert_and_read_back_with_enumerable_class_key_and_optional_dependents() => base.Can_insert_and_read_back_with_enumerable_class_key_and_optional_dependents(); public class KeysWithConvertersCosmosFixture : KeysWithConvertersFixtureBase diff --git a/test/EFCore.Cosmos.FunctionalTests/MaterializationInterceptionCosmosTest.cs b/test/EFCore.Cosmos.FunctionalTests/MaterializationInterceptionCosmosTest.cs index 6eb6cc1db04..189b6226411 100644 --- a/test/EFCore.Cosmos.FunctionalTests/MaterializationInterceptionCosmosTest.cs +++ b/test/EFCore.Cosmos.FunctionalTests/MaterializationInterceptionCosmosTest.cs @@ -11,6 +11,9 @@ public class MaterializationInterceptionCosmosTest : public override Task Intercept_query_materialization_with_owned_types_projecting_collection(bool async, bool usePooling) => Task.CompletedTask; + public override Task Intercept_query_materialization_with_owned_types(bool async, bool usePooling) + => CosmosTestHelpers.Instance.NoSyncTest(async, a => base.Intercept_query_materialization_with_owned_types(a, usePooling)); + public class CosmosLibraryContext(DbContextOptions options) : LibraryContext(options) { protected override void OnModelCreating(ModelBuilder modelBuilder) diff --git a/test/EFCore.Cosmos.FunctionalTests/OptimisticConcurrencyCosmosTest.cs b/test/EFCore.Cosmos.FunctionalTests/OptimisticConcurrencyCosmosTest.cs index 69bb109f823..b690a982c4a 100644 --- a/test/EFCore.Cosmos.FunctionalTests/OptimisticConcurrencyCosmosTest.cs +++ b/test/EFCore.Cosmos.FunctionalTests/OptimisticConcurrencyCosmosTest.cs @@ -7,14 +7,9 @@ namespace Microsoft.EntityFrameworkCore; #nullable disable -public class OptimisticConcurrencyCosmosTest : OptimisticConcurrencyTestBase, byte[]> +public class OptimisticConcurrencyCosmosTest(F1CosmosFixture fixture) + : OptimisticConcurrencyTestBase, byte[]>(fixture), IAsyncLifetime { - public OptimisticConcurrencyCosmosTest(F1CosmosFixture fixture) - : base(fixture) - { - fixture.Reseed(); - } - // Non-persisted property in query // Issue #17670 public override Task Calling_GetDatabaseValues_on_owned_entity_works(bool async) @@ -48,9 +43,56 @@ public override Task Attempting_to_delete_same_relationship_twice_for_many_to_ma public override Task Attempting_to_add_same_relationship_twice_for_many_to_many_results_in_independent_association_exception() => Task.CompletedTask; + // Uses lazy-loader, which is always sync + public override Task Two_concurrency_issues_in_one_to_one_related_entities_can_be_handled_by_dealing_with_dependent_first() + => CosmosTestHelpers.Instance.NoSyncTest( + false, + _ => base.Two_concurrency_issues_in_one_to_one_related_entities_can_be_handled_by_dealing_with_dependent_first()); + + // Uses lazy-loader, which is always sync + public override Task Two_concurrency_issues_in_one_to_many_related_entities_can_be_handled_by_dealing_with_dependent_first() + => CosmosTestHelpers.Instance.NoSyncTest( + false, + _ => base.Two_concurrency_issues_in_one_to_many_related_entities_can_be_handled_by_dealing_with_dependent_first()); + protected override IDbContextTransaction BeginTransaction(DatabaseFacade facade) => new FakeDbContextTransaction(); + public override Task Calling_Reload_on_an_Added_entity_that_is_not_in_database_is_no_op(bool async) + => CosmosTestHelpers.Instance.NoSyncTest(async, a => base.Calling_Reload_on_an_Added_entity_that_is_not_in_database_is_no_op(a)); + + public override Task Calling_Reload_on_an_Unchanged_entity_that_is_not_in_database_detaches_it(bool async) + => CosmosTestHelpers.Instance.NoSyncTest( + async, a => base.Calling_Reload_on_an_Unchanged_entity_that_is_not_in_database_detaches_it(a)); + + public override Task Calling_Reload_on_a_Modified_entity_that_is_not_in_database_detaches_it(bool async) + => CosmosTestHelpers.Instance.NoSyncTest( + async, a => base.Calling_Reload_on_a_Modified_entity_that_is_not_in_database_detaches_it(a)); + + public override Task Calling_Reload_on_a_Deleted_entity_that_is_not_in_database_detaches_it(bool async) + => CosmosTestHelpers.Instance.NoSyncTest( + async, a => base.Calling_Reload_on_a_Deleted_entity_that_is_not_in_database_detaches_it(a)); + + public override Task Calling_Reload_on_a_Detached_entity_that_is_not_in_database_detaches_it(bool async) + => CosmosTestHelpers.Instance.NoSyncTest( + async, a => base.Calling_Reload_on_a_Detached_entity_that_is_not_in_database_detaches_it(a)); + + public override Task Calling_Reload_on_an_Unchanged_entity_makes_the_entity_unchanged(bool async) + => CosmosTestHelpers.Instance.NoSyncTest(async, a => base.Calling_Reload_on_an_Unchanged_entity_makes_the_entity_unchanged(a)); + + public override Task Calling_Reload_on_a_Modified_entity_makes_the_entity_unchanged(bool async) + => CosmosTestHelpers.Instance.NoSyncTest(async, a => base.Calling_Reload_on_a_Modified_entity_makes_the_entity_unchanged(a)); + + public override Task Calling_Reload_on_a_Deleted_entity_makes_the_entity_unchanged(bool async) + => CosmosTestHelpers.Instance.NoSyncTest(async, a => base.Calling_Reload_on_a_Deleted_entity_makes_the_entity_unchanged(a)); + + public override Task Calling_Reload_on_an_Added_entity_that_was_saved_elsewhere_makes_the_entity_unchanged(bool async) + => CosmosTestHelpers.Instance.NoSyncTest( + async, a => base.Calling_Reload_on_an_Added_entity_that_was_saved_elsewhere_makes_the_entity_unchanged(a)); + + public override Task Calling_Reload_on_a_Detached_entity_makes_the_entity_unchanged(bool async) + => CosmosTestHelpers.Instance.NoSyncTest(async, a => base.Calling_Reload_on_a_Detached_entity_makes_the_entity_unchanged(a)); + private class FakeDbContextTransaction : IDbContextTransaction { public Guid TransactionId @@ -77,4 +119,10 @@ public void Rollback() public Task RollbackAsync(CancellationToken cancellationToken = default) => Task.CompletedTask; } + + public Task InitializeAsync() + => Fixture.ReseedAsync(); + + public Task DisposeAsync() + => Task.CompletedTask; } diff --git a/test/EFCore.Cosmos.FunctionalTests/Query/FromSqlQueryCosmosTest.cs b/test/EFCore.Cosmos.FunctionalTests/Query/FromSqlQueryCosmosTest.cs index 89e9555e112..83a4a13564c 100644 --- a/test/EFCore.Cosmos.FunctionalTests/Query/FromSqlQueryCosmosTest.cs +++ b/test/EFCore.Cosmos.FunctionalTests/Query/FromSqlQueryCosmosTest.cs @@ -25,38 +25,37 @@ protected NorthwindContext CreateContext() [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public async Task FromSqlRaw_queryable_simple(bool async) - { - using var context = CreateContext(); - var query = context.Set().FromSqlRaw( - @"SELECT * FROM root c WHERE c[""Discriminator""] = ""Customer"" AND c[""ContactName""] LIKE '%z%'"); + public Task FromSqlRaw_queryable_simple(bool async) + => Fixture.NoSyncTest( + async, async a => + { + using var context = CreateContext(); + var query = context.Set().FromSqlRaw( + @"SELECT * FROM root c WHERE c[""Discriminator""] = ""Customer"" AND c[""ContactName""] LIKE '%z%'"); - var actual = async - ? await query.ToArrayAsync() - : query.ToArray(); + var actual = a + ? await query.ToArrayAsync() + : query.ToArray(); - Assert.Equal(14, actual.Length); - Assert.Equal(14, context.ChangeTracker.Entries().Count()); + Assert.Equal(14, actual.Length); + Assert.Equal(14, context.ChangeTracker.Entries().Count()); - AssertSql( - """ + AssertSql( + """ SELECT c FROM ( SELECT * FROM root c WHERE c["Discriminator"] = "Customer" AND c["ContactName"] LIKE '%z%' ) c """); - } + }); - [ConditionalTheory] - [MemberData(nameof(IsAsyncData))] - public async Task FromSqlRaw_queryable_incorrect_discriminator_throws(bool async) + [ConditionalFact] + public async Task FromSqlRaw_queryable_incorrect_discriminator_throws() { using var context = CreateContext(); var query = context.Set().FromSqlRaw(@"SELECT * FROM root c WHERE c[""Discriminator""] = ""Order"""); - var exception = async - ? await Assert.ThrowsAsync(() => query.ToArrayAsync()) - : Assert.Throws(() => query.ToArray()); + var exception = await Assert.ThrowsAsync(() => query.ToArrayAsync()); Assert.Equal( CoreStrings.UnableToDiscriminate(context.Model.FindEntityType(typeof(Customer))!.DisplayName(), "Order"), @@ -65,215 +64,229 @@ public async Task FromSqlRaw_queryable_incorrect_discriminator_throws(bool async [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public async Task FromSqlRaw_queryable_simple_columns_out_of_order(bool async) - { - using var context = CreateContext(); - var query = context.Set().FromSqlRaw( - @"SELECT c[""id""], c[""Discriminator""], c[""Region""], c[""PostalCode""], c[""Phone""], c[""Fax""], c[""CustomerID""], c[""Country""], c[""ContactTitle""], c[""ContactName""], c[""CompanyName""], c[""City""], c[""Address""] FROM root c WHERE c[""Discriminator""] = ""Customer"""); + public Task FromSqlRaw_queryable_simple_columns_out_of_order(bool async) + => Fixture.NoSyncTest( + async, async a => + { + using var context = CreateContext(); + var query = context.Set().FromSqlRaw( + @"SELECT c[""id""], c[""Discriminator""], c[""Region""], c[""PostalCode""], c[""Phone""], c[""Fax""], c[""CustomerID""], c[""Country""], c[""ContactTitle""], c[""ContactName""], c[""CompanyName""], c[""City""], c[""Address""] FROM root c WHERE c[""Discriminator""] = ""Customer"""); - var actual = async - ? await query.ToArrayAsync() - : query.ToArray(); + var actual = a + ? await query.ToArrayAsync() + : query.ToArray(); - Assert.Equal(91, actual.Length); - Assert.Equal(91, context.ChangeTracker.Entries().Count()); + Assert.Equal(91, actual.Length); + Assert.Equal(91, context.ChangeTracker.Entries().Count()); - AssertSql( - """ + AssertSql( + """ SELECT c FROM ( SELECT c["id"], c["Discriminator"], c["Region"], c["PostalCode"], c["Phone"], c["Fax"], c["CustomerID"], c["Country"], c["ContactTitle"], c["ContactName"], c["CompanyName"], c["City"], c["Address"] FROM root c WHERE c["Discriminator"] = "Customer" ) c """); - } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public async Task FromSqlRaw_queryable_simple_columns_out_of_order_and_extra_columns(bool async) - { - using var context = CreateContext(); - var query = context.Set().FromSqlRaw( - @"SELECT c[""id""], c[""Discriminator""], c[""Region""], c[""PostalCode""], c[""PostalCode""] AS Foo, c[""Phone""], c[""Fax""], c[""CustomerID""], c[""Country""], c[""ContactTitle""], c[""ContactName""], c[""CompanyName""], c[""City""], c[""Address""] FROM root c WHERE c[""Discriminator""] = ""Customer"""); + public Task FromSqlRaw_queryable_simple_columns_out_of_order_and_extra_columns(bool async) + => Fixture.NoSyncTest( + async, async a => + { + using var context = CreateContext(); + var query = context.Set().FromSqlRaw( + @"SELECT c[""id""], c[""Discriminator""], c[""Region""], c[""PostalCode""], c[""PostalCode""] AS Foo, c[""Phone""], c[""Fax""], c[""CustomerID""], c[""Country""], c[""ContactTitle""], c[""ContactName""], c[""CompanyName""], c[""City""], c[""Address""] FROM root c WHERE c[""Discriminator""] = ""Customer"""); - var actual = async - ? await query.ToArrayAsync() - : query.ToArray(); + var actual = a + ? await query.ToArrayAsync() + : query.ToArray(); - Assert.Equal(91, actual.Length); - Assert.Equal(91, context.ChangeTracker.Entries().Count()); + Assert.Equal(91, actual.Length); + Assert.Equal(91, context.ChangeTracker.Entries().Count()); - AssertSql( - """ + AssertSql( + """ SELECT c FROM ( SELECT c["id"], c["Discriminator"], c["Region"], c["PostalCode"], c["PostalCode"] AS Foo, c["Phone"], c["Fax"], c["CustomerID"], c["Country"], c["ContactTitle"], c["ContactName"], c["CompanyName"], c["City"], c["Address"] FROM root c WHERE c["Discriminator"] = "Customer" ) c """); - } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public async Task FromSqlRaw_queryable_composed(bool async) - { - using var context = CreateContext(); - var query = context.Set().FromSqlRaw(@"SELECT * FROM root c WHERE c[""Discriminator""] = ""Customer""") - .Where(c => c.ContactName.Contains("z")); + public Task FromSqlRaw_queryable_composed(bool async) + => Fixture.NoSyncTest( + async, async a => + { + using var context = CreateContext(); + var query = context.Set().FromSqlRaw(@"SELECT * FROM root c WHERE c[""Discriminator""] = ""Customer""") + .Where(c => c.ContactName.Contains("z")); - var sql = query.ToQueryString(); + var sql = query.ToQueryString(); - var actual = async - ? await query.ToArrayAsync() - : query.ToArray(); + var actual = a + ? await query.ToArrayAsync() + : query.ToArray(); - Assert.Equal(14, actual.Length); - Assert.Equal(14, context.ChangeTracker.Entries().Count()); + Assert.Equal(14, actual.Length); + Assert.Equal(14, context.ChangeTracker.Entries().Count()); - AssertSql( - """ + AssertSql( + """ SELECT c FROM ( SELECT * FROM root c WHERE c["Discriminator"] = "Customer" ) c WHERE CONTAINS(c["ContactName"], "z") """); - } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual async Task FromSqlRaw_queryable_composed_after_removing_whitespaces(bool async) - { - using var context = CreateContext(); - var query = context.Set().FromSqlRaw( - _eol + " " + _eol + _eol + _eol + "SELECT" + _eol + @"* FROM root c WHERE c[""Discriminator""] = ""Customer""") - .Where(c => c.ContactName.Contains("z")); + public virtual Task FromSqlRaw_queryable_composed_after_removing_whitespaces(bool async) + => Fixture.NoSyncTest( + async, async a => + { + using var context = CreateContext(); + var query = context.Set().FromSqlRaw( + _eol + " " + _eol + _eol + _eol + "SELECT" + _eol + @"* FROM root c WHERE c[""Discriminator""] = ""Customer""") + .Where(c => c.ContactName.Contains("z")); - var actual = async - ? await query.ToArrayAsync() - : query.ToArray(); + var actual = a + ? await query.ToArrayAsync() + : query.ToArray(); - Assert.Equal(14, actual.Length); + Assert.Equal(14, actual.Length); - AssertSql( - @"SELECT c + AssertSql( + @"SELECT c FROM ( " - + @" + + @" SELECT * FROM root c WHERE c[""Discriminator""] = ""Customer"" ) c WHERE CONTAINS(c[""ContactName""], ""z"")"); - } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public async Task FromSqlRaw_queryable_composed_compiled(bool async) - { - if (async) - { - var query = EF.CompileAsyncQuery( - (NorthwindContext context) => context.Set() - .FromSqlRaw(@"SELECT * FROM root c WHERE c[""Discriminator""] = ""Customer""") - .Where(c => c.ContactName.Contains("z"))); - - using (var context = CreateContext()) + public Task FromSqlRaw_queryable_composed_compiled(bool async) + => Fixture.NoSyncTest( + async, async a => { - var actual = await query(context).ToListAsync(); - - Assert.Equal(14, actual.Count); - } - } - else - { - var query = EF.CompileQuery( - (NorthwindContext context) => context.Set() - .FromSqlRaw(@"SELECT * FROM root c WHERE c[""Discriminator""] = ""Customer""") - .Where(c => c.ContactName.Contains("z"))); - - using (var context = CreateContext()) - { - var actual = query(context).ToArray(); - - Assert.Equal(14, actual.Length); - } - } - - AssertSql( - """ + if (a) + { + var query = EF.CompileAsyncQuery( + (NorthwindContext context) => context.Set() + .FromSqlRaw(@"SELECT * FROM root c WHERE c[""Discriminator""] = ""Customer""") + .Where(c => c.ContactName.Contains("z"))); + + using (var context = CreateContext()) + { + var actual = await query(context).ToListAsync(); + + Assert.Equal(14, actual.Count); + } + } + else + { + var query = EF.CompileQuery( + (NorthwindContext context) => context.Set() + .FromSqlRaw(@"SELECT * FROM root c WHERE c[""Discriminator""] = ""Customer""") + .Where(c => c.ContactName.Contains("z"))); + + using (var context = CreateContext()) + { + var actual = query(context).ToArray(); + + Assert.Equal(14, actual.Length); + } + } + + AssertSql( + """ SELECT c FROM ( SELECT * FROM root c WHERE c["Discriminator"] = "Customer" ) c WHERE CONTAINS(c["ContactName"], "z") """); - } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual async Task FromSqlRaw_queryable_composed_compiled_with_parameter(bool async) - { - if (async) - { - var query = EF.CompileAsyncQuery( - (NorthwindContext context) => context.Set().FromSqlRaw( - @"SELECT * FROM root c WHERE c[""Discriminator""] = ""Customer"" AND c[""CustomerID""] = {0}", "CONSH") - .Where(c => c.ContactName.Contains("z"))); - - using (var context = CreateContext()) + public virtual Task FromSqlRaw_queryable_composed_compiled_with_parameter(bool async) + => Fixture.NoSyncTest( + async, async a => { - var actual = await query(context).ToListAsync(); - - Assert.Single(actual); - } - } - else - { - var query = EF.CompileQuery( - (NorthwindContext context) => context.Set().FromSqlRaw( - @"SELECT * FROM root c WHERE c[""Discriminator""] = ""Customer"" AND c[""CustomerID""] = {0}", "CONSH") - .Where(c => c.ContactName.Contains("z"))); - - using (var context = CreateContext()) - { - var actual = query(context).ToArray(); - - Assert.Single(actual); - } - } - - AssertSql( - """ + if (a) + { + var query = EF.CompileAsyncQuery( + (NorthwindContext context) => context.Set().FromSqlRaw( + @"SELECT * FROM root c WHERE c[""Discriminator""] = ""Customer"" AND c[""CustomerID""] = {0}", "CONSH") + .Where(c => c.ContactName.Contains("z"))); + + using (var context = CreateContext()) + { + var actual = await query(context).ToListAsync(); + + Assert.Single(actual); + } + } + else + { + var query = EF.CompileQuery( + (NorthwindContext context) => context.Set().FromSqlRaw( + @"SELECT * FROM root c WHERE c[""Discriminator""] = ""Customer"" AND c[""CustomerID""] = {0}", "CONSH") + .Where(c => c.ContactName.Contains("z"))); + + using (var context = CreateContext()) + { + var actual = query(context).ToArray(); + + Assert.Single(actual); + } + } + + AssertSql( + """ SELECT c FROM ( SELECT * FROM root c WHERE c["Discriminator"] = "Customer" AND c["CustomerID"] = "CONSH" ) c WHERE CONTAINS(c["ContactName"], "z") """); - } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual async Task FromSqlRaw_queryable_multiple_line_query(bool async) - { - using var context = CreateContext(); - var query = context.Set().FromSqlRaw( - """ + public virtual Task FromSqlRaw_queryable_multiple_line_query(bool async) + => Fixture.NoSyncTest( + async, async a => + { + using var context = CreateContext(); + var query = context.Set().FromSqlRaw( + """ SELECT * FROM root c WHERE c["Discriminator"] = "Customer" AND c["City"] = 'London' """); - var actual = async - ? await query.ToArrayAsync() - : query.ToArray(); + var actual = a + ? await query.ToArrayAsync() + : query.ToArray(); - Assert.Equal(6, actual.Length); - Assert.True(actual.All(c => c.City == "London")); + Assert.Equal(6, actual.Length); + Assert.True(actual.All(c => c.City == "London")); - AssertSql( - """ + AssertSql( + """ SELECT c FROM ( SELECT * @@ -281,30 +294,32 @@ FROM root c WHERE c["Discriminator"] = "Customer" AND c["City"] = 'London' ) c """); - } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual async Task FromSqlRaw_queryable_composed_multiple_line_query(bool async) - { - using var context = CreateContext(); - var query = context.Set().FromSqlRaw( - """ + public virtual Task FromSqlRaw_queryable_composed_multiple_line_query(bool async) + => Fixture.NoSyncTest( + async, async a => + { + using var context = CreateContext(); + var query = context.Set().FromSqlRaw( + """ SELECT * FROM root c WHERE c["Discriminator"] = "Customer" """) - .Where(c => c.City == "London"); + .Where(c => c.City == "London"); - var actual = async - ? await query.ToArrayAsync() - : query.ToArray(); + var actual = a + ? await query.ToArrayAsync() + : query.ToArray(); - Assert.Equal(6, actual.Length); - Assert.True(actual.All(c => c.City == "London")); + Assert.Equal(6, actual.Length); + Assert.True(actual.All(c => c.City == "London")); - AssertSql( - """ + AssertSql( + """ SELECT c FROM ( SELECT * @@ -313,30 +328,33 @@ FROM root c ) c WHERE (c["City"] = "London") """); - } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public async Task FromSqlRaw_queryable_with_parameters(bool async) - { - var city = "London"; - var contactTitle = "Sales Representative"; + public Task FromSqlRaw_queryable_with_parameters(bool async) + => Fixture.NoSyncTest( + async, async a => + { + var city = "London"; + var contactTitle = "Sales Representative"; - using var context = CreateContext(); - var query = context.Set().FromSqlRaw( - @"SELECT * FROM root c WHERE c[""Discriminator""] = ""Customer"" AND c[""City""] = {0} AND c[""ContactTitle""] = {1}", city, - contactTitle); + using var context = CreateContext(); + var query = context.Set().FromSqlRaw( + @"SELECT * FROM root c WHERE c[""Discriminator""] = ""Customer"" AND c[""City""] = {0} AND c[""ContactTitle""] = {1}", + city, + contactTitle); - var actual = async - ? await query.ToArrayAsync() - : query.ToArray(); + var actual = a + ? await query.ToArrayAsync() + : query.ToArray(); - Assert.Equal(3, actual.Length); - Assert.True(actual.All(c => c.City == "London")); - Assert.True(actual.All(c => c.ContactTitle == "Sales Representative")); + Assert.Equal(3, actual.Length); + Assert.True(actual.All(c => c.City == "London")); + Assert.True(actual.All(c => c.ContactTitle == "Sales Representative")); - AssertSql( - """ + AssertSql( + """ @p0='London' @p1='Sales Representative' @@ -345,28 +363,30 @@ SELECT c SELECT * FROM root c WHERE c["Discriminator"] = "Customer" AND c["City"] = @p0 AND c["ContactTitle"] = @p1 ) c """); - } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public async Task FromSqlRaw_queryable_with_parameters_inline(bool async) - { - using var context = CreateContext(); - var query = context.Set().FromSqlRaw( - @"SELECT * FROM root c WHERE c[""Discriminator""] = ""Customer"" AND c[""City""] = {0} AND c[""ContactTitle""] = {1}", - "London", - "Sales Representative"); - - var actual = async - ? await query.ToArrayAsync() - : query.ToArray(); - - Assert.Equal(3, actual.Length); - Assert.True(actual.All(c => c.City == "London")); - Assert.True(actual.All(c => c.ContactTitle == "Sales Representative")); - - AssertSql( - """ + public Task FromSqlRaw_queryable_with_parameters_inline(bool async) + => Fixture.NoSyncTest( + async, async a => + { + using var context = CreateContext(); + var query = context.Set().FromSqlRaw( + @"SELECT * FROM root c WHERE c[""Discriminator""] = ""Customer"" AND c[""City""] = {0} AND c[""ContactTitle""] = {1}", + "London", + "Sales Representative"); + + var actual = a + ? await query.ToArrayAsync() + : query.ToArray(); + + Assert.Equal(3, actual.Length); + Assert.True(actual.All(c => c.City == "London")); + Assert.True(actual.All(c => c.ContactTitle == "Sales Representative")); + + AssertSql( + """ @p0='London' @p1='Sales Representative' @@ -375,27 +395,29 @@ SELECT c SELECT * FROM root c WHERE c["Discriminator"] = "Customer" AND c["City"] = @p0 AND c["ContactTitle"] = @p1 ) c """); - } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public async Task FromSqlRaw_queryable_with_null_parameter(bool async) - { - uint? reportsTo = null; + public Task FromSqlRaw_queryable_with_null_parameter(bool async) + => Fixture.NoSyncTest( + async, async a => + { + uint? reportsTo = null; - using var context = CreateContext(); - var query = context.Set().FromSqlRaw( - @"SELECT * FROM root c WHERE c[""Discriminator""] = ""Employee"" AND c[""ReportsTo""] = {0} OR (IS_NULL(c[""ReportsTo""]) AND IS_NULL({0}))", - reportsTo); + using var context = CreateContext(); + var query = context.Set().FromSqlRaw( + @"SELECT * FROM root c WHERE c[""Discriminator""] = ""Employee"" AND c[""ReportsTo""] = {0} OR (IS_NULL(c[""ReportsTo""]) AND IS_NULL({0}))", + reportsTo); - var actual = async - ? await query.ToArrayAsync() - : query.ToArray(); + var actual = a + ? await query.ToArrayAsync() + : query.ToArray(); - Assert.Single(actual); + Assert.Single(actual); - AssertSql( - """ + AssertSql( + """ @p0=null SELECT c @@ -403,31 +425,33 @@ SELECT c SELECT * FROM root c WHERE c["Discriminator"] = "Employee" AND c["ReportsTo"] = @p0 OR (IS_NULL(c["ReportsTo"]) AND IS_NULL(@p0)) ) c """); - } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public async Task FromSqlRaw_queryable_with_parameters_and_closure(bool async) - { - var city = "London"; - var contactTitle = "Sales Representative"; + public Task FromSqlRaw_queryable_with_parameters_and_closure(bool async) + => Fixture.NoSyncTest( + async, async a => + { + var city = "London"; + var contactTitle = "Sales Representative"; - using var context = CreateContext(); - var query = context.Set().FromSqlRaw( - @"SELECT * FROM root c WHERE c[""Discriminator""] = ""Customer"" AND c[""City""] = {0}", city) - .Where(c => c.ContactTitle == contactTitle); - var queryString = query.ToQueryString(); + using var context = CreateContext(); + var query = context.Set().FromSqlRaw( + @"SELECT * FROM root c WHERE c[""Discriminator""] = ""Customer"" AND c[""City""] = {0}", city) + .Where(c => c.ContactTitle == contactTitle); + var queryString = query.ToQueryString(); - var actual = async - ? await query.ToArrayAsync() - : query.ToArray(); + var actual = a + ? await query.ToArrayAsync() + : query.ToArray(); - Assert.Equal(3, actual.Length); - Assert.True(actual.All(c => c.City == "London")); - Assert.True(actual.All(c => c.ContactTitle == "Sales Representative")); + Assert.Equal(3, actual.Length); + Assert.True(actual.All(c => c.City == "London")); + Assert.True(actual.All(c => c.ContactTitle == "Sales Representative")); - AssertSql( - """ + AssertSql( + """ @p0='London' @__contactTitle_1='Sales Representative' @@ -437,83 +461,88 @@ SELECT c ) c WHERE (c["ContactTitle"] = @__contactTitle_1) """); - } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual async Task FromSqlRaw_queryable_simple_cache_key_includes_query_string(bool async) - { - using var context = CreateContext(); - var query = context.Set() - .FromSqlRaw(@"SELECT * FROM root c WHERE c[""Discriminator""] = ""Customer"" AND c[""City""] = 'London'"); + public virtual Task FromSqlRaw_queryable_simple_cache_key_includes_query_string(bool async) + => Fixture.NoSyncTest( + async, async a => + { + using var context = CreateContext(); + var query = context.Set() + .FromSqlRaw(@"SELECT * FROM root c WHERE c[""Discriminator""] = ""Customer"" AND c[""City""] = 'London'"); - var actual = async - ? await query.ToArrayAsync() - : query.ToArray(); + var actual = a + ? await query.ToArrayAsync() + : query.ToArray(); - Assert.Equal(6, actual.Length); - Assert.True(actual.All(c => c.City == "London")); + Assert.Equal(6, actual.Length); + Assert.True(actual.All(c => c.City == "London")); - query = context.Set() - .FromSqlRaw(@"SELECT * FROM root c WHERE c[""Discriminator""] = ""Customer"" AND c[""City""] = 'Seattle'"); + query = context.Set() + .FromSqlRaw(@"SELECT * FROM root c WHERE c[""Discriminator""] = ""Customer"" AND c[""City""] = 'Seattle'"); - actual = async - ? await query.ToArrayAsync() - : query.ToArray(); + actual = a + ? await query.ToArrayAsync() + : query.ToArray(); - Assert.Single(actual); - Assert.True(actual.All(c => c.City == "Seattle")); + Assert.Single(actual); + Assert.True(actual.All(c => c.City == "Seattle")); - AssertSql( - """ + AssertSql( + """ SELECT c FROM ( SELECT * FROM root c WHERE c["Discriminator"] = "Customer" AND c["City"] = 'London' ) c """, - // - """ + // + """ SELECT c FROM ( SELECT * FROM root c WHERE c["Discriminator"] = "Customer" AND c["City"] = 'Seattle' ) c """); - } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual async Task FromSqlRaw_queryable_with_parameters_cache_key_includes_parameters(bool async) - { - var city = "London"; - var contactTitle = "Sales Representative"; - var sql = @"SELECT * FROM root c WHERE c[""Discriminator""] = ""Customer"" AND c[""City""] = {0} AND c[""ContactTitle""] = {1}"; + public virtual Task FromSqlRaw_queryable_with_parameters_cache_key_includes_parameters(bool async) + => Fixture.NoSyncTest( + async, async a => + { + var city = "London"; + var contactTitle = "Sales Representative"; + var sql = + @"SELECT * FROM root c WHERE c[""Discriminator""] = ""Customer"" AND c[""City""] = {0} AND c[""ContactTitle""] = {1}"; - using var context = CreateContext(); - var query = context.Set().FromSqlRaw(sql, city, contactTitle); + using var context = CreateContext(); + var query = context.Set().FromSqlRaw(sql, city, contactTitle); - var actual = async - ? await query.ToArrayAsync() - : query.ToArray(); + var actual = a + ? await query.ToArrayAsync() + : query.ToArray(); - Assert.Equal(3, actual.Length); - Assert.True(actual.All(c => c.City == "London")); - Assert.True(actual.All(c => c.ContactTitle == "Sales Representative")); + Assert.Equal(3, actual.Length); + Assert.True(actual.All(c => c.City == "London")); + Assert.True(actual.All(c => c.ContactTitle == "Sales Representative")); - city = "Madrid"; - contactTitle = "Accounting Manager"; + city = "Madrid"; + contactTitle = "Accounting Manager"; - query = context.Set().FromSqlRaw(sql, city, contactTitle); + query = context.Set().FromSqlRaw(sql, city, contactTitle); - actual = async - ? await query.ToArrayAsync() - : query.ToArray(); + actual = a + ? await query.ToArrayAsync() + : query.ToArray(); - Assert.Equal(2, actual.Length); - Assert.True(actual.All(c => c.City == "Madrid")); - Assert.True(actual.All(c => c.ContactTitle == "Accounting Manager")); + Assert.Equal(2, actual.Length); + Assert.True(actual.All(c => c.City == "Madrid")); + Assert.True(actual.All(c => c.ContactTitle == "Accounting Manager")); - AssertSql( - """ + AssertSql( + """ @p0='London' @p1='Sales Representative' @@ -522,8 +551,8 @@ SELECT c SELECT * FROM root c WHERE c["Discriminator"] = "Customer" AND c["City"] = @p0 AND c["ContactTitle"] = @p1 ) c """, - // - """ + // + """ @p0='Madrid' @p1='Accounting Manager' @@ -532,51 +561,55 @@ SELECT c SELECT * FROM root c WHERE c["Discriminator"] = "Customer" AND c["City"] = @p0 AND c["ContactTitle"] = @p1 ) c """); - } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual async Task FromSqlRaw_queryable_simple_as_no_tracking_not_composed(bool async) - { - using var context = CreateContext(); - var query = context.Set().FromSqlRaw(@"SELECT * FROM root c WHERE c[""Discriminator""] = ""Customer""") - .AsNoTracking(); + public virtual Task FromSqlRaw_queryable_simple_as_no_tracking_not_composed(bool async) + => Fixture.NoSyncTest( + async, async a => + { + using var context = CreateContext(); + var query = context.Set().FromSqlRaw(@"SELECT * FROM root c WHERE c[""Discriminator""] = ""Customer""") + .AsNoTracking(); - var actual = async - ? await query.ToArrayAsync() - : query.ToArray(); + var actual = a + ? await query.ToArrayAsync() + : query.ToArray(); - Assert.Equal(91, actual.Length); - Assert.Empty(context.ChangeTracker.Entries()); + Assert.Equal(91, actual.Length); + Assert.Empty(context.ChangeTracker.Entries()); - AssertSql( - """ + AssertSql( + """ SELECT c FROM ( SELECT * FROM root c WHERE c["Discriminator"] = "Customer" ) c """); - } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual async Task FromSqlRaw_queryable_simple_projection_composed(bool async) - { - using var context = CreateContext(); - var query = context.Set().FromSqlRaw( - @"SELECT * + public virtual Task FromSqlRaw_queryable_simple_projection_composed(bool async) + => Fixture.NoSyncTest( + async, async a => + { + using var context = CreateContext(); + var query = context.Set().FromSqlRaw( + @"SELECT * FROM root c WHERE c[""Discriminator""] = ""Product"" AND NOT c[""Discontinued""] AND ((c[""UnitsInStock""] + c[""UnitsOnOrder""]) < c[""ReorderLevel""])") - .Select(p => p.ProductName); + .Select(p => p.ProductName); - var actual = async - ? await query.ToArrayAsync() - : query.ToArray(); + var actual = a + ? await query.ToArrayAsync() + : query.ToArray(); - Assert.Equal(2, actual.Length); + Assert.Equal(2, actual.Length); - AssertSql( - """ + AssertSql( + """ SELECT c["ProductName"] FROM ( SELECT * @@ -584,92 +617,96 @@ FROM root c WHERE c["Discriminator"] = "Product" AND NOT c["Discontinued"] AND ((c["UnitsInStock"] + c["UnitsOnOrder"]) < c["ReorderLevel"]) ) c """); - } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual async Task FromSqlRaw_composed_with_nullable_predicate(bool async) - { - using var context = CreateContext(); - var query = context.Set().FromSqlRaw(@"SELECT * FROM root c WHERE c[""Discriminator""] = ""Customer""") - .Where(c => c.ContactName == c.CompanyName); + public virtual Task FromSqlRaw_composed_with_nullable_predicate(bool async) + => Fixture.NoSyncTest( + async, async a => + { + using var context = CreateContext(); + var query = context.Set().FromSqlRaw(@"SELECT * FROM root c WHERE c[""Discriminator""] = ""Customer""") + .Where(c => c.ContactName == c.CompanyName); - var actual = async - ? await query.ToArrayAsync() - : query.ToArray(); + var actual = a + ? await query.ToArrayAsync() + : query.ToArray(); - Assert.Empty(actual); + Assert.Empty(actual); - AssertSql( - """ + AssertSql( + """ SELECT c FROM ( SELECT * FROM root c WHERE c["Discriminator"] = "Customer" ) c WHERE (c["ContactName"] = c["CompanyName"]) """); - } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual async Task FromSqlRaw_does_not_parameterize_interpolated_string(bool async) - { - using var context = CreateContext(); - var propertyName = "OrderID"; - var max = 10250; - var query = context.Orders.FromSqlRaw( - $@"SELECT * FROM root c WHERE c[""Discriminator""] = ""Order"" AND c[""{propertyName}""] < {{0}}", max); + public virtual Task FromSqlRaw_does_not_parameterize_interpolated_string(bool async) + => Fixture.NoSyncTest( + async, async a => + { + using var context = CreateContext(); + var propertyName = "OrderID"; + var max = 10250; + var query = context.Orders.FromSqlRaw( + $@"SELECT * FROM root c WHERE c[""Discriminator""] = ""Order"" AND c[""{propertyName}""] < {{0}}", max); - var actual = async - ? await query.ToListAsync() - : query.ToList(); + var actual = a + ? await query.ToListAsync() + : query.ToList(); - Assert.Equal(2, actual.Count); - } + Assert.Equal(2, actual.Count); + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual async Task FromSqlRaw_queryable_simple_projection_not_composed(bool async) - { - using var context = CreateContext(); - var query = context.Set().FromSqlRaw(@"SELECT * FROM root c WHERE c[""Discriminator""] = ""Customer""") - .Select( - c => new { c.CustomerID, c.City }) - .AsNoTracking(); + public virtual Task FromSqlRaw_queryable_simple_projection_not_composed(bool async) + => Fixture.NoSyncTest( + async, async a => + { + using var context = CreateContext(); + var query = context.Set().FromSqlRaw(@"SELECT * FROM root c WHERE c[""Discriminator""] = ""Customer""") + .Select( + c => new { c.CustomerID, c.City }) + .AsNoTracking(); - var actual = async - ? await query.ToArrayAsync() - : query.ToArray(); + var actual = a + ? await query.ToArrayAsync() + : query.ToArray(); - Assert.Equal(91, actual.Length); - Assert.Empty(context.ChangeTracker.Entries()); + Assert.Equal(91, actual.Length); + Assert.Empty(context.ChangeTracker.Entries()); - AssertSql( - """ + AssertSql( + """ SELECT c["CustomerID"], c["City"] FROM ( SELECT * FROM root c WHERE c["Discriminator"] = "Customer" ) c """); - } + }); - [ConditionalTheory] - [MemberData(nameof(IsAsyncData))] - public async Task FromSqlRaw_queryable_simple_with_missing_key_and_non_tracking_throws(bool async) + [ConditionalFact] + public async Task FromSqlRaw_queryable_simple_with_missing_key_and_non_tracking_throws() { - using var context = CreateContext(); - var query = context.Set() - .FromSqlRaw(@"SELECT * FROM root c WHERE c[""Discriminator""] = ""Category""") - .AsNoTracking(); - var exception = async - ? await Assert.ThrowsAsync(() => query.ToArrayAsync()) - : Assert.Throws(() => query.ToArray()); - - Assert.Equal( - CoreStrings.InvalidKeyValue( - context.Model.FindEntityType(typeof(Customer))!.DisplayName(), - "CustomerID"), - exception.Message); + using var context = CreateContext(); + var query = context.Set() + .FromSqlRaw(@"SELECT * FROM root c WHERE c[""Discriminator""] = ""Category""") + .AsNoTracking(); + + var exception = await Assert.ThrowsAsync(() => query.ToArrayAsync()); + + Assert.Equal( + CoreStrings.InvalidKeyValue( + context.Model.FindEntityType(typeof(Customer))!.DisplayName(), + "CustomerID"), + exception.Message); } private void AssertSql(params string[] expected) diff --git a/test/EFCore.Cosmos.FunctionalTests/Query/InheritanceQueryCosmosFixture.cs b/test/EFCore.Cosmos.FunctionalTests/Query/InheritanceQueryCosmosFixture.cs index 2daeac2fa04..d1e8a045de6 100644 --- a/test/EFCore.Cosmos.FunctionalTests/Query/InheritanceQueryCosmosFixture.cs +++ b/test/EFCore.Cosmos.FunctionalTests/Query/InheritanceQueryCosmosFixture.cs @@ -18,4 +18,7 @@ public override bool UseGeneratedKeys public override bool EnableComplexTypes => false; + + public Task NoSyncTest(bool async, Func testCode) + => CosmosTestHelpers.Instance.NoSyncTest(async, testCode); } diff --git a/test/EFCore.Cosmos.FunctionalTests/Query/InheritanceQueryCosmosTest.cs b/test/EFCore.Cosmos.FunctionalTests/Query/InheritanceQueryCosmosTest.cs index 53185802eab..85da1020934 100644 --- a/test/EFCore.Cosmos.FunctionalTests/Query/InheritanceQueryCosmosTest.cs +++ b/test/EFCore.Cosmos.FunctionalTests/Query/InheritanceQueryCosmosTest.cs @@ -14,218 +14,250 @@ public InheritanceQueryCosmosTest(InheritanceQueryCosmosFixture fixture, ITestOu //TestLoggerFactory.TestOutputHelper = testOutputHelper; } - public override async Task Can_query_when_shared_column(bool async) - { - await base.Can_query_when_shared_column(async); - - AssertSql( - """ + public override Task Can_query_when_shared_column(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Can_query_when_shared_column(a); + + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = 1) OFFSET 0 LIMIT 2 """, - // - """ + // + """ SELECT c FROM root c WHERE (c["Discriminator"] = 2) OFFSET 0 LIMIT 2 """, - // - """ + // + """ SELECT c FROM root c WHERE (c["Discriminator"] = 3) OFFSET 0 LIMIT 2 """); - } + }); - public override async Task Can_query_all_types_when_shared_column(bool async) - { - await base.Can_query_all_types_when_shared_column(async); + public override Task Can_query_all_types_when_shared_column(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Can_query_all_types_when_shared_column(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE c["Discriminator"] IN (0, 1, 2, 3) """); - } + }); - public override async Task Can_use_of_type_animal(bool async) - { - await base.Can_use_of_type_animal(async); + public override Task Can_use_of_type_animal(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Can_use_of_type_animal(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE c["Discriminator"] IN ("Eagle", "Kiwi") ORDER BY c["Species"] """); - } + }); - public override async Task Can_use_is_kiwi(bool async) - { - await base.Can_use_is_kiwi(async); + public override Task Can_use_is_kiwi(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Can_use_is_kiwi(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] IN ("Eagle", "Kiwi") AND (c["Discriminator"] = "Kiwi")) """); - } + }); - public override async Task Can_use_is_kiwi_with_cast(bool async) - { - await base.Can_use_is_kiwi_with_cast(async); + public override Task Can_use_is_kiwi_with_cast(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Can_use_is_kiwi_with_cast(a); - AssertSql( - """ + AssertSql( + """ SELECT VALUE {"Value" : ((c["Discriminator"] = "Kiwi") ? c["FoundOn"] : 0)} FROM root c WHERE c["Discriminator"] IN ("Eagle", "Kiwi") """); - } + }); - public override async Task Can_use_backwards_is_animal(bool async) - { - await base.Can_use_backwards_is_animal(async); + public override Task Can_use_backwards_is_animal(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Can_use_backwards_is_animal(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Kiwi") """); - } + }); - public override async Task Can_use_is_kiwi_with_other_predicate(bool async) - { - await base.Can_use_is_kiwi_with_other_predicate(async); + public override Task Can_use_is_kiwi_with_other_predicate(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Can_use_is_kiwi_with_other_predicate(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] IN ("Eagle", "Kiwi") AND ((c["Discriminator"] = "Kiwi") AND (c["CountryId"] = 1))) """); - } + }); - public override async Task Can_use_is_kiwi_in_projection(bool async) - { - await base.Can_use_is_kiwi_in_projection(async); + public override Task Can_use_is_kiwi_in_projection(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Can_use_is_kiwi_in_projection(a); - AssertSql( - """ + AssertSql( + """ SELECT VALUE {"c" : (c["Discriminator"] = "Kiwi")} FROM root c WHERE c["Discriminator"] IN ("Eagle", "Kiwi") """); - } + }); - public override async Task Can_use_of_type_bird(bool async) - { - await base.Can_use_of_type_bird(async); + public override Task Can_use_of_type_bird(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Can_use_of_type_bird(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] IN ("Eagle", "Kiwi") AND c["Discriminator"] IN ("Eagle", "Kiwi")) ORDER BY c["Species"] """); - } + }); - public override async Task Can_use_of_type_bird_predicate(bool async) - { - await base.Can_use_of_type_bird_predicate(async); + public override Task Can_use_of_type_bird_predicate(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Can_use_of_type_bird_predicate(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] IN ("Eagle", "Kiwi") AND (c["CountryId"] = 1)) AND c["Discriminator"] IN ("Eagle", "Kiwi")) ORDER BY c["Species"] """); - } + }); - public override async Task Can_use_of_type_bird_with_projection(bool async) - { - await base.Can_use_of_type_bird_with_projection(async); + public override Task Can_use_of_type_bird_with_projection(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Can_use_of_type_bird_with_projection(a); - AssertSql( - """ + AssertSql( + """ SELECT c["EagleId"] FROM root c WHERE (c["Discriminator"] IN ("Eagle", "Kiwi") AND c["Discriminator"] IN ("Eagle", "Kiwi")) """); - } + }); - public override async Task Can_use_of_type_bird_first(bool async) - { - await base.Can_use_of_type_bird_first(async); + public override Task Can_use_of_type_bird_first(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Can_use_of_type_bird_first(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] IN ("Eagle", "Kiwi") AND c["Discriminator"] IN ("Eagle", "Kiwi")) ORDER BY c["Species"] OFFSET 0 LIMIT 1 """); - } + }); - public override async Task Can_use_of_type_kiwi(bool async) - { - await base.Can_use_of_type_kiwi(async); + public override Task Can_use_of_type_kiwi(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Can_use_of_type_kiwi(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] IN ("Eagle", "Kiwi") AND (c["Discriminator"] = "Kiwi")) """); - } + }); - public override async Task Can_use_backwards_of_type_animal(bool async) - { - await base.Can_use_backwards_of_type_animal(async); + public override Task Can_use_backwards_of_type_animal(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Can_use_backwards_of_type_animal(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Kiwi") """); - } + }); - public override async Task Can_use_of_type_rose(bool async) - { - await base.Can_use_of_type_rose(async); + public override Task Can_use_of_type_rose(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Can_use_of_type_rose(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] IN ("Daisy", "Rose") AND (c["Discriminator"] = "Rose")) """); - } + }); - public override async Task Can_query_all_animals(bool async) - { - await base.Can_query_all_animals(async); + public override Task Can_query_all_animals(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Can_query_all_animals(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE c["Discriminator"] IN ("Eagle", "Kiwi") ORDER BY c["Species"] """); - } + }); [ConditionalTheory(Skip = "Issue#17246 Views are not supported")] public override async Task Can_query_all_animal_views(bool async) @@ -235,70 +267,80 @@ public override async Task Can_query_all_animal_views(bool async) AssertSql(" "); } - public override async Task Can_query_all_plants(bool async) - { - await base.Can_query_all_plants(async); + public override Task Can_query_all_plants(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Can_query_all_plants(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE c["Discriminator"] IN ("Daisy", "Rose") ORDER BY c["Species"] """); - } + }); - public override async Task Can_filter_all_animals(bool async) - { - await base.Can_filter_all_animals(async); + public override Task Can_filter_all_animals(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Can_filter_all_animals(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] IN ("Eagle", "Kiwi") AND (c["Name"] = "Great spotted kiwi")) ORDER BY c["Species"] """); - } + }); - public override async Task Can_query_all_birds(bool async) - { - await base.Can_query_all_birds(async); + public override Task Can_query_all_birds(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Can_query_all_birds(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE c["Discriminator"] IN ("Eagle", "Kiwi") ORDER BY c["Species"] """); - } + }); - public override async Task Can_query_just_kiwis(bool async) - { - await base.Can_query_just_kiwis(async); + public override Task Can_query_just_kiwis(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Can_query_just_kiwis(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Kiwi") OFFSET 0 LIMIT 2 """); - } + }); - public override async Task Can_query_just_roses(bool async) - { - await base.Can_query_just_roses(async); + public override Task Can_query_just_roses(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Can_query_just_roses(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Rose") OFFSET 0 LIMIT 2 """); - } + }); [ConditionalTheory(Skip = "Issue#17246 Non-embedded Include")] public override async Task Can_include_animals(bool async) @@ -316,82 +358,94 @@ public override async Task Can_include_prey(bool async) AssertSql(" "); } - public override async Task Can_use_of_type_kiwi_where_south_on_derived_property(bool async) - { - await base.Can_use_of_type_kiwi_where_south_on_derived_property(async); + public override Task Can_use_of_type_kiwi_where_south_on_derived_property(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Can_use_of_type_kiwi_where_south_on_derived_property(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] IN ("Eagle", "Kiwi") AND (c["Discriminator"] = "Kiwi")) AND (c["FoundOn"] = 1)) """); - } + }); - public override async Task Can_use_of_type_kiwi_where_north_on_derived_property(bool async) - { - await base.Can_use_of_type_kiwi_where_north_on_derived_property(async); + public override Task Can_use_of_type_kiwi_where_north_on_derived_property(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Can_use_of_type_kiwi_where_north_on_derived_property(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] IN ("Eagle", "Kiwi") AND (c["Discriminator"] = "Kiwi")) AND (c["FoundOn"] = 0)) """); - } + }); - public override async Task Discriminator_used_when_projection_over_derived_type(bool async) - { - await base.Discriminator_used_when_projection_over_derived_type(async); + public override Task Discriminator_used_when_projection_over_derived_type(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Discriminator_used_when_projection_over_derived_type(a); - AssertSql( - """ + AssertSql( + """ SELECT c["FoundOn"] FROM root c WHERE (c["Discriminator"] = "Kiwi") """); - } + }); - public override async Task Discriminator_used_when_projection_over_derived_type2(bool async) - { - await base.Discriminator_used_when_projection_over_derived_type2(async); + public override Task Discriminator_used_when_projection_over_derived_type2(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Discriminator_used_when_projection_over_derived_type2(a); - AssertSql( - """ + AssertSql( + """ SELECT c["IsFlightless"], c["Discriminator"] FROM root c WHERE c["Discriminator"] IN ("Eagle", "Kiwi") """); - } + }); - public override async Task Discriminator_with_cast_in_shadow_property(bool async) - { - await base.Discriminator_with_cast_in_shadow_property(async); + public override Task Discriminator_with_cast_in_shadow_property(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Discriminator_with_cast_in_shadow_property(a); - AssertSql( - """ + AssertSql( + """ SELECT VALUE {"Predator" : c["Name"]} FROM root c WHERE (c["Discriminator"] IN ("Eagle", "Kiwi") AND ("Kiwi" = c["Discriminator"])) """); - } + }); - public override async Task Discriminator_used_when_projection_over_of_type(bool async) - { - await base.Discriminator_used_when_projection_over_of_type(async); + public override Task Discriminator_used_when_projection_over_of_type(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Discriminator_used_when_projection_over_of_type(a); - AssertSql( - """ + AssertSql( + """ SELECT c["FoundOn"] FROM root c WHERE (c["Discriminator"] IN ("Eagle", "Kiwi") AND (c["Discriminator"] = "Kiwi")) """); - } + }); [ConditionalFact(Skip = "Issue#17246 Transations not supported")] - public override void Can_insert_update_delete() + public override async Task Can_insert_update_delete() { - base.Can_insert_update_delete(); + await base.Can_insert_update_delete(); AssertSql(" "); } @@ -417,12 +471,14 @@ public override async Task OfType_Union_OfType(bool async) AssertSql(" "); } - public override async Task Subquery_OfType(bool async) - { - await base.Subquery_OfType(async); + public override Task Subquery_OfType(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Subquery_OfType(a); - AssertSql( - """ + AssertSql( + """ @__p_0='5' SELECT DISTINCT c @@ -431,7 +487,7 @@ FROM root c ORDER BY c["Species"] OFFSET 0 LIMIT @__p_0 """); - } + }); public override async Task Union_entity_equality(bool async) { @@ -440,9 +496,9 @@ public override async Task Union_entity_equality(bool async) AssertSql(" "); } - public override void Setting_foreign_key_to_a_different_type_throws() + public override async Task Setting_foreign_key_to_a_different_type_throws() { - base.Setting_foreign_key_to_a_different_type_throws(); + await base.Setting_foreign_key_to_a_different_type_throws(); AssertSql( """ @@ -453,21 +509,23 @@ OFFSET 0 LIMIT 2 """); } - public override async Task Byte_enum_value_constant_used_in_projection(bool async) - { - await base.Byte_enum_value_constant_used_in_projection(async); + public override Task Byte_enum_value_constant_used_in_projection(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Byte_enum_value_constant_used_in_projection(a); - AssertSql( - """ + AssertSql( + """ SELECT VALUE {"c" : (c["IsFlightless"] ? 0 : 1)} FROM root c WHERE (c["Discriminator"] = "Kiwi") """); - } + }); - public override void Member_access_on_intermediate_type_works() + public override async Task Member_access_on_intermediate_type_works() { - base.Member_access_on_intermediate_type_works(); + await base.Member_access_on_intermediate_type_works(); AssertSql( """ @@ -486,101 +544,145 @@ public override async Task Is_operator_on_result_of_FirstOrDefault(bool async) AssertSql(" "); } - public override async Task Selecting_only_base_properties_on_base_type(bool async) - { - await base.Selecting_only_base_properties_on_base_type(async); + public override Task Selecting_only_base_properties_on_base_type(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Selecting_only_base_properties_on_base_type(a); - AssertSql( - """ + AssertSql( + """ SELECT c["Name"] FROM root c WHERE c["Discriminator"] IN ("Eagle", "Kiwi") """); - } + }); - public override async Task Selecting_only_base_properties_on_derived_type(bool async) - { - await base.Selecting_only_base_properties_on_derived_type(async); + public override Task Selecting_only_base_properties_on_derived_type(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Selecting_only_base_properties_on_derived_type(a); - AssertSql( - """ + AssertSql( + """ SELECT c["Name"] FROM root c WHERE c["Discriminator"] IN ("Eagle", "Kiwi") """); - } + }); - public override async Task GetType_in_hierarchy_in_abstract_base_type(bool async) - { - await base.GetType_in_hierarchy_in_abstract_base_type(async); + public override Task GetType_in_hierarchy_in_abstract_base_type(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.GetType_in_hierarchy_in_abstract_base_type(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] IN ("Eagle", "Kiwi") AND false) """); - } + }); - public override async Task GetType_in_hierarchy_in_intermediate_type(bool async) - { - await base.GetType_in_hierarchy_in_intermediate_type(async); + public override Task GetType_in_hierarchy_in_intermediate_type(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.GetType_in_hierarchy_in_intermediate_type(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] IN ("Eagle", "Kiwi") AND false) """); - } + }); - public override async Task GetType_in_hierarchy_in_leaf_type_with_sibling(bool async) - { - await base.GetType_in_hierarchy_in_leaf_type_with_sibling(async); + public override Task GetType_in_hierarchy_in_leaf_type_with_sibling(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.GetType_in_hierarchy_in_leaf_type_with_sibling(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] IN ("Eagle", "Kiwi") AND (c["Discriminator"] = "Eagle")) """); - } + }); - public override async Task GetType_in_hierarchy_in_leaf_type_with_sibling2(bool async) - { - await base.GetType_in_hierarchy_in_leaf_type_with_sibling2(async); + public override Task GetType_in_hierarchy_in_leaf_type_with_sibling2(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.GetType_in_hierarchy_in_leaf_type_with_sibling2(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] IN ("Eagle", "Kiwi") AND (c["Discriminator"] = "Kiwi")) """); - } + }); - public override async Task GetType_in_hierarchy_in_leaf_type_with_sibling2_reverse(bool async) - { - await base.GetType_in_hierarchy_in_leaf_type_with_sibling2_reverse(async); + public override Task GetType_in_hierarchy_in_leaf_type_with_sibling2_reverse(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.GetType_in_hierarchy_in_leaf_type_with_sibling2_reverse(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] IN ("Eagle", "Kiwi") AND (c["Discriminator"] = "Kiwi")) """); - } + }); - public override async Task GetType_in_hierarchy_in_leaf_type_with_sibling2_not_equal(bool async) - { - await base.GetType_in_hierarchy_in_leaf_type_with_sibling2_not_equal(async); + public override Task GetType_in_hierarchy_in_leaf_type_with_sibling2_not_equal(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.GetType_in_hierarchy_in_leaf_type_with_sibling2_not_equal(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] IN ("Eagle", "Kiwi") AND (c["Discriminator"] != "Kiwi")) """); - } + }); + + public override Task Using_is_operator_on_multiple_type_with_no_result(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Using_is_operator_on_multiple_type_with_no_result(a); + + AssertSql( + """ +SELECT c +FROM root c +WHERE ((c["Discriminator"] IN ("Eagle", "Kiwi") AND (c["Discriminator"] = "Kiwi")) AND (c["Discriminator"] = "Eagle")) +"""); + }); + + public override Task Using_is_operator_with_of_type_on_multiple_type_with_no_result(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Using_is_operator_with_of_type_on_multiple_type_with_no_result(a); + + AssertSql( + """ +SELECT c +FROM root c +WHERE ((c["Discriminator"] IN ("Eagle", "Kiwi") AND (c["Discriminator"] = "Kiwi")) AND (c["Discriminator"] = "Eagle")) +"""); + }); protected override bool EnforcesFkConstraints => false; diff --git a/test/EFCore.Cosmos.FunctionalTests/Query/NorthwindAggregateOperatorsQueryCosmosTest.cs b/test/EFCore.Cosmos.FunctionalTests/Query/NorthwindAggregateOperatorsQueryCosmosTest.cs index 55846960281..6856cc4ae9d 100644 --- a/test/EFCore.Cosmos.FunctionalTests/Query/NorthwindAggregateOperatorsQueryCosmosTest.cs +++ b/test/EFCore.Cosmos.FunctionalTests/Query/NorthwindAggregateOperatorsQueryCosmosTest.cs @@ -26,375 +26,440 @@ public NorthwindAggregateOperatorsQueryCosmosTest( public virtual void Check_all_tests_overridden() => TestHelpers.AssertAllMethodsOverridden(GetType()); - public override async Task Average_over_default_returns_default(bool async) - { - await base.Average_over_default_returns_default(async); - - AssertSql( - """ + public override Task Average_over_default_returns_default(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Average_over_default_returns_default(a); + + AssertSql( + """ SELECT AVG((c["OrderID"] - 10248)) AS c FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderID"] = 10248)) """); - } + }); - public override async Task Contains_over_keyless_entity_throws(bool async) - { - // Aggregates. Issue #16146. - await AssertTranslationFailed(() => base.Contains_over_keyless_entity_throws(async)); + public override Task Contains_over_keyless_entity_throws(bool async) + => Fixture.NoSyncTest( + async, async a => + { + // The `First()` query is always executed synchronously. The outer query does not translate. + if (!a) + { + // Aggregates. Issue #16146. + await base.Contains_over_keyless_entity_throws(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Customer") OFFSET 0 LIMIT 1 """); - } + } + }); - public override async Task Contains_with_local_non_primitive_list_closure_mix(bool async) - { - await base.Contains_with_local_non_primitive_list_closure_mix(async); + public override Task Contains_with_local_non_primitive_list_closure_mix(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Contains_with_local_non_primitive_list_closure_mix(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND c["CustomerID"] IN ("ABCDE", "ALFKI")) """); - } + }); - public override async Task Contains_with_local_non_primitive_list_inline_closure_mix(bool async) - { - await base.Contains_with_local_non_primitive_list_inline_closure_mix(async); + public override Task Contains_with_local_non_primitive_list_inline_closure_mix(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Contains_with_local_non_primitive_list_inline_closure_mix(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND c["CustomerID"] IN ("ABCDE", "ALFKI")) """, - // - """ + // + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND c["CustomerID"] IN ("ABCDE", "ANATR")) """); - } + }); - public override async Task Count_on_projection_with_client_eval(bool async) - { - await base.Count_on_projection_with_client_eval(async); + public override Task Count_on_projection_with_client_eval(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Count_on_projection_with_client_eval(a); - AssertSql( - """ + AssertSql( + """ SELECT COUNT(1) AS c FROM root c WHERE (c["Discriminator"] = "Order") """, - // - """ + // + """ SELECT COUNT(1) AS c FROM root c WHERE (c["Discriminator"] = "Order") """, - // - """ + // + """ SELECT COUNT(1) AS c FROM root c WHERE (c["Discriminator"] = "Order") """); - } + }); - public override async Task First(bool async) - { - await base.First(async); + public override Task First(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.First(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Customer") ORDER BY c["ContactName"] OFFSET 0 LIMIT 1 """); - } + }); - public override async Task Max_over_default_returns_default(bool async) - { - await base.Max_over_default_returns_default(async); + public override Task Max_over_default_returns_default(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Max_over_default_returns_default(a); - AssertSql( - """ + AssertSql( + """ SELECT MAX((c["OrderID"] - 10248)) AS c FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderID"] = 10248)) """); - } - - public override async Task Min_over_default_returns_default(bool async) + }); - { - await base.Min_over_default_returns_default(async); + public override Task Min_over_default_returns_default(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Min_over_default_returns_default(a); - AssertSql( - """ + AssertSql( + """ SELECT MIN((c["OrderID"] - 10248)) AS c FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderID"] = 10248)) """); - } + }); - public override async Task Sum_over_empty_returns_zero(bool async) - { - await base.Sum_over_empty_returns_zero(async); + public override Task Sum_over_empty_returns_zero(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Sum_over_empty_returns_zero(a); - AssertSql( - """ + AssertSql( + """ SELECT SUM(c["OrderID"]) AS c FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderID"] = 42)) """); - } + }); - public override async Task First_Predicate(bool async) - { - await base.First_Predicate(async); + public override Task First_Predicate(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.First_Predicate(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["City"] = "London")) ORDER BY c["ContactName"] OFFSET 0 LIMIT 1 """); - } + }); public override async Task Single_Throws(bool async) { - await base.Single_Throws(async); + // Always throws for sync. + if (async) + { + await base.Single_Throws(async); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Customer") OFFSET 0 LIMIT 2 """); + } } - public override async Task Where_First(bool async) - { - await base.Where_First(async); + public override Task Where_First(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_First(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["City"] = "London")) ORDER BY c["ContactName"] OFFSET 0 LIMIT 1 """); - } + }); - public override async Task Where_Single(bool async) - { - await base.Where_Single(async); + public override Task Where_Single(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_Single(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = "ALFKI")) OFFSET 0 LIMIT 2 """); - } + }); - public override async Task FirstOrDefault(bool async) - { - await base.FirstOrDefault(async); + public override Task FirstOrDefault(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.FirstOrDefault(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Customer") ORDER BY c["ContactName"] OFFSET 0 LIMIT 1 """); - } + }); - public override async Task Array_cast_to_IEnumerable_Contains_with_constant(bool async) - { - await base.Array_cast_to_IEnumerable_Contains_with_constant(async); + public override Task Array_cast_to_IEnumerable_Contains_with_constant(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Array_cast_to_IEnumerable_Contains_with_constant(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND c["CustomerID"] IN ("ALFKI", "WRONG")) """); - } + }); - public override async Task FirstOrDefault_Predicate(bool async) - { - await base.FirstOrDefault_Predicate(async); + public override Task FirstOrDefault_Predicate(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.FirstOrDefault_Predicate(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["City"] = "London")) ORDER BY c["ContactName"] OFFSET 0 LIMIT 1 """); - } + }); - public override async Task SingleOrDefault_Predicate(bool async) - { - await base.SingleOrDefault_Predicate(async); + public override Task SingleOrDefault_Predicate(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.SingleOrDefault_Predicate(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = "ALFKI")) OFFSET 0 LIMIT 2 """); - } + }); public override async Task SingleOrDefault_Throws(bool async) { - await base.SingleOrDefault_Throws(async); + // Always throws for sync. + if (async) + { + await base.SingleOrDefault_Throws(async); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Customer") OFFSET 0 LIMIT 2 """); + } } - public override async Task Where_FirstOrDefault(bool async) - { - await base.Where_FirstOrDefault(async); + public override Task Where_FirstOrDefault(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_FirstOrDefault(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["City"] = "London")) ORDER BY c["ContactName"] OFFSET 0 LIMIT 1 """); - } + }); - public override async Task Where_SingleOrDefault(bool async) - { - await base.Where_SingleOrDefault(async); + public override Task Where_SingleOrDefault(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_SingleOrDefault(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = "ALFKI")) OFFSET 0 LIMIT 2 """); - } + }); public override async Task Select_All(bool async) { - // Contains over subquery. Issue #17246. - await AssertTranslationFailed(() => base.Select_All(async)); + // Always throws sync-not-support for sync. + if (async) + { + // Contains over subquery. Issue #17246. + await AssertTranslationFailed(() => base.Select_All(async)); - AssertSql(); + AssertSql(); + } } - public override async Task Sum_with_no_arg(bool async) - { - await base.Sum_with_no_arg(async); + public override Task Sum_with_no_arg(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Sum_with_no_arg(a); - AssertSql( - """ + AssertSql( + """ SELECT SUM(c["OrderID"]) AS c FROM root c WHERE (c["Discriminator"] = "Order") """); - } + }); - public override async Task Sum_with_no_data_cast_to_nullable(bool async) - { - await base.Sum_with_no_data_cast_to_nullable(async); + public override Task Sum_with_no_data_cast_to_nullable(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Sum_with_no_data_cast_to_nullable(a); - AssertSql( - """ + AssertSql( + """ SELECT SUM(c["OrderID"]) AS c FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderID"] < 0)) """); - } + }); - public override async Task Sum_with_binary_expression(bool async) - { - await base.Sum_with_binary_expression(async); + public override Task Sum_with_binary_expression(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Sum_with_binary_expression(a); - AssertSql( - """ + AssertSql( + """ SELECT SUM((c["OrderID"] * 2)) AS c FROM root c WHERE (c["Discriminator"] = "Order") """); - } + }); - public override async Task Sum_with_no_arg_empty(bool async) - { - await base.Sum_with_no_arg_empty(async); + public override Task Sum_with_no_arg_empty(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Sum_with_no_arg_empty(a); - AssertSql( - """ + AssertSql( + """ SELECT SUM(c["OrderID"]) AS c FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderID"] = 42)) """); - } + }); - public override async Task Sum_with_no_data_nullable(bool async) - { - await base.Sum_with_no_data_nullable(async); + public override Task Sum_with_no_data_nullable(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Sum_with_no_data_nullable(a); - AssertSql( - """ + AssertSql( + """ SELECT SUM(c["SupplierID"]) AS c FROM root c WHERE (c["Discriminator"] = "Product") """); - } + }); - public override async Task Sum_with_arg(bool async) - { - await base.Sum_with_arg(async); + public override Task Sum_with_arg(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Sum_with_arg(a); - AssertSql( - """ + AssertSql( + """ SELECT SUM(c["OrderID"]) AS c FROM root c WHERE (c["Discriminator"] = "Order") """); - } + }); - public override async Task Sum_with_arg_expression(bool async) - { - await base.Sum_with_arg_expression(async); + public override Task Sum_with_arg_expression(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Sum_with_arg_expression(a); - AssertSql( - """ + AssertSql( + """ SELECT SUM((c["OrderID"] + c["OrderID"])) AS c FROM root c WHERE (c["Discriminator"] = "Order") """); - } + }); public override async Task Sum_with_division_on_decimal(bool async) { @@ -413,17 +478,19 @@ await Assert.ThrowsAsync( AssertSql(); } - public override async Task Sum_with_coalesce(bool async) - { - await base.Sum_with_coalesce(async); + public override Task Sum_with_coalesce(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Sum_with_coalesce(a); - AssertSql( - """ + AssertSql( + """ SELECT SUM(((c["UnitPrice"] != null) ? c["UnitPrice"] : 0.0)) AS c FROM root c WHERE ((c["Discriminator"] = "Product") AND (c["ProductID"] < 40)) """); - } + }); public override async Task Sum_over_subquery_is_client_eval(bool async) { @@ -449,17 +516,19 @@ public override async Task Sum_over_min_subquery_is_client_eval(bool async) AssertSql(); } - public override async Task Sum_on_float_column(bool async) - { - await base.Sum_on_float_column(async); + public override Task Sum_on_float_column(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Sum_on_float_column(a); - AssertSql( - """ + AssertSql( + """ SELECT SUM(c["Discount"]) AS c FROM root c WHERE ((c["Discriminator"] = "OrderDetail") AND (c["ProductID"] = 1)) """); - } + }); public override async Task Sum_on_float_column_in_subquery(bool async) { @@ -471,62 +540,78 @@ public override async Task Sum_on_float_column_in_subquery(bool async) public override async Task Average_no_data(bool async) { - await base.Average_no_data(async); + // Sync always throws before getting to exception being tested. + if (async) + { + await base.Average_no_data(async); - AssertSql( - """ + AssertSql( + """ SELECT AVG(c["OrderID"]) AS c FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderID"] = -1)) """); + } } - public override async Task Average_no_data_nullable(bool async) - { - await base.Average_no_data_nullable(async); + public override Task Average_no_data_nullable(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Average_no_data_nullable(a); - AssertSql( - """ + AssertSql( + """ SELECT AVG(c["SupplierID"]) AS c FROM root c WHERE ((c["Discriminator"] = "Product") AND (c["SupplierID"] = -1)) """); - } + }); - public override async Task Average_no_data_cast_to_nullable(bool async) - { - await base.Average_no_data_cast_to_nullable(async); + public override Task Average_no_data_cast_to_nullable(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Average_no_data_cast_to_nullable(a); - AssertSql( - """ + AssertSql( + """ SELECT AVG(c["OrderID"]) AS c FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderID"] = -1)) """); - } + }); public override async Task Min_no_data(bool async) { - await base.Min_no_data(async); + // Always throws for sync. + if (async) + { + await base.Min_no_data(async); - AssertSql( - """ + AssertSql( + """ SELECT MIN(c["OrderID"]) AS c FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderID"] = -1)) """); + } } public override async Task Max_no_data(bool async) { - await base.Max_no_data(async); + // Always throws for sync. + if (async) + { + await base.Max_no_data(async); - AssertSql( - """ + AssertSql( + """ SELECT MAX(c["OrderID"]) AS c FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderID"] = -1)) """); + } } public override async Task Average_no_data_subquery(bool async) @@ -545,29 +630,33 @@ public override async Task Max_no_data_subquery(bool async) AssertSql(); } - public override async Task Max_no_data_nullable(bool async) - { - await base.Max_no_data_nullable(async); + public override Task Max_no_data_nullable(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Max_no_data_nullable(a); - AssertSql( - """ + AssertSql( + """ SELECT MAX(c["SupplierID"]) AS c FROM root c WHERE ((c["Discriminator"] = "Product") AND (c["SupplierID"] = -1)) """); - } + }); - public override async Task Max_no_data_cast_to_nullable(bool async) - { - await base.Max_no_data_cast_to_nullable(async); + public override Task Max_no_data_cast_to_nullable(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Max_no_data_cast_to_nullable(a); - AssertSql( - """ + AssertSql( + """ SELECT MAX(c["OrderID"]) AS c FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderID"] = -1)) """); - } + }); public override async Task Min_no_data_subquery(bool async) { @@ -579,53 +668,65 @@ public override async Task Min_no_data_subquery(bool async) public override async Task Average_with_no_arg(bool async) { - // Average truncates. Issue #26378. - await Assert.ThrowsAsync(async () => await base.Average_with_no_arg(async)); + // Always throws for sync. + if (async) + { + // Average truncates. Issue #26378. + await Assert.ThrowsAsync(async () => await base.Average_with_no_arg(async)); - AssertSql( - """ + AssertSql( + """ SELECT AVG(c["OrderID"]) AS c FROM root c WHERE (c["Discriminator"] = "Order") """); + } } - public override async Task Average_with_binary_expression(bool async) - { - await base.Average_with_binary_expression(async); + public override Task Average_with_binary_expression(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Average_with_binary_expression(a); - AssertSql( - """ + AssertSql( + """ SELECT AVG((c["OrderID"] * 2)) AS c FROM root c WHERE (c["Discriminator"] = "Order") """); - } + }); public override async Task Average_with_arg(bool async) { - // Average truncates. Issue #26378. - await Assert.ThrowsAsync(async () => await base.Average_with_arg(async)); + // Always throws for sync. + if (async) + { + // Average truncates. Issue #26378. + await Assert.ThrowsAsync(async () => await base.Average_with_arg(async)); - AssertSql( - """ + AssertSql( + """ SELECT AVG(c["OrderID"]) AS c FROM root c WHERE (c["Discriminator"] = "Order") """); + } } - public override async Task Average_with_arg_expression(bool async) - { - await base.Average_with_arg_expression(async); + public override Task Average_with_arg_expression(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Average_with_arg_expression(a); - AssertSql( - """ + AssertSql( + """ SELECT AVG((c["OrderID"] + c["OrderID"])) AS c FROM root c WHERE (c["Discriminator"] = "Order") """); - } + }); public override async Task Average_with_division_on_decimal(bool async) { @@ -644,17 +745,19 @@ await Assert.ThrowsAsync( AssertSql(); } - public override async Task Average_with_coalesce(bool async) - { - await base.Average_with_coalesce(async); + public override Task Average_with_coalesce(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Average_with_coalesce(a); - AssertSql( - """ + AssertSql( + """ SELECT AVG(((c["UnitPrice"] != null) ? c["UnitPrice"] : 0.0)) AS c FROM root c WHERE ((c["Discriminator"] = "Product") AND (c["ProductID"] < 40)) """); - } + }); public override async Task Average_over_subquery_is_client_eval(bool async) { @@ -680,17 +783,19 @@ public override async Task Average_over_max_subquery_is_client_eval(bool async) AssertSql(); } - public override async Task Average_on_float_column(bool async) - { - await base.Average_on_float_column(async); + public override Task Average_on_float_column(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Average_on_float_column(a); - AssertSql( - """ + AssertSql( + """ SELECT AVG(c["Discount"]) AS c FROM root c WHERE ((c["Discriminator"] = "OrderDetail") AND (c["ProductID"] = 1)) """); - } + }); public override async Task Average_on_float_column_in_subquery(bool async) { @@ -708,65 +813,75 @@ public override async Task Average_on_float_column_in_subquery_with_cast(bool as AssertSql(); } - public override async Task Min_with_no_arg(bool async) - { - await base.Min_with_no_arg(async); + public override Task Min_with_no_arg(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Min_with_no_arg(a); - AssertSql( - """ + AssertSql( + """ SELECT MIN(c["OrderID"]) AS c FROM root c WHERE (c["Discriminator"] = "Order") """); - } + }); - public override async Task Min_with_arg(bool async) - { - await base.Min_with_arg(async); + public override Task Min_with_arg(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Min_with_arg(a); - AssertSql( - """ + AssertSql( + """ SELECT MIN(c["OrderID"]) AS c FROM root c WHERE (c["Discriminator"] = "Order") """); - } + }); - public override async Task Min_no_data_nullable(bool async) - { - await base.Min_no_data_nullable(async); + public override Task Min_no_data_nullable(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Min_no_data_nullable(a); - AssertSql( - """ + AssertSql( + """ SELECT MIN(c["SupplierID"]) AS c FROM root c WHERE ((c["Discriminator"] = "Product") AND (c["SupplierID"] = -1)) """); - } + }); - public override async Task Min_no_data_cast_to_nullable(bool async) - { - await base.Min_no_data_cast_to_nullable(async); + public override Task Min_no_data_cast_to_nullable(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Min_no_data_cast_to_nullable(a); - AssertSql( - """ + AssertSql( + """ SELECT MIN(c["OrderID"]) AS c FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderID"] = -1)) """); - } + }); - public override async Task Min_with_coalesce(bool async) - { - await base.Min_with_coalesce(async); + public override Task Min_with_coalesce(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Min_with_coalesce(a); - AssertSql( - """ + AssertSql( + """ SELECT MIN(((c["UnitPrice"] != null) ? c["UnitPrice"] : 0.0)) AS c FROM root c WHERE ((c["Discriminator"] = "Product") AND (c["ProductID"] < 40)) """); - } + }); public override async Task Min_over_subquery_is_client_eval(bool async) { @@ -792,41 +907,47 @@ public override async Task Min_over_max_subquery_is_client_eval(bool async) AssertSql(); } - public override async Task Max_with_no_arg(bool async) - { - await base.Max_with_no_arg(async); + public override Task Max_with_no_arg(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Max_with_no_arg(a); - AssertSql( - """ + AssertSql( + """ SELECT MAX(c["OrderID"]) AS c FROM root c WHERE (c["Discriminator"] = "Order") """); - } + }); - public override async Task Max_with_arg(bool async) - { - await base.Max_with_arg(async); + public override Task Max_with_arg(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Max_with_arg(a); - AssertSql( - """ + AssertSql( + """ SELECT MAX(c["OrderID"]) AS c FROM root c WHERE (c["Discriminator"] = "Order") """); - } + }); - public override async Task Max_with_coalesce(bool async) - { - await base.Max_with_coalesce(async); + public override Task Max_with_coalesce(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Max_with_coalesce(a); - AssertSql( - """ + AssertSql( + """ SELECT MAX(((c["UnitPrice"] != null) ? c["UnitPrice"] : 0.0)) AS c FROM root c WHERE ((c["Discriminator"] = "Product") AND (c["ProductID"] < 40)) """); - } + }); public override async Task Max_over_subquery_is_client_eval(bool async) { @@ -852,89 +973,103 @@ public override async Task Max_over_sum_subquery_is_client_eval(bool async) AssertSql(); } - public override async Task Count_with_no_predicate(bool async) - { - await base.Count_with_no_predicate(async); + public override Task Count_with_no_predicate(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Count_with_no_predicate(a); - AssertSql( - """ + AssertSql( + """ SELECT COUNT(1) AS c FROM root c WHERE (c["Discriminator"] = "Order") """); - } + }); - public override async Task Count_with_predicate(bool async) - { - await base.Count_with_predicate(async); + public override Task Count_with_predicate(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Count_with_predicate(a); - AssertSql( - """ + AssertSql( + """ SELECT COUNT(1) AS c FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["CustomerID"] = "ALFKI")) """); - } + }); - public override async Task Count_with_order_by(bool async) - { - await base.Count_with_order_by(async); + public override Task Count_with_order_by(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Count_with_order_by(a); - AssertSql( - """ + AssertSql( + """ SELECT COUNT(1) AS c FROM root c WHERE (c["Discriminator"] = "Order") """); - } + }); - public override async Task Where_OrderBy_Count(bool async) - { - await base.Where_OrderBy_Count(async); + public override Task Where_OrderBy_Count(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_OrderBy_Count(a); - AssertSql( - """ + AssertSql( + """ SELECT COUNT(1) AS c FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["CustomerID"] = "ALFKI")) """); - } + }); - public override async Task OrderBy_Where_Count(bool async) - { - await base.OrderBy_Where_Count(async); + public override Task OrderBy_Where_Count(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.OrderBy_Where_Count(a); - AssertSql( - """ + AssertSql( + """ SELECT COUNT(1) AS c FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["CustomerID"] = "ALFKI")) """); - } + }); - public override async Task OrderBy_Count_with_predicate(bool async) - { - await base.OrderBy_Count_with_predicate(async); + public override Task OrderBy_Count_with_predicate(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.OrderBy_Count_with_predicate(a); - AssertSql( - """ + AssertSql( + """ SELECT COUNT(1) AS c FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["CustomerID"] = "ALFKI")) """); - } + }); - public override async Task OrderBy_Where_Count_with_predicate(bool async) - { - await base.OrderBy_Where_Count_with_predicate(async); + public override Task OrderBy_Where_Count_with_predicate(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.OrderBy_Where_Count_with_predicate(a); - AssertSql( - """ + AssertSql( + """ SELECT COUNT(1) AS c FROM root c WHERE (((c["Discriminator"] = "Order") AND (c["OrderID"] > 10)) AND (c["CustomerID"] != "ALFKI")) """); - } + }); public override async Task Where_OrderBy_Count_client_eval(bool async) { @@ -1003,11 +1138,14 @@ public override async Task Count_after_client_projection(bool async) public override async Task OrderBy_client_Take(bool async) { - await Assert.ThrowsAsync( - async () => await base.OrderBy_client_Take(async)); + // Always throws for sync. + if (async) + { + await Assert.ThrowsAsync( + async () => await base.OrderBy_client_Take(async)); - AssertSql( - """ + AssertSql( + """ @__p_0='10' SELECT c @@ -1016,45 +1154,52 @@ FROM root c ORDER BY 42 OFFSET 0 LIMIT @__p_0 """); + } } - public override async Task Distinct(bool async) - { - await base.Distinct(async); + public override Task Distinct(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Distinct(a); - AssertSql( - """ + AssertSql( + """ SELECT DISTINCT c FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); [ConditionalTheory(Skip = "Fails on CI #27688")] - public override async Task Distinct_Scalar(bool async) - { - await base.Distinct_Scalar(async); - - AssertSql( - """ + public override Task Distinct_Scalar(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Distinct_Scalar(a); + + AssertSql( + """ SELECT DISTINCT c[""City""] FROM root c WHERE (c[""Discriminator""] = ""Customer"") """); - } + }); - public override async Task OrderBy_Distinct(bool async) - { - await base.OrderBy_Distinct(async); + public override Task OrderBy_Distinct(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.OrderBy_Distinct(a); - AssertSql( - """ + AssertSql( + """ SELECT DISTINCT c["City"] FROM root c WHERE (c["Discriminator"] = "Customer") ORDER BY c["CustomerID"] """); - } + }); public override async Task Distinct_OrderBy(bool async) // Subquery pushdown. Issue #16156. @@ -1094,18 +1239,20 @@ public override async Task Select_Select_Distinct_Count(bool async) AssertSql(); } - public override async Task Single_Predicate(bool async) - { - await base.Single_Predicate(async); + public override Task Single_Predicate(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Single_Predicate(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = "ALFKI")) OFFSET 0 LIMIT 2 """); - } + }); public override async Task FirstOrDefault_inside_subquery_gets_server_evaluated(bool async) { @@ -1131,115 +1278,131 @@ public override async Task First_inside_subquery_gets_client_evaluated(bool asyn AssertSql(); } - public override async Task Last(bool async) - { - await base.Last(async); + public override Task Last(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Last(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Customer") ORDER BY c["ContactName"] DESC OFFSET 0 LIMIT 1 """); - } + }); - public override async Task Last_when_no_order_by(bool async) - { - await base.Last_when_no_order_by(async); + public override Task Last_when_no_order_by(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Last_when_no_order_by(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = "ALFKI")) OFFSET 0 LIMIT 1 """); - } + }); - public override async Task LastOrDefault_when_no_order_by(bool async) - { - await base.LastOrDefault_when_no_order_by(async); + public override Task LastOrDefault_when_no_order_by(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.LastOrDefault_when_no_order_by(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = "ALFKI")) OFFSET 0 LIMIT 1 """); - } + }); - public override async Task Last_Predicate(bool async) - { - await base.Last_Predicate(async); + public override Task Last_Predicate(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Last_Predicate(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["City"] = "London")) ORDER BY c["ContactName"] DESC OFFSET 0 LIMIT 1 """); - } + }); - public override async Task Where_Last(bool async) - { - await base.Where_Last(async); + public override Task Where_Last(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_Last(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["City"] = "London")) ORDER BY c["ContactName"] DESC OFFSET 0 LIMIT 1 """); - } + }); - public override async Task LastOrDefault(bool async) - { - await base.LastOrDefault(async); + public override Task LastOrDefault(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.LastOrDefault(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Customer") ORDER BY c["ContactName"] DESC OFFSET 0 LIMIT 1 """); - } + }); - public override async Task LastOrDefault_Predicate(bool async) - { - await base.LastOrDefault_Predicate(async); + public override Task LastOrDefault_Predicate(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.LastOrDefault_Predicate(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["City"] = "London")) ORDER BY c["ContactName"] DESC OFFSET 0 LIMIT 1 """); - } + }); - public override async Task Where_LastOrDefault(bool async) - { - await base.Where_LastOrDefault(async); + public override Task Where_LastOrDefault(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_LastOrDefault(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["City"] = "London")) ORDER BY c["ContactName"] DESC OFFSET 0 LIMIT 1 """); - } + }); public override async Task Contains_with_subquery(bool async) { @@ -1249,23 +1412,25 @@ public override async Task Contains_with_subquery(bool async) AssertSql(); } - public override async Task Contains_with_local_array_closure(bool async) - { - await base.Contains_with_local_array_closure(async); + public override Task Contains_with_local_array_closure(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Contains_with_local_array_closure(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND c["CustomerID"] IN ("ABCDE", "ALFKI")) """, - // - """ + // + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND c["CustomerID"] IN ("ABCDE")) """); - } + }); public override async Task Contains_with_subquery_and_local_array_closure(bool async) { @@ -1275,162 +1440,184 @@ public override async Task Contains_with_subquery_and_local_array_closure(bool a AssertSql(); } - public override async Task Contains_with_local_uint_array_closure(bool async) - { - await base.Contains_with_local_uint_array_closure(async); + public override Task Contains_with_local_uint_array_closure(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Contains_with_local_uint_array_closure(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Employee") AND c["EmployeeID"] IN (0, 1)) """, - // - """ + // + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Employee") AND c["EmployeeID"] IN (0)) """); - } + }); - public override async Task Contains_with_local_nullable_uint_array_closure(bool async) - { - await base.Contains_with_local_nullable_uint_array_closure(async); + public override Task Contains_with_local_nullable_uint_array_closure(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Contains_with_local_nullable_uint_array_closure(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Employee") AND c["EmployeeID"] IN (0, 1)) """, - // - """ + // + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Employee") AND c["EmployeeID"] IN (0)) """); - } + }); - public override async Task Contains_with_local_array_inline(bool async) - { - await base.Contains_with_local_array_inline(async); + public override Task Contains_with_local_array_inline(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Contains_with_local_array_inline(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND c["CustomerID"] IN ("ABCDE", "ALFKI")) """); - } + }); - public override async Task Contains_with_local_list_closure(bool async) - { - await base.Contains_with_local_list_closure(async); + public override Task Contains_with_local_list_closure(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Contains_with_local_list_closure(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND c["CustomerID"] IN ("ABCDE", "ALFKI")) """); - } + }); - public override async Task Contains_with_local_object_list_closure(bool async) - { - await base.Contains_with_local_object_list_closure(async); + public override Task Contains_with_local_object_list_closure(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Contains_with_local_object_list_closure(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND c["CustomerID"] IN ("ABCDE", "ALFKI")) """); - } + }); - public override async Task Contains_with_local_list_closure_all_null(bool async) - { - await base.Contains_with_local_list_closure_all_null(async); + public override Task Contains_with_local_list_closure_all_null(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Contains_with_local_list_closure_all_null(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = null)) """); - } + }); - public override async Task Contains_with_local_list_inline(bool async) - { - await base.Contains_with_local_list_inline(async); + public override Task Contains_with_local_list_inline(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Contains_with_local_list_inline(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND c["CustomerID"] IN ("ABCDE", "ALFKI")) """); - } + }); - public override async Task Contains_with_local_list_inline_closure_mix(bool async) - { - await base.Contains_with_local_list_inline_closure_mix(async); + public override Task Contains_with_local_list_inline_closure_mix(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Contains_with_local_list_inline_closure_mix(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND c["CustomerID"] IN ("ABCDE", "ALFKI")) """, - // - """ + // + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND c["CustomerID"] IN ("ABCDE", "ANATR")) """); - } + }); - public override async Task Contains_with_local_enumerable_closure(bool async) - { - await base.Contains_with_local_enumerable_closure(async); - AssertSql( - """ + public override Task Contains_with_local_enumerable_closure(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Contains_with_local_enumerable_closure(a); + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND c["CustomerID"] IN ("ABCDE", "ALFKI")) """, - // - """ + // + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND c["CustomerID"] IN ("ABCDE")) """); - } + }); - public override async Task Contains_with_local_object_enumerable_closure(bool async) - { - await base.Contains_with_local_object_enumerable_closure(async); + public override Task Contains_with_local_object_enumerable_closure(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Contains_with_local_object_enumerable_closure(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND c["CustomerID"] IN ("ABCDE", "ALFKI")) """ - ); - } + ); + }); - public override async Task Contains_with_local_enumerable_closure_all_null(bool async) - { - await base.Contains_with_local_enumerable_closure_all_null(async); + public override Task Contains_with_local_enumerable_closure_all_null(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Contains_with_local_enumerable_closure_all_null(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (true = false)) """ - ); - } + ); + }); public override async Task Contains_with_local_enumerable_inline(bool async) { @@ -1452,255 +1639,291 @@ await Assert.ThrowsAsync( AssertSql(); } - public override async Task Contains_with_local_ordered_enumerable_closure(bool async) - { - await base.Contains_with_local_ordered_enumerable_closure(async); + public override Task Contains_with_local_ordered_enumerable_closure(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Contains_with_local_ordered_enumerable_closure(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND c["CustomerID"] IN ("ABCDE", "ALFKI")) """, // - """ + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND c["CustomerID"] IN ("ABCDE")) """ - ); - } + ); + }); - public override async Task Contains_with_local_object_ordered_enumerable_closure(bool async) - { - await base.Contains_with_local_object_ordered_enumerable_closure(async); + public override Task Contains_with_local_object_ordered_enumerable_closure(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Contains_with_local_object_ordered_enumerable_closure(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND c["CustomerID"] IN ("ABCDE", "ALFKI")) """ - ); - } + ); + }); - public override async Task Contains_with_local_ordered_enumerable_closure_all_null(bool async) - { - await base.Contains_with_local_ordered_enumerable_closure_all_null(async); + public override Task Contains_with_local_ordered_enumerable_closure_all_null(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Contains_with_local_ordered_enumerable_closure_all_null(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = null)) """ - ); - } + ); + }); - public override async Task Contains_with_local_ordered_enumerable_inline(bool async) - { - await base.Contains_with_local_ordered_enumerable_inline(async); + public override Task Contains_with_local_ordered_enumerable_inline(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Contains_with_local_ordered_enumerable_inline(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND c["CustomerID"] IN ("ABCDE", "ALFKI")) """ - ); - } + ); + }); - public override async Task Contains_with_local_ordered_enumerable_inline_closure_mix(bool async) - { - await base.Contains_with_local_ordered_enumerable_inline_closure_mix(async); + public override Task Contains_with_local_ordered_enumerable_inline_closure_mix(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Contains_with_local_ordered_enumerable_inline_closure_mix(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND c["CustomerID"] IN ("ABCDE", "ALFKI")) """, // - """ + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND c["CustomerID"] IN ("ABCDE", "ANATR")) """ - ); - } + ); + }); - public override async Task Contains_with_local_read_only_collection_closure(bool async) - { - await base.Contains_with_local_read_only_collection_closure(async); + public override Task Contains_with_local_read_only_collection_closure(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Contains_with_local_read_only_collection_closure(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND c["CustomerID"] IN ("ABCDE", "ALFKI")) """, // - """ + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND c["CustomerID"] IN ("ABCDE")) """ - ); - } + ); + }); - public override async Task Contains_with_local_object_read_only_collection_closure(bool async) - { - await base.Contains_with_local_object_read_only_collection_closure(async); + public override Task Contains_with_local_object_read_only_collection_closure(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Contains_with_local_object_read_only_collection_closure(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND c["CustomerID"] IN ("ABCDE", "ALFKI")) """ - ); - } + ); + }); - public override async Task Contains_with_local_ordered_read_only_collection_all_null(bool async) - { - await base.Contains_with_local_ordered_read_only_collection_all_null(async); + public override Task Contains_with_local_ordered_read_only_collection_all_null(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Contains_with_local_ordered_read_only_collection_all_null(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = null)) """ - ); - } + ); + }); - public override async Task Contains_with_local_read_only_collection_inline(bool async) - { - await base.Contains_with_local_read_only_collection_inline(async); + public override Task Contains_with_local_read_only_collection_inline(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Contains_with_local_read_only_collection_inline(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND c["CustomerID"] IN ("ABCDE", "ALFKI")) """ - ); - } + ); + }); - public override async Task Contains_with_local_read_only_collection_inline_closure_mix(bool async) - { - await base.Contains_with_local_read_only_collection_inline_closure_mix(async); + public override Task Contains_with_local_read_only_collection_inline_closure_mix(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Contains_with_local_read_only_collection_inline_closure_mix(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND c["CustomerID"] IN ("ABCDE", "ALFKI")) """, // - """ + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND c["CustomerID"] IN ("ABCDE", "ANATR")) """ - ); - } + ); + }); - public override async Task Contains_with_local_collection_false(bool async) - { - await base.Contains_with_local_collection_false(async); + public override Task Contains_with_local_collection_false(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Contains_with_local_collection_false(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND c["CustomerID"] NOT IN ("ABCDE", "ALFKI")) """); - } + }); - public override async Task Contains_with_local_collection_complex_predicate_and(bool async) - { - await base.Contains_with_local_collection_complex_predicate_and(async); + public override Task Contains_with_local_collection_complex_predicate_and(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Contains_with_local_collection_complex_predicate_and(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (((c["CustomerID"] = "ALFKI") OR (c["CustomerID"] = "ABCDE")) AND c["CustomerID"] IN ("ABCDE", "ALFKI"))) """); - } + }); - public override async Task Contains_with_local_collection_complex_predicate_or(bool async) - { - await base.Contains_with_local_collection_complex_predicate_or(async); + public override Task Contains_with_local_collection_complex_predicate_or(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Contains_with_local_collection_complex_predicate_or(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] IN ("ABCDE", "ALFKI") OR ((c["CustomerID"] = "ALFKI") OR (c["CustomerID"] = "ABCDE")))) """); - } + }); - public override async Task Contains_with_local_collection_complex_predicate_not_matching_ins1(bool async) - { - await base.Contains_with_local_collection_complex_predicate_not_matching_ins1(async); + public override Task Contains_with_local_collection_complex_predicate_not_matching_ins1(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Contains_with_local_collection_complex_predicate_not_matching_ins1(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (((c["CustomerID"] = "ALFKI") OR (c["CustomerID"] = "ABCDE")) OR c["CustomerID"] NOT IN ("ABCDE", "ALFKI"))) """); - } + }); - public override async Task Contains_with_local_collection_complex_predicate_not_matching_ins2(bool async) - { - await base.Contains_with_local_collection_complex_predicate_not_matching_ins2(async); + public override Task Contains_with_local_collection_complex_predicate_not_matching_ins2(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Contains_with_local_collection_complex_predicate_not_matching_ins2(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] IN ("ABCDE", "ALFKI") AND ((c["CustomerID"] != "ALFKI") AND (c["CustomerID"] != "ABCDE")))) """); - } + }); - public override async Task Contains_with_local_collection_sql_injection(bool async) - { - await base.Contains_with_local_collection_sql_injection(async); + public override Task Contains_with_local_collection_sql_injection(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Contains_with_local_collection_sql_injection(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] IN ("ALFKI", "ABC')); GO; DROP TABLE Orders; GO; --") OR ((c["CustomerID"] = "ALFKI") OR (c["CustomerID"] = "ABCDE")))) """); - } + }); - public override async Task Contains_with_local_collection_empty_closure(bool async) - { - await base.Contains_with_local_collection_empty_closure(async); + public override Task Contains_with_local_collection_empty_closure(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Contains_with_local_collection_empty_closure(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (true = false)) """); - } + }); - public override async Task Contains_with_local_collection_empty_inline(bool async) - { - await base.Contains_with_local_collection_empty_inline(async); + public override Task Contains_with_local_collection_empty_inline(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Contains_with_local_collection_empty_inline(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND NOT((true = false))) """); - } + }); public override async Task Contains_top_level(bool async) { @@ -1753,11 +1976,15 @@ await Assert.ThrowsAsync( public override async Task Max_with_non_matching_types_in_projection_introduces_explicit_cast(bool async) { - // Aggregate selecting non-mapped type. Issue #20677. - await Assert.ThrowsAsync( - async () => await base.Max_with_non_matching_types_in_projection_introduces_explicit_cast(async)); + // Always throws for sync. + if (async) + { + // Aggregate selecting non-mapped type. Issue #20677. + await Assert.ThrowsAsync( + async () => await base.Max_with_non_matching_types_in_projection_introduces_explicit_cast(async)); - AssertSql(); + AssertSql(); + } } public override async Task Min_with_non_matching_types_in_projection_introduces_explicit_cast(bool async) @@ -1771,12 +1998,16 @@ await Assert.ThrowsAsync( public override async Task OrderBy_Take_Last_gives_correct_result(bool async) { - Assert.Equal( - CosmosStrings.ReverseAfterSkipTakeNotSupported, - (await Assert.ThrowsAsync( - async () => await base.OrderBy_Take_Last_gives_correct_result(async))).Message); + // Always throws sync-not-support for sync. + if (async) + { + Assert.Equal( + CosmosStrings.ReverseAfterSkipTakeNotSupported, + (await Assert.ThrowsAsync( + async () => await base.OrderBy_Take_Last_gives_correct_result(async))).Message); - AssertSql(); + AssertSql(); + } } public override async Task OrderBy_Skip_Last_gives_correct_result(bool async) @@ -1791,16 +2022,17 @@ public override async Task OrderBy_Skip_Last_gives_correct_result(bool async) public override async Task Contains_over_entityType_should_rewrite_to_identity_equality(bool async) { - // Contains over subquery. Issue #17246. - await AssertTranslationFailed(() => base.Contains_over_entityType_should_rewrite_to_identity_equality(async)); - - AssertSql( - """ -SELECT c -FROM root c -WHERE ((c["Discriminator"] = "Order") AND (c["OrderID"] = 10248)) -OFFSET 0 LIMIT 2 -"""); + // Inner query is always sync. + if (!async) + { + await Fixture.NoSyncTest( + async, async a => + { + // Contains over subquery. Issue #17246. + await base.Contains_over_entityType_should_rewrite_to_identity_equality(a); + } + ); + } } public override async Task List_Contains_over_entityType_should_rewrite_to_identity_equality(bool async) @@ -1811,101 +2043,117 @@ public override async Task List_Contains_over_entityType_should_rewrite_to_ident AssertSql(); } - public override async Task List_Contains_with_constant_list(bool async) - { - await base.List_Contains_with_constant_list(async); + public override Task List_Contains_with_constant_list(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.List_Contains_with_constant_list(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND c["CustomerID"] IN ("ALFKI", "ANATR")) """); - } + }); - public override async Task List_Contains_with_parameter_list(bool async) - { - await base.List_Contains_with_parameter_list(async); + public override Task List_Contains_with_parameter_list(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.List_Contains_with_parameter_list(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND c["CustomerID"] IN ("ALFKI", "ANATR")) """); - } + }); - public override async Task Contains_with_parameter_list_value_type_id(bool async) - { - await base.Contains_with_parameter_list_value_type_id(async); + public override Task Contains_with_parameter_list_value_type_id(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Contains_with_parameter_list_value_type_id(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Order") AND c["OrderID"] IN (10248, 10249)) """); - } + }); - public override async Task Contains_with_constant_list_value_type_id(bool async) - { - await base.Contains_with_constant_list_value_type_id(async); + public override Task Contains_with_constant_list_value_type_id(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Contains_with_constant_list_value_type_id(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Order") AND c["OrderID"] IN (10248, 10249)) """); - } + }); - public override async Task IImmutableSet_Contains_with_parameter(bool async) - { - await base.IImmutableSet_Contains_with_parameter(async); + public override Task IImmutableSet_Contains_with_parameter(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.IImmutableSet_Contains_with_parameter(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND c["CustomerID"] IN ("ALFKI")) """); - } + }); - public override async Task IReadOnlySet_Contains_with_parameter(bool async) - { - await base.IReadOnlySet_Contains_with_parameter(async); + public override Task IReadOnlySet_Contains_with_parameter(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.IReadOnlySet_Contains_with_parameter(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND c["CustomerID"] IN ("ALFKI")) """); - } + }); - public override async Task HashSet_Contains_with_parameter(bool async) - { - await base.HashSet_Contains_with_parameter(async); + public override Task HashSet_Contains_with_parameter(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.HashSet_Contains_with_parameter(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND c["CustomerID"] IN ("ALFKI")) """); - } + }); - public override async Task ImmutableHashSet_Contains_with_parameter(bool async) - { - await base.ImmutableHashSet_Contains_with_parameter(async); + public override Task ImmutableHashSet_Contains_with_parameter(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.ImmutableHashSet_Contains_with_parameter(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND c["CustomerID"] IN ("ALFKI")) """); - } + }); public override async Task Contains_over_entityType_with_null_should_rewrite_to_false(bool async) { @@ -1923,149 +2171,171 @@ public override async Task Contains_over_entityType_with_null_in_projection(bool AssertSql(); } - public override async Task String_FirstOrDefault_in_projection_does_not_do_client_eval(bool async) - { - await base.String_FirstOrDefault_in_projection_does_not_do_client_eval(async); + public override Task String_FirstOrDefault_in_projection_does_not_do_client_eval(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.String_FirstOrDefault_in_projection_does_not_do_client_eval(a); - AssertSql( - """ + AssertSql( + """ SELECT LEFT(c["CustomerID"], 1) AS c FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); - public override async Task Project_constant_Sum(bool async) - { - await base.Project_constant_Sum(async); + public override Task Project_constant_Sum(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Project_constant_Sum(a); - AssertSql( - """ + AssertSql( + """ SELECT SUM(1) AS c FROM root c WHERE (c["Discriminator"] = "Employee") """); - } + }); - public override async Task Where_subquery_any_equals_operator(bool async) - { - await base.Where_subquery_any_equals_operator(async); + public override Task Where_subquery_any_equals_operator(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_subquery_any_equals_operator(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND c["CustomerID"] IN ("ABCDE", "ALFKI", "ANATR")) """); - } + }); - public override async Task Where_subquery_any_equals(bool async) - { - await base.Where_subquery_any_equals(async); + public override Task Where_subquery_any_equals(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_subquery_any_equals(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND c["CustomerID"] IN ("ABCDE", "ALFKI", "ANATR")) """); - } + }); - public override async Task Where_subquery_any_equals_static(bool async) - { - await base.Where_subquery_any_equals_static(async); + public override Task Where_subquery_any_equals_static(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_subquery_any_equals_static(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND c["CustomerID"] IN ("ABCDE", "ALFKI", "ANATR")) """); - } + }); - public override async Task Where_subquery_where_any(bool async) - { - await base.Where_subquery_where_any(async); + public override Task Where_subquery_where_any(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_subquery_where_any(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (((c["Discriminator"] = "Customer") AND (c["City"] = "México D.F.")) AND c["CustomerID"] IN ("ABCDE", "ALFKI", "ANATR")) """, - // - """ + // + """ SELECT c FROM root c WHERE (((c["Discriminator"] = "Customer") AND (c["City"] = "México D.F.")) AND c["CustomerID"] IN ("ABCDE", "ALFKI", "ANATR")) """); - } + }); - public override async Task Where_subquery_all_not_equals_operator(bool async) - { - await base.Where_subquery_all_not_equals_operator(async); + public override Task Where_subquery_all_not_equals_operator(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_subquery_all_not_equals_operator(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND c["CustomerID"] NOT IN ("ABCDE", "ALFKI", "ANATR")) """); - } + }); - public override async Task Where_subquery_all_not_equals(bool async) - { - await base.Where_subquery_all_not_equals(async); + public override Task Where_subquery_all_not_equals(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_subquery_all_not_equals(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND c["CustomerID"] NOT IN ("ABCDE", "ALFKI", "ANATR")) """); - } + }); - public override async Task Where_subquery_all_not_equals_static(bool async) - { - await base.Where_subquery_all_not_equals_static(async); + public override Task Where_subquery_all_not_equals_static(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_subquery_all_not_equals_static(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND c["CustomerID"] NOT IN ("ABCDE", "ALFKI", "ANATR")) """); - } + }); - public override async Task Where_subquery_where_all(bool async) - { - await base.Where_subquery_where_all(async); + public override Task Where_subquery_where_all(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_subquery_where_all(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (((c["Discriminator"] = "Customer") AND (c["City"] = "México D.F.")) AND c["CustomerID"] NOT IN ("ABCDE", "ALFKI", "ANATR")) """, - // - """ + // + """ SELECT c FROM root c WHERE (((c["Discriminator"] = "Customer") AND (c["City"] = "México D.F.")) AND c["CustomerID"] NOT IN ("ABCDE", "ALFKI", "ANATR")) """); - } + }); - public override async Task Cast_to_same_Type_Count_works(bool async) - { - await base.Cast_to_same_Type_Count_works(async); + public override Task Cast_to_same_Type_Count_works(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Cast_to_same_Type_Count_works(a); - AssertSql( - """ + AssertSql( + """ SELECT COUNT(1) AS c FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); public override async Task Cast_before_aggregate_is_preserved(bool async) { @@ -2261,127 +2531,141 @@ public override async Task Contains_inside_aggregate_function_with_GroupBy(bool AssertSql(); } - public override async Task Contains_inside_Average_without_GroupBy(bool async) - { - await base.Contains_inside_Average_without_GroupBy(async); + public override Task Contains_inside_Average_without_GroupBy(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Contains_inside_Average_without_GroupBy(a); - AssertSql( - """ + AssertSql( + """ SELECT AVG((c["City"] IN ("London", "Berlin") ? 1.0 : 0.0)) AS c FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); - public override async Task Contains_inside_Sum_without_GroupBy(bool async) - { - await base.Contains_inside_Sum_without_GroupBy(async); + public override Task Contains_inside_Sum_without_GroupBy(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Contains_inside_Sum_without_GroupBy(a); - AssertSql( - """ + AssertSql( + """ SELECT SUM((c["City"] IN ("London", "Berlin") ? 1 : 0)) AS c FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); - public override async Task Contains_inside_Count_without_GroupBy(bool async) - { - await base.Contains_inside_Count_without_GroupBy(async); + public override Task Contains_inside_Count_without_GroupBy(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Contains_inside_Count_without_GroupBy(a); - AssertSql( - """ + AssertSql( + """ SELECT COUNT(1) AS c FROM root c WHERE ((c["Discriminator"] = "Customer") AND c["City"] IN ("London", "Berlin")) """); - } + }); - public override async Task Contains_inside_LongCount_without_GroupBy(bool async) - { - await base.Contains_inside_LongCount_without_GroupBy(async); + public override Task Contains_inside_LongCount_without_GroupBy(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Contains_inside_LongCount_without_GroupBy(a); - AssertSql( - """ + AssertSql( + """ SELECT COUNT(1) AS c FROM root c WHERE ((c["Discriminator"] = "Customer") AND c["City"] IN ("London", "Berlin")) """); - } + }); - public override async Task Contains_inside_Max_without_GroupBy(bool async) - { - await base.Contains_inside_Max_without_GroupBy(async); + public override Task Contains_inside_Max_without_GroupBy(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Contains_inside_Max_without_GroupBy(a); - AssertSql( - """ + AssertSql( + """ SELECT MAX((c["City"] IN ("London", "Berlin") ? 1 : 0)) AS c FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); - public override async Task Contains_inside_Min_without_GroupBy(bool async) - { - await base.Contains_inside_Min_without_GroupBy(async); + public override Task Contains_inside_Min_without_GroupBy(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Contains_inside_Min_without_GroupBy(a); - AssertSql( - """ + AssertSql( + """ SELECT MIN((c["City"] IN ("London", "Berlin") ? 1 : 0)) AS c FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); - public override async Task Return_type_of_singular_operator_is_preserved(bool async) - { - await base.Return_type_of_singular_operator_is_preserved(async); + public override Task Return_type_of_singular_operator_is_preserved(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Return_type_of_singular_operator_is_preserved(a); - AssertSql( -""" + AssertSql( + """ SELECT c["CustomerID"], c["City"] FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = "ALFKI")) OFFSET 0 LIMIT 1 """, - // - """ + // + """ SELECT c["CustomerID"], c["City"] FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = "ALFKI")) OFFSET 0 LIMIT 1 """, - // - """ + // + """ SELECT c["CustomerID"], c["City"] FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = "ALFKI")) OFFSET 0 LIMIT 2 """, - // - """ + // + """ SELECT c["CustomerID"], c["City"] FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = "ALFKI")) OFFSET 0 LIMIT 2 """, - // - """ + // + """ SELECT c["CustomerID"], c["City"] FROM root c WHERE ((c["Discriminator"] = "Customer") AND STARTSWITH(c["CustomerID"], "A")) ORDER BY c["CustomerID"] DESC OFFSET 0 LIMIT 1 """, - // - """ + // + """ SELECT c["CustomerID"], c["City"] FROM root c WHERE ((c["Discriminator"] = "Customer") AND STARTSWITH(c["CustomerID"], "A")) ORDER BY c["CustomerID"] DESC OFFSET 0 LIMIT 1 """); - } + }); [ConditionalTheory(Skip = "Issue #20677")] public override async Task Type_casting_inside_sum(bool async) diff --git a/test/EFCore.Cosmos.FunctionalTests/Query/NorthwindDbFunctionsQueryCosmosTest.cs b/test/EFCore.Cosmos.FunctionalTests/Query/NorthwindDbFunctionsQueryCosmosTest.cs index 0b135f341ec..f763a2682ad 100644 --- a/test/EFCore.Cosmos.FunctionalTests/Query/NorthwindDbFunctionsQueryCosmosTest.cs +++ b/test/EFCore.Cosmos.FunctionalTests/Query/NorthwindDbFunctionsQueryCosmosTest.cs @@ -54,29 +54,33 @@ public override async Task Like_identity(bool async) AssertSql(); } - public override async Task Random_return_less_than_1(bool async) - { - await base.Random_return_less_than_1(async); - - AssertSql( - """ + public override Task Random_return_less_than_1(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Random_return_less_than_1(async); + + AssertSql( + """ SELECT COUNT(1) AS c FROM root c WHERE ((c["Discriminator"] = "Order") AND (RAND() < 1.0)) """); - } + }); - public override async Task Random_return_greater_than_0(bool async) - { - await base.Random_return_greater_than_0(async); + public override Task Random_return_greater_than_0(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Random_return_greater_than_0(async); - AssertSql( - """ + AssertSql( + """ SELECT COUNT(1) AS c FROM root c WHERE ((c["Discriminator"] = "Order") AND (RAND() >= 0.0)) """); - } + }); private void AssertSql(params string[] expected) => Fixture.TestSqlLoggerFactory.AssertBaseline(expected); diff --git a/test/EFCore.Cosmos.FunctionalTests/Query/NorthwindFunctionsQueryCosmosTest.cs b/test/EFCore.Cosmos.FunctionalTests/Query/NorthwindFunctionsQueryCosmosTest.cs index b0d22270226..c65d2341d05 100644 --- a/test/EFCore.Cosmos.FunctionalTests/Query/NorthwindFunctionsQueryCosmosTest.cs +++ b/test/EFCore.Cosmos.FunctionalTests/Query/NorthwindFunctionsQueryCosmosTest.cs @@ -24,200 +24,232 @@ public NorthwindFunctionsQueryCosmosTest( public virtual void Check_all_tests_overridden() => TestHelpers.AssertAllMethodsOverridden(GetType()); - public override async Task String_StartsWith_Literal(bool async) - { - await base.String_StartsWith_Literal(async); + public override Task String_StartsWith_Literal(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.String_StartsWith_Literal(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND STARTSWITH(c["ContactName"], "M")) """); - } + }); - public override async Task String_StartsWith_Parameter(bool async) - { - await base.String_StartsWith_Parameter(async); + public override Task String_StartsWith_Parameter(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.String_StartsWith_Parameter(a); - AssertSql( - """ + AssertSql( + """ @__pattern_0='M' SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND STARTSWITH(c["ContactName"], @__pattern_0)) """); - } + }); - public override async Task String_StartsWith_Identity(bool async) - { - await base.String_StartsWith_Identity(async); + public override Task String_StartsWith_Identity(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.String_StartsWith_Identity(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND STARTSWITH(c["ContactName"], c["ContactName"])) """); - } + }); - public override async Task String_StartsWith_Column(bool async) - { - await base.String_StartsWith_Column(async); + public override Task String_StartsWith_Column(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.String_StartsWith_Column(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND STARTSWITH(c["ContactName"], c["ContactName"])) """); - } + }); - public override async Task String_StartsWith_MethodCall(bool async) - { - await base.String_StartsWith_MethodCall(async); + public override Task String_StartsWith_MethodCall(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.String_StartsWith_MethodCall(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND STARTSWITH(c["ContactName"], "M")) """); - } + }); - public override async Task String_EndsWith_Literal(bool async) - { - await base.String_EndsWith_Literal(async); + public override Task String_EndsWith_Literal(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.String_EndsWith_Literal(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND ENDSWITH(c["ContactName"], "b")) """); - } + }); - public override async Task String_EndsWith_Parameter(bool async) - { - await base.String_EndsWith_Parameter(async); + public override Task String_EndsWith_Parameter(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.String_EndsWith_Parameter(a); - AssertSql( - """ + AssertSql( + """ @__pattern_0='b' SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND ENDSWITH(c["ContactName"], @__pattern_0)) """); - } + }); - public override async Task String_EndsWith_Identity(bool async) - { - await base.String_EndsWith_Identity(async); + public override Task String_EndsWith_Identity(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.String_EndsWith_Identity(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND ENDSWITH(c["ContactName"], c["ContactName"])) """); - } + }); - public override async Task String_EndsWith_Column(bool async) - { - await base.String_EndsWith_Column(async); + public override Task String_EndsWith_Column(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.String_EndsWith_Column(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND ENDSWITH(c["ContactName"], c["ContactName"])) """); - } + }); - public override async Task String_EndsWith_MethodCall(bool async) - { - await base.String_EndsWith_MethodCall(async); + public override Task String_EndsWith_MethodCall(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.String_EndsWith_MethodCall(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND ENDSWITH(c["ContactName"], "m")) """); - } + }); - public override async Task String_Contains_Literal(bool async) - { - await base.String_Contains_Literal(async); + public override Task String_Contains_Literal(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.String_Contains_Literal(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND CONTAINS(c["ContactName"], "M")) """); - } + }); - public override async Task String_Contains_Identity(bool async) - { - await base.String_Contains_Identity(async); - AssertSql( - """ + public override Task String_Contains_Identity(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.String_Contains_Identity(a); + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND CONTAINS(c["ContactName"], c["ContactName"])) """); - } + }); - public override async Task String_Contains_Column(bool async) - { - await base.String_Contains_Column(async); + public override Task String_Contains_Column(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.String_Contains_Column(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND CONTAINS(c["ContactName"], c["ContactName"])) """); - } + }); - public override async Task String_FirstOrDefault_MethodCall(bool async) - { - await base.String_FirstOrDefault_MethodCall(async); + public override Task String_FirstOrDefault_MethodCall(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.String_FirstOrDefault_MethodCall(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (LEFT(c["ContactName"], 1) = "A")) """); - } + }); - public override async Task String_LastOrDefault_MethodCall(bool async) - { - await base.String_LastOrDefault_MethodCall(async); + public override Task String_LastOrDefault_MethodCall(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.String_LastOrDefault_MethodCall(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (RIGHT(c["ContactName"], 1) = "s")) """); - } + }); - public override async Task String_Contains_MethodCall(bool async) - { - await base.String_Contains_MethodCall(async); + public override Task String_Contains_MethodCall(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.String_Contains_MethodCall(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND CONTAINS(c["ContactName"], "M")) """); - } + }); public override async Task String_Compare_simple_zero(bool async) { @@ -315,53 +347,61 @@ public override async Task String_Compare_to_multi_predicate(bool async) AssertSql(); } - public override async Task Where_math_abs1(bool async) - { - await base.Where_math_abs1(async); + public override Task Where_math_abs1(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_math_abs1(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Product") AND (ABS(c["ProductID"]) > 10)) """); - } + }); - public override async Task Where_math_abs2(bool async) - { - await base.Where_math_abs2(async); + public override Task Where_math_abs2(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_math_abs2(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (((c["Discriminator"] = "OrderDetail") AND (c["UnitPrice"] < 7.0)) AND (ABS(c["Quantity"]) > 10)) """); - } + }); - public override async Task Where_math_abs3(bool async) - { - await base.Where_math_abs3(async); + public override Task Where_math_abs3(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_math_abs3(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (((c["Discriminator"] = "OrderDetail") AND (c["Quantity"] < 5)) AND (ABS(c["UnitPrice"]) > 10.0)) """); - } + }); - public override async Task Where_math_abs_uncorrelated(bool async) - { - await base.Where_math_abs_uncorrelated(async); + public override Task Where_math_abs_uncorrelated(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_math_abs_uncorrelated(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (((c["Discriminator"] = "OrderDetail") AND (c["UnitPrice"] < 7.0)) AND (10 < c["ProductID"])) """); - } + }); public override async Task Where_math_ceiling1(bool async) { @@ -371,29 +411,33 @@ public override async Task Where_math_ceiling1(bool async) AssertSql(); } - public override async Task Where_math_ceiling2(bool async) - { - await base.Where_math_ceiling2(async); + public override Task Where_math_ceiling2(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_math_ceiling2(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (((c["Discriminator"] = "OrderDetail") AND (c["Quantity"] < 5)) AND (CEILING(c["UnitPrice"]) > 10.0)) """); - } + }); - public override async Task Where_math_floor(bool async) - { - await base.Where_math_floor(async); + public override Task Where_math_floor(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_math_floor(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (((c["Discriminator"] = "OrderDetail") AND (c["Quantity"] < 5)) AND (FLOOR(c["UnitPrice"]) > 10.0)) """); - } + }); public override async Task Where_math_power(bool async) { @@ -411,17 +455,19 @@ public override async Task Where_math_square(bool async) AssertSql(); } - public override async Task Where_math_round(bool async) - { - await base.Where_math_round(async); + public override Task Where_math_round(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_math_round(async); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (((c["Discriminator"] = "OrderDetail") AND (c["Quantity"] < 5)) AND (ROUND(c["UnitPrice"]) > 10.0)) """); - } + }); public override Task Sum_over_round_works_correctly_in_projection(bool async) => AssertTranslationFailed(() => base.Sum_over_round_works_correctly_in_projection(async)); @@ -435,29 +481,33 @@ public override Task Sum_over_truncate_works_correctly_in_projection(bool async) public override Task Sum_over_truncate_works_correctly_in_projection_2(bool async) => AssertTranslationFailed(() => base.Sum_over_truncate_works_correctly_in_projection_2(async)); - public override async Task Select_math_round_int(bool async) - { - await base.Select_math_round_int(async); + public override Task Select_math_round_int(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_math_round_int(a); - AssertSql( - """ + AssertSql( + """ SELECT c["OrderID"] FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderID"] < 10250)) """); - } + }); - public override async Task Select_math_truncate_int(bool async) - { - await base.Select_math_truncate_int(async); + public override Task Select_math_truncate_int(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_math_truncate_int(a); - AssertSql( - """ + AssertSql( + """ SELECT c["OrderID"] FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderID"] < 10250)) """); - } + }); public override async Task Where_math_round2(bool async) { @@ -467,17 +517,19 @@ public override async Task Where_math_round2(bool async) AssertSql(); } - public override async Task Where_math_truncate(bool async) - { - await base.Where_math_truncate(async); + public override Task Where_math_truncate(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_math_truncate(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (((c["Discriminator"] = "OrderDetail") AND (c["Quantity"] < 5)) AND (TRUNC(c["UnitPrice"]) > 10.0)) """); - } + }); public override async Task Where_math_exp(bool async) { @@ -575,17 +627,19 @@ public override async Task Where_math_tan(bool async) AssertSql(); } - public override async Task Where_math_sign(bool async) - { - await base.Where_math_sign(async); + public override Task Where_math_sign(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_math_sign(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (((c["Discriminator"] = "OrderDetail") AND (c["OrderID"] = 11077)) AND (SIGN(c["Discount"]) > 0)) """); - } + }); public override async Task Where_math_min(bool async) { @@ -659,17 +713,19 @@ public override async Task Where_mathf_abs1(bool async) AssertSql(); } - public override async Task Where_mathf_ceiling1(bool async) - { - await base.Where_mathf_ceiling1(async); + public override Task Where_mathf_ceiling1(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_mathf_ceiling1(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (((c["Discriminator"] = "OrderDetail") AND (c["UnitPrice"] < 7.0)) AND (CEILING(c["Discount"]) > 0.0)) """); - } + }); public override async Task Where_mathf_floor(bool async) { @@ -679,29 +735,33 @@ public override async Task Where_mathf_floor(bool async) AssertSql(); } - public override async Task Where_mathf_power(bool async) - { - await base.Where_mathf_power(async); + public override Task Where_mathf_power(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_mathf_power(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "OrderDetail") AND (POWER(c["Discount"], 3.0) > 0.005)) """); - } + }); - public override async Task Where_mathf_square(bool async) - { - await base.Where_mathf_square(async); + public override Task Where_mathf_square(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_mathf_square(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "OrderDetail") AND (POWER(c["Discount"], 2.0) > 0.05)) """); - } + }); public override async Task Where_mathf_round2(bool async) { @@ -719,185 +779,215 @@ public override async Task Where_mathf_truncate(bool async) AssertSql(); } - public override async Task Where_mathf_exp(bool async) - { - await base.Where_mathf_exp(async); + public override Task Where_mathf_exp(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_mathf_exp(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (((c["Discriminator"] = "OrderDetail") AND (c["OrderID"] = 11077)) AND (EXP(c["Discount"]) > 1.0)) """); - } + }); - public override async Task Where_mathf_log10(bool async) - { - await base.Where_mathf_log10(async); + public override Task Where_mathf_log10(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_mathf_log10(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (((c["Discriminator"] = "OrderDetail") AND ((c["OrderID"] = 11077) AND (c["Discount"] > 0.0))) AND (LOG10(c["Discount"]) < 0.0)) """); - } + }); - public override async Task Where_mathf_log(bool async) - { - await base.Where_mathf_log(async); + public override Task Where_mathf_log(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_mathf_log(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (((c["Discriminator"] = "OrderDetail") AND ((c["OrderID"] = 11077) AND (c["Discount"] > 0.0))) AND (LOG(c["Discount"]) < 0.0)) """); - } + }); - public override async Task Where_mathf_log_new_base(bool async) - { - await base.Where_mathf_log_new_base(async); + public override Task Where_mathf_log_new_base(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_mathf_log_new_base(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (((c["Discriminator"] = "OrderDetail") AND ((c["OrderID"] = 11077) AND (c["Discount"] > 0.0))) AND (LOG(c["Discount"], 7.0) < -1.0)) """); - } + }); - public override async Task Where_mathf_sqrt(bool async) - { - await base.Where_mathf_sqrt(async); + public override Task Where_mathf_sqrt(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_mathf_sqrt(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (((c["Discriminator"] = "OrderDetail") AND (c["OrderID"] = 11077)) AND (SQRT(c["Discount"]) > 0.0)) """); - } + }); - public override async Task Where_mathf_acos(bool async) - { - await base.Where_mathf_acos(async); + public override Task Where_mathf_acos(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_mathf_acos(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (((c["Discriminator"] = "OrderDetail") AND (c["OrderID"] = 11077)) AND (ACOS(c["Discount"]) > 1.0)) """); - } + }); - public override async Task Where_mathf_asin(bool async) - { - await base.Where_mathf_asin(async); + public override Task Where_mathf_asin(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_mathf_asin(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (((c["Discriminator"] = "OrderDetail") AND (c["OrderID"] = 11077)) AND (ASIN(c["Discount"]) > 0.0)) """); - } + }); - public override async Task Where_mathf_atan(bool async) - { - await base.Where_mathf_atan(async); + public override Task Where_mathf_atan(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_mathf_atan(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (((c["Discriminator"] = "OrderDetail") AND (c["OrderID"] = 11077)) AND (ATAN(c["Discount"]) > 0.0)) """); - } + }); - public override async Task Where_mathf_atan2(bool async) - { - await base.Where_mathf_atan2(async); + public override Task Where_mathf_atan2(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_mathf_atan2(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (((c["Discriminator"] = "OrderDetail") AND (c["OrderID"] = 11077)) AND (ATN2(c["Discount"], 1.0) > 0.0)) """); - } + }); - public override async Task Where_mathf_cos(bool async) - { - await base.Where_mathf_cos(async); + public override Task Where_mathf_cos(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_mathf_cos(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (((c["Discriminator"] = "OrderDetail") AND (c["OrderID"] = 11077)) AND (COS(c["Discount"]) > 0.0)) """); - } + }); - public override async Task Where_mathf_sin(bool async) - { - await base.Where_mathf_sin(async); + public override Task Where_mathf_sin(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_mathf_sin(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (((c["Discriminator"] = "OrderDetail") AND (c["OrderID"] = 11077)) AND (SIN(c["Discount"]) > 0.0)) """); - } + }); - public override async Task Where_mathf_tan(bool async) - { - await base.Where_mathf_tan(async); + public override Task Where_mathf_tan(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_mathf_tan(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (((c["Discriminator"] = "OrderDetail") AND (c["OrderID"] = 11077)) AND (TAN(c["Discount"]) > 0.0)) """); - } + }); - public override async Task Where_mathf_sign(bool async) - { - await base.Where_mathf_sign(async); + public override Task Where_mathf_sign(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_mathf_sign(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (((c["Discriminator"] = "OrderDetail") AND (c["OrderID"] = 11077)) AND (SIGN(c["Discount"]) > 0)) """); - } + }); - public override async Task Where_mathf_degrees(bool async) - { - await base.Where_mathf_degrees(async); + public override Task Where_mathf_degrees(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_mathf_degrees(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (((c["Discriminator"] = "OrderDetail") AND (c["OrderID"] = 11077)) AND (DEGREES(c["Discount"]) > 0.0)) """); - } + }); - public override async Task Where_mathf_radians(bool async) - { - await base.Where_mathf_radians(async); + public override Task Where_mathf_radians(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_mathf_radians(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (((c["Discriminator"] = "OrderDetail") AND (c["OrderID"] = 11077)) AND (RADIANS(c["Discount"]) > 0.0)) """); - } + }); public override async Task Where_guid_newguid(bool async) { @@ -907,29 +997,33 @@ public override async Task Where_guid_newguid(bool async) AssertSql(); } - public override async Task Where_string_to_upper(bool async) - { - await base.Where_string_to_upper(async); + public override Task Where_string_to_upper(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_string_to_upper(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (UPPER(c["CustomerID"]) = "ALFKI")) """); - } + }); - public override async Task Where_string_to_lower(bool async) - { - await base.Where_string_to_lower(async); + public override Task Where_string_to_lower(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_string_to_lower(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (LOWER(c["CustomerID"]) = "alfki")) """); - } + }); public override async Task Where_functions_nested(bool async) { @@ -1003,193 +1097,223 @@ public override async Task Convert_ToString(bool async) AssertSql(); } - public override async Task Indexof_with_emptystring(bool async) - { - await base.Indexof_with_emptystring(async); + public override Task Indexof_with_emptystring(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Indexof_with_emptystring(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (INDEX_OF(c["ContactName"], "") = 0)) """); - } + }); - public override async Task Indexof_with_one_constant_arg(bool async) - { - await base.Indexof_with_one_constant_arg(async); + public override Task Indexof_with_one_constant_arg(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Indexof_with_one_constant_arg(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (INDEX_OF(c["ContactName"], "a") = 1)) """); - } + }); - public override async Task Indexof_with_one_parameter_arg(bool async) - { - await base.Indexof_with_one_parameter_arg(async); + public override Task Indexof_with_one_parameter_arg(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Indexof_with_one_parameter_arg(a); - AssertSql( - """ + AssertSql( + """ @__pattern_0='a' SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (INDEX_OF(c["ContactName"], @__pattern_0) = 1)) """); - } + }); - public override async Task Indexof_with_constant_starting_position(bool async) - { - await base.Indexof_with_constant_starting_position(async); + public override Task Indexof_with_constant_starting_position(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Indexof_with_constant_starting_position(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (INDEX_OF(c["ContactName"], "a", 2) = 4)) """); - } + }); - public override async Task Indexof_with_parameter_starting_position(bool async) - { - await base.Indexof_with_parameter_starting_position(async); + public override Task Indexof_with_parameter_starting_position(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Indexof_with_parameter_starting_position(a); - AssertSql( - """ + AssertSql( + """ @__start_0='2' SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (INDEX_OF(c["ContactName"], "a", @__start_0) = 4)) """); - } + }); - public override async Task Replace_with_emptystring(bool async) - { - await base.Replace_with_emptystring(async); + public override Task Replace_with_emptystring(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Replace_with_emptystring(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (REPLACE(c["ContactName"], "ia", "") = "Mar Anders")) """); - } + }); - public override async Task Replace_using_property_arguments(bool async) - { - await base.Replace_using_property_arguments(async); + public override Task Replace_using_property_arguments(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Replace_using_property_arguments(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (REPLACE(c["ContactName"], c["ContactName"], c["CustomerID"]) = c["CustomerID"])) """); - } + }); - public override async Task Substring_with_one_arg_with_zero_startindex(bool async) - { - await base.Substring_with_one_arg_with_zero_startindex(async); + public override Task Substring_with_one_arg_with_zero_startindex(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Substring_with_one_arg_with_zero_startindex(a); - AssertSql( - """ + AssertSql( + """ SELECT c["ContactName"] FROM root c WHERE ((c["Discriminator"] = "Customer") AND (SUBSTRING(c["CustomerID"], 0, LENGTH(c["CustomerID"])) = "ALFKI")) """); - } + }); - public override async Task Substring_with_one_arg_with_constant(bool async) - { - await base.Substring_with_one_arg_with_constant(async); + public override Task Substring_with_one_arg_with_constant(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Substring_with_one_arg_with_constant(a); - AssertSql( - """ + AssertSql( + """ SELECT c["ContactName"] FROM root c WHERE ((c["Discriminator"] = "Customer") AND (SUBSTRING(c["CustomerID"], 1, LENGTH(c["CustomerID"])) = "LFKI")) """); - } + }); - public override async Task Substring_with_one_arg_with_closure(bool async) - { - await base.Substring_with_one_arg_with_closure(async); + public override Task Substring_with_one_arg_with_closure(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Substring_with_one_arg_with_closure(a); - AssertSql( - """ + AssertSql( + """ @__start_0='2' SELECT c["ContactName"] FROM root c WHERE ((c["Discriminator"] = "Customer") AND (SUBSTRING(c["CustomerID"], @__start_0, LENGTH(c["CustomerID"])) = "FKI")) """); - } + }); - public override async Task Substring_with_two_args_with_zero_startindex(bool async) - { - await base.Substring_with_two_args_with_zero_startindex(async); + public override Task Substring_with_two_args_with_zero_startindex(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Substring_with_two_args_with_zero_startindex(a); - AssertSql( - """ + AssertSql( + """ SELECT LEFT(c["ContactName"], 3) AS c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = "ALFKI")) """); - } + }); - public override async Task Substring_with_two_args_with_zero_length(bool async) - { - await base.Substring_with_two_args_with_zero_length(async); + public override Task Substring_with_two_args_with_zero_length(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Substring_with_two_args_with_zero_length(a); - AssertSql( - """ + AssertSql( + """ SELECT SUBSTRING(c["ContactName"], 2, 0) AS c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = "ALFKI")) """); - } + }); - public override async Task Substring_with_two_args_with_constant(bool async) - { - await base.Substring_with_two_args_with_constant(async); + public override Task Substring_with_two_args_with_constant(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Substring_with_two_args_with_constant(a); - AssertSql( - """ + AssertSql( + """ SELECT SUBSTRING(c["ContactName"], 1, 3) AS c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = "ALFKI")) """); - } + }); - public override async Task Substring_with_two_args_with_closure(bool async) - { - await base.Substring_with_two_args_with_closure(async); + public override Task Substring_with_two_args_with_closure(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Substring_with_two_args_with_closure(a); - AssertSql( - """ + AssertSql( + """ @__start_0='2' SELECT SUBSTRING(c["ContactName"], @__start_0, 3) AS c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = "ALFKI")) """); - } + }); - public override async Task Substring_with_two_args_with_Index_of(bool async) - { - await base.Substring_with_two_args_with_Index_of(async); + public override Task Substring_with_two_args_with_Index_of(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Substring_with_two_args_with_Index_of(a); - AssertSql( - """ + AssertSql( + """ SELECT SUBSTRING(c["ContactName"], INDEX_OF(c["ContactName"], "a"), 3) AS c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = "ALFKI")) """); - } + }); public override async Task IsNullOrEmpty_in_predicate(bool async) { @@ -1215,29 +1339,33 @@ public override async Task IsNullOrWhiteSpace_in_predicate_on_non_nullable_colum AssertSql(); } - public override async Task IsNullOrEmpty_in_projection(bool async) - { - await base.IsNullOrEmpty_in_projection(async); + public override Task IsNullOrEmpty_in_projection(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.IsNullOrEmpty_in_projection(a); - AssertSql( - """ + AssertSql( + """ SELECT c["CustomerID"], c["Region"] FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); - public override async Task IsNullOrEmpty_negated_in_projection(bool async) - { - await base.IsNullOrEmpty_negated_in_projection(async); + public override Task IsNullOrEmpty_negated_in_projection(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.IsNullOrEmpty_negated_in_projection(a); - AssertSql( - """ + AssertSql( + """ SELECT c["CustomerID"], c["Region"] FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); public override async Task IsNullOrWhiteSpace_in_predicate(bool async) { @@ -1247,17 +1375,19 @@ public override async Task IsNullOrWhiteSpace_in_predicate(bool async) AssertSql(); } - public override async Task TrimStart_without_arguments_in_predicate(bool async) - { - await base.TrimStart_without_arguments_in_predicate(async); + public override Task TrimStart_without_arguments_in_predicate(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.TrimStart_without_arguments_in_predicate(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (LTRIM(c["ContactTitle"]) = "Owner")) """); - } + }); public override async Task TrimStart_with_char_argument_in_predicate(bool async) { @@ -1275,17 +1405,19 @@ public override async Task TrimStart_with_char_array_argument_in_predicate(bool AssertSql(); } - public override async Task TrimEnd_without_arguments_in_predicate(bool async) - { - await base.TrimEnd_without_arguments_in_predicate(async); + public override Task TrimEnd_without_arguments_in_predicate(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.TrimEnd_without_arguments_in_predicate(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (RTRIM(c["ContactTitle"]) = "Owner")) """); - } + }); public override async Task TrimEnd_with_char_argument_in_predicate(bool async) { @@ -1303,17 +1435,19 @@ public override async Task TrimEnd_with_char_array_argument_in_predicate(bool as AssertSql(); } - public override async Task Trim_without_argument_in_predicate(bool async) - { - await base.Trim_without_argument_in_predicate(async); + public override Task Trim_without_argument_in_predicate(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Trim_without_argument_in_predicate(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (TRIM(c["ContactTitle"]) = "Owner")) """); - } + }); public override async Task Trim_with_char_argument_in_predicate(bool async) { @@ -1333,63 +1467,74 @@ public override async Task Trim_with_char_array_argument_in_predicate(bool async public override async Task Order_by_length_twice(bool async) { - // Unsupported ORDER BY clause. Issue #27037. - await Assert.ThrowsAsync(() => base.Order_by_length_twice(async)); + // Always throws for sync. + if (async) + { + // Unsupported ORDER BY clause. Issue #27037. + await Assert.ThrowsAsync(() => base.Order_by_length_twice(async)); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Customer") ORDER BY LENGTH(c["CustomerID"]), c["CustomerID"] """); + } } public override async Task Order_by_length_twice_followed_by_projection_of_naked_collection_navigation(bool async) { // Cosmos client evaluation. Issue #17246. - await AssertTranslationFailed(() => base.Order_by_length_twice_followed_by_projection_of_naked_collection_navigation(async)); + await AssertTranslationFailed( + () => base.Order_by_length_twice_followed_by_projection_of_naked_collection_navigation(async)); AssertSql(); } - public override async Task Static_string_equals_in_predicate(bool async) - { - await base.Static_string_equals_in_predicate(async); + public override Task Static_string_equals_in_predicate(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Static_string_equals_in_predicate(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = "ANATR")) """); - } + }); - public override async Task Static_equals_nullable_datetime_compared_to_non_nullable(bool async) - { - await base.Static_equals_nullable_datetime_compared_to_non_nullable(async); + public override Task Static_equals_nullable_datetime_compared_to_non_nullable(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Static_equals_nullable_datetime_compared_to_non_nullable(a); - AssertSql( - """ + AssertSql( + """ @__arg_0='1996-07-04T00:00:00' SELECT c FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderDate"] = @__arg_0)) """); - } + }); - public override async Task Static_equals_int_compared_to_long(bool async) - { - await base.Static_equals_int_compared_to_long(async); + public override Task Static_equals_int_compared_to_long(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Static_equals_int_compared_to_long(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Order") AND false) """); - } + }); public override async Task Projecting_Math_Truncate_and_ordering_by_it_twice(bool async) { @@ -1439,126 +1584,142 @@ public override async Task Int_Compare_to_simple_zero(bool async) AssertSql(); } - public override async Task Regex_IsMatch_MethodCall(bool async) - { - await base.Regex_IsMatch_MethodCall(async); + public override Task Regex_IsMatch_MethodCall(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Regex_IsMatch_MethodCall(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND RegexMatch(c["CustomerID"], "^T")) """); - } + }); - public override async Task Regex_IsMatch_MethodCall_constant_input(bool async) - { - await base.Regex_IsMatch_MethodCall_constant_input(async); + public override Task Regex_IsMatch_MethodCall_constant_input(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Regex_IsMatch_MethodCall_constant_input(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND RegexMatch("ALFKI", c["CustomerID"])) """); - } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual async Task Regex_IsMatch_MethodCall_With_Option_None(bool async) - { - await AssertQuery( - async, - ss => ss.Set().Where(o => Regex.IsMatch(o.CustomerID, "^T", RegexOptions.None))); + public virtual Task Regex_IsMatch_MethodCall_With_Option_None(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await AssertQuery( + async, + ss => ss.Set().Where(o => Regex.IsMatch(o.CustomerID, "^T", RegexOptions.None))); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND RegexMatch(c["CustomerID"], "^T")) """); - } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual async Task Regex_IsMatch_MethodCall_With_Option_IgnoreCase(bool async) - { - await AssertQuery( - async, - ss => ss.Set().Where(o => Regex.IsMatch(o.CustomerID, "^T", RegexOptions.IgnoreCase))); + public virtual Task Regex_IsMatch_MethodCall_With_Option_IgnoreCase(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await AssertQuery( + async, + ss => ss.Set().Where(o => Regex.IsMatch(o.CustomerID, "^T", RegexOptions.IgnoreCase))); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND RegexMatch(c["CustomerID"], "^T", "i")) """); - } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual async Task Regex_IsMatch_MethodCall_With_Option_Multiline(bool async) - { - await AssertQuery( - async, - ss => ss.Set().Where(o => Regex.IsMatch(o.CustomerID, "^T", RegexOptions.Multiline))); + public virtual Task Regex_IsMatch_MethodCall_With_Option_Multiline(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await AssertQuery( + async, + ss => ss.Set().Where(o => Regex.IsMatch(o.CustomerID, "^T", RegexOptions.Multiline))); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND RegexMatch(c["CustomerID"], "^T", "m")) """); - } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual async Task Regex_IsMatch_MethodCall_With_Option_Singleline(bool async) - { - await AssertQuery( - async, - ss => ss.Set().Where(o => Regex.IsMatch(o.CustomerID, "^T", RegexOptions.Singleline))); + public virtual Task Regex_IsMatch_MethodCall_With_Option_Singleline(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await AssertQuery( + async, + ss => ss.Set().Where(o => Regex.IsMatch(o.CustomerID, "^T", RegexOptions.Singleline))); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND RegexMatch(c["CustomerID"], "^T", "s")) """); - } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual async Task Regex_IsMatch_MethodCall_With_Option_IgnorePatternWhitespace(bool async) - { - await AssertQuery( - async, - ss => ss.Set().Where(o => Regex.IsMatch(o.CustomerID, "^T", RegexOptions.IgnorePatternWhitespace))); + public virtual Task Regex_IsMatch_MethodCall_With_Option_IgnorePatternWhitespace(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await AssertQuery( + async, + ss => ss.Set().Where(o => Regex.IsMatch(o.CustomerID, "^T", RegexOptions.IgnorePatternWhitespace))); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND RegexMatch(c["CustomerID"], "^T", "x")) """); - } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual async Task Regex_IsMatch_MethodCall_With_Options_IgnoreCase_And_IgnorePatternWhitespace(bool async) - { - await AssertQuery( - async, - ss => ss.Set().Where( - o => Regex.IsMatch(o.CustomerID, "^T", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace))); + public virtual Task Regex_IsMatch_MethodCall_With_Options_IgnoreCase_And_IgnorePatternWhitespace(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await AssertQuery( + async, + ss => ss.Set().Where( + o => Regex.IsMatch(o.CustomerID, "^T", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace))); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND RegexMatch(c["CustomerID"], "^T", "ix")) """); - } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] @@ -1579,67 +1740,75 @@ public virtual Task Regex_IsMatch_MethodCall_With_Any_Unsupported_Option(bool as [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual async Task Case_insensitive_string_comparison_instance(bool async) - { - await AssertQuery( - async, - ss => ss.Set().Where(c => c.CustomerID.Equals("alFkI", StringComparison.OrdinalIgnoreCase))); + public virtual Task Case_insensitive_string_comparison_instance(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await AssertQuery( + async, + ss => ss.Set().Where(c => c.CustomerID.Equals("alFkI", StringComparison.OrdinalIgnoreCase))); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND STRINGEQUALS(c["CustomerID"], "alFkI", true)) """); - } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual async Task Case_insensitive_string_comparison_static(bool async) - { - await AssertQuery( - async, - ss => ss.Set().Where(c => string.Equals(c.CustomerID, "alFkI", StringComparison.OrdinalIgnoreCase))); + public virtual Task Case_insensitive_string_comparison_static(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await AssertQuery( + async, + ss => ss.Set().Where(c => string.Equals(c.CustomerID, "alFkI", StringComparison.OrdinalIgnoreCase))); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND STRINGEQUALS(c["CustomerID"], "alFkI", true)) """); - } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual async Task Case_sensitive_string_comparison_instance(bool async) - { - await AssertQuery( - async, - ss => ss.Set().Where(c => c.CustomerID.Equals("ALFKI", StringComparison.Ordinal))); + public virtual Task Case_sensitive_string_comparison_instance(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await AssertQuery( + async, + ss => ss.Set().Where(c => c.CustomerID.Equals("ALFKI", StringComparison.Ordinal))); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND STRINGEQUALS(c["CustomerID"], "ALFKI")) """); - } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual async Task Case_sensitive_string_comparison_static(bool async) - { - await AssertQuery( - async, - ss => ss.Set().Where(c => string.Equals(c.CustomerID, "ALFKI", StringComparison.Ordinal))); + public virtual Task Case_sensitive_string_comparison_static(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await AssertQuery( + async, + ss => ss.Set().Where(c => string.Equals(c.CustomerID, "ALFKI", StringComparison.Ordinal))); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND STRINGEQUALS(c["CustomerID"], "ALFKI")) """); - } + }); public override async Task Datetime_subtraction_TotalDays(bool async) { @@ -1649,67 +1818,77 @@ public override async Task Datetime_subtraction_TotalDays(bool async) AssertSql(); } - public override async Task String_Contains_constant_with_whitespace(bool async) - { - await base.String_Contains_constant_with_whitespace(async); + public override Task String_Contains_constant_with_whitespace(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.String_Contains_constant_with_whitespace(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND CONTAINS(c["ContactName"], " ")) """); - } + }); - public override async Task String_Contains_parameter_with_whitespace(bool async) - { - await base.String_Contains_parameter_with_whitespace(async); + public override Task String_Contains_parameter_with_whitespace(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.String_Contains_parameter_with_whitespace(a); - AssertSql( - """ + AssertSql( + """ @__pattern_0=' ' SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND CONTAINS(c["ContactName"], @__pattern_0)) """); - } + }); - public override async Task Select_mathf_round(bool async) - { - await base.Select_mathf_round(async); + public override Task Select_mathf_round(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_mathf_round(a); - AssertSql( - """ + AssertSql( + """ SELECT c["OrderID"] FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderID"] < 10250)) """); - } + }); - public override async Task Select_mathf_round2(bool async) - { - await base.Select_mathf_round2(async); + public override Task Select_mathf_round2(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_mathf_round2(a); - AssertSql( - """ + AssertSql( + """ SELECT c["UnitPrice"] FROM root c WHERE ((c["Discriminator"] = "OrderDetail") AND (c["Quantity"] < 5)) """); - } + }); - public override async Task Select_mathf_truncate(bool async) - { - await base.Select_mathf_truncate(async); + public override Task Select_mathf_truncate(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_mathf_truncate(a); - AssertSql( - """ + AssertSql( + """ SELECT c["UnitPrice"] FROM root c WHERE ((c["Discriminator"] = "OrderDetail") AND (c["Quantity"] < 5)) """); - } + }); public override Task String_Join_over_non_nullable_column(bool async) => AssertTranslationFailed(() => base.String_Join_over_non_nullable_column(async)); diff --git a/test/EFCore.Cosmos.FunctionalTests/Query/NorthwindKeylessEntitiesQueryCosmosTest.cs b/test/EFCore.Cosmos.FunctionalTests/Query/NorthwindKeylessEntitiesQueryCosmosTest.cs index 935364bc6ff..e1266a09bf3 100644 --- a/test/EFCore.Cosmos.FunctionalTests/Query/NorthwindKeylessEntitiesQueryCosmosTest.cs +++ b/test/EFCore.Cosmos.FunctionalTests/Query/NorthwindKeylessEntitiesQueryCosmosTest.cs @@ -23,42 +23,50 @@ public NorthwindKeylessEntitiesQueryCosmosTest( public virtual void Check_all_tests_overridden() => TestHelpers.AssertAllMethodsOverridden(GetType()); - public override async Task KeylessEntity_simple(bool async) - { - await base.KeylessEntity_simple(async); - - AssertSql( - """ + public override Task KeylessEntity_simple(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.KeylessEntity_simple(a); + + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); - public override async Task KeylessEntity_where_simple(bool async) - { - await base.KeylessEntity_where_simple(async); + public override Task KeylessEntity_where_simple(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.KeylessEntity_where_simple(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["City"] = "London")) """); - } + }); public override async Task KeylessEntity_by_database_view(bool async) { - // Views are not supported. - await Assert.ThrowsAsync( + // Always throws for sync. + if (async) + { + // Views are not supported. + await Assert.ThrowsAsync( () => base.KeylessEntity_by_database_view(async)); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "ProductView") """); + } } public override async Task Entity_mapped_to_view_on_right_side_of_join(bool async) @@ -70,16 +78,20 @@ public override async Task Entity_mapped_to_view_on_right_side_of_join(bool asyn public override async Task KeylessEntity_with_nav_defining_query(bool async) { - // Defining queries are not supported. - await Assert.ThrowsAsync( + // Always throws for sync. + if (async) + { + // Defining queries are not supported. + await Assert.ThrowsAsync( () => base.KeylessEntity_with_nav_defining_query(async)); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["OrderCount"] > 0)) """); + } } public override async Task KeylessEntity_with_mixed_tracking(bool async) @@ -98,17 +110,19 @@ public override async Task KeylessEntity_with_included_nav(bool async) AssertSql(); } - public override async Task KeylessEntity_with_defining_query(bool async) - { - await base.KeylessEntity_with_defining_query(async); + public override Task KeylessEntity_with_defining_query(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.KeylessEntity_with_defining_query(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["CustomerID"] = "ALFKI")) """); - } + }); public override async Task KeylessEntity_with_defining_query_and_correlated_collection(bool async) { @@ -158,37 +172,41 @@ public override async Task Collection_correlated_with_keyless_entity_in_predicat AssertSql(); } - public override async Task Auto_initialized_view_set(bool async) - { - await base.Auto_initialized_view_set(async); + public override Task Auto_initialized_view_set(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Auto_initialized_view_set(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); - public override async Task Count_over_keyless_entity(bool async) - { - await base.Count_over_keyless_entity(async); + public override Task Count_over_keyless_entity(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Count_over_keyless_entity(a); - AssertSql( - """ + AssertSql( + """ SELECT COUNT(1) AS c FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); - public override async Task Count_over_keyless_entity_with_pushdown(bool async) + public override Task Count_over_keyless_entity_with_pushdown(bool async) // Cosmos client evaluation. Issue #17246. - => await AssertTranslationFailed(() => base.Count_over_keyless_entity_with_pushdown(async)); + => AssertTranslationFailed(() => base.Count_over_keyless_entity_with_pushdown(async)); - public override async Task Count_over_keyless_entity_with_pushdown_empty_projection(bool async) + public override Task Count_over_keyless_entity_with_pushdown_empty_projection(bool async) // Cosmos client evaluation. Issue #17246. - => await AssertTranslationFailed(() => base.Count_over_keyless_entity_with_pushdown_empty_projection(async)); + => AssertTranslationFailed(() => base.Count_over_keyless_entity_with_pushdown_empty_projection(async)); private void AssertSql(params string[] expected) => Fixture.TestSqlLoggerFactory.AssertBaseline(expected); diff --git a/test/EFCore.Cosmos.FunctionalTests/Query/NorthwindMiscellaneousQueryCosmosTest.cs b/test/EFCore.Cosmos.FunctionalTests/Query/NorthwindMiscellaneousQueryCosmosTest.cs index 49590339070..3a5a1b51799 100644 --- a/test/EFCore.Cosmos.FunctionalTests/Query/NorthwindMiscellaneousQueryCosmosTest.cs +++ b/test/EFCore.Cosmos.FunctionalTests/Query/NorthwindMiscellaneousQueryCosmosTest.cs @@ -30,35 +30,39 @@ public virtual void Check_all_tests_overridden() [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual async Task Simple_IQueryable(bool async) - { - await AssertQuery(async, ss => ss.Set()); - - AssertSql( - """ + public virtual Task Simple_IQueryable(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await AssertQuery(a, ss => ss.Set()); + + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); - public override async Task Shaper_command_caching_when_parameter_names_different(bool async) - { - await base.Shaper_command_caching_when_parameter_names_different(async); + public override Task Shaper_command_caching_when_parameter_names_different(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Shaper_command_caching_when_parameter_names_different(a); - AssertSql( - """ + AssertSql( + """ SELECT COUNT(1) AS c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = "ALFKI")) """, - // - """ + // + """ SELECT COUNT(1) AS c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = "ALFKI")) """); - } + }); public override async Task Lifting_when_subquery_nested_order_by_anonymous(bool async) { @@ -76,12 +80,14 @@ public override async Task Lifting_when_subquery_nested_order_by_simple(bool asy AssertSql(); } - public override async Task Local_dictionary(bool async) - { - await base.Local_dictionary(async); + public override Task Local_dictionary(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Local_dictionary(a); - AssertSql( - """ + AssertSql( + """ @__p_0='ALFKI' SELECT c @@ -89,40 +95,46 @@ FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = @__p_0)) OFFSET 0 LIMIT 2 """); - } + }); - public override async Task Entity_equality_self(bool async) - { - await base.Entity_equality_self(async); + public override Task Entity_equality_self(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Entity_equality_self(a); - AssertSql( - """ + AssertSql( + """ SELECT c["CustomerID"] FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = c["CustomerID"])) """); - } + }); - public override async Task Entity_equality_local(bool async) - { - await base.Entity_equality_local(async); + public override Task Entity_equality_local(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Entity_equality_local(a); - AssertSql( - """ + AssertSql( + """ @__entity_equality_local_0_CustomerID='ANATR' SELECT c["CustomerID"] FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = @__entity_equality_local_0_CustomerID)) """); - } + }); - public override async Task Entity_equality_local_composite_key(bool async) - { - await base.Entity_equality_local_composite_key(async); + public override Task Entity_equality_local_composite_key(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Entity_equality_local_composite_key(a); - AssertSql( - """ + AssertSql( + """ @__entity_equality_local_0_OrderID='10248' @__entity_equality_local_0_ProductID='11' @@ -130,7 +142,7 @@ SELECT c FROM root c WHERE ((c["Discriminator"] = "OrderDetail") AND ((c["OrderID"] = @__entity_equality_local_0_OrderID) AND (c["ProductID"] = @__entity_equality_local_0_ProductID))) """); - } + }); public override async Task Join_with_entity_equality_local_on_both_sources(bool async) { @@ -140,53 +152,61 @@ public override async Task Join_with_entity_equality_local_on_both_sources(bool AssertSql(); } - public override async Task Entity_equality_local_inline(bool async) - { - await base.Entity_equality_local_inline(async); + public override Task Entity_equality_local_inline(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Entity_equality_local_inline(a); - AssertSql( - """ + AssertSql( + """ SELECT c["CustomerID"] FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = "ANATR")) """); - } + }); - public override async Task Entity_equality_local_inline_composite_key(bool async) - { - await base.Entity_equality_local_inline_composite_key(async); + public override Task Entity_equality_local_inline_composite_key(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Entity_equality_local_inline_composite_key(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "OrderDetail") AND ((c["OrderID"] = 10248) AND (c["ProductID"] = 11))) """); - } + }); - public override async Task Entity_equality_null(bool async) - { - await base.Entity_equality_null(async); + public override Task Entity_equality_null(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Entity_equality_null(a); - AssertSql( - """ + AssertSql( + """ SELECT c["CustomerID"] FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = null)) """); - } + }); - public override async Task Entity_equality_not_null(bool async) - { - await base.Entity_equality_not_null(async); + public override Task Entity_equality_not_null(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Entity_equality_not_null(a); - AssertSql( - """ + AssertSql( + """ SELECT c["CustomerID"] FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] != null)) """); - } + }); public override async Task Query_when_evaluatable_queryable_method_call_with_repository(bool async) { @@ -467,47 +487,59 @@ public override async Task Let_any_subquery_anonymous(bool async) public override async Task OrderBy_arithmetic(bool async) { - // Cosmos client evaluation. Issue #17246. - await Assert.ThrowsAsync( - async () => await base.OrderBy_arithmetic(async)); + // Always throws for sync. + if (async) + { + // Cosmos client evaluation. Issue #17246. + await Assert.ThrowsAsync( + async () => await base.OrderBy_arithmetic(async)); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Employee") ORDER BY (c["EmployeeID"] - c["EmployeeID"]) """); + } } public override async Task OrderBy_condition_comparison(bool async) { - // Cosmos client evaluation. Issue #17246. - await Assert.ThrowsAsync( - async () => await base.OrderBy_condition_comparison(async)); + // Always throws for sync. + if (async) + { + // Cosmos client evaluation. Issue #17246. + await Assert.ThrowsAsync( + async () => await base.OrderBy_condition_comparison(async)); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Product") ORDER BY (c["UnitsInStock"] > 0), c["ProductID"] """); + } } public override async Task OrderBy_ternary_conditions(bool async) { - // Cosmos client evaluation. Issue #17246. - await Assert.ThrowsAsync( - async () => await base.OrderBy_ternary_conditions(async)); + // Always throws for sync. + if (async) + { + // Cosmos client evaluation. Issue #17246. + await Assert.ThrowsAsync( + async () => await base.OrderBy_ternary_conditions(async)); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Product") ORDER BY ((c["UnitsInStock"] > 10) ? (c["ProductID"] > 40) : (c["ProductID"] <= 40)), c["ProductID"] """); + } } public override async Task OrderBy_any(bool async) @@ -538,12 +570,14 @@ public override async Task Skip_no_orderby(bool async) AssertSql(); } - public override async Task Skip_Take(bool async) - { - await base.Skip_Take(async); + public override Task Skip_Take(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Skip_Take(a); - AssertSql( - """ + AssertSql( + """ @__p_0='5' @__p_1='10' @@ -553,7 +587,7 @@ FROM root c ORDER BY c["ContactName"] OFFSET @__p_0 LIMIT @__p_1 """); - } + }); public override async Task Join_Customers_Orders_Skip_Take(bool async) { @@ -633,48 +667,56 @@ public override async Task Take_Where_Distinct_Count(bool async) AssertSql(); } - public override async Task Queryable_simple(bool async) - { - await base.Queryable_simple(async); + public override Task Queryable_simple(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Queryable_simple(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); - public override async Task Queryable_simple_anonymous(bool async) - { - await base.Queryable_simple_anonymous(async); + public override Task Queryable_simple_anonymous(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Queryable_simple_anonymous(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); - public override async Task Queryable_nested_simple(bool async) - { - await base.Queryable_nested_simple(async); + public override Task Queryable_nested_simple(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Queryable_nested_simple(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); - public override async Task Queryable_simple_anonymous_projection_subquery(bool async) - { - await base.Queryable_simple_anonymous_projection_subquery(async); + public override Task Queryable_simple_anonymous_projection_subquery(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Queryable_simple_anonymous_projection_subquery(a); - AssertSql( - """ + AssertSql( + """ @__p_0='91' SELECT c["City"] @@ -682,14 +724,16 @@ FROM root c WHERE (c["Discriminator"] = "Customer") OFFSET 0 LIMIT @__p_0 """); - } + }); - public override async Task Queryable_simple_anonymous_subquery(bool async) - { - await base.Queryable_simple_anonymous_subquery(async); + public override Task Queryable_simple_anonymous_subquery(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Queryable_simple_anonymous_subquery(a); - AssertSql( - """ + AssertSql( + """ @__p_0='91' SELECT c @@ -697,14 +741,16 @@ FROM root c WHERE (c["Discriminator"] = "Customer") OFFSET 0 LIMIT @__p_0 """); - } + }); - public override async Task Take_simple(bool async) - { - await base.Take_simple(async); + public override Task Take_simple(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Take_simple(a); - AssertSql( - """ + AssertSql( + """ @__p_0='10' SELECT c @@ -713,14 +759,16 @@ FROM root c ORDER BY c["CustomerID"] OFFSET 0 LIMIT @__p_0 """); - } + }); - public override async Task Take_simple_parameterized(bool async) - { - await base.Take_simple_parameterized(async); + public override Task Take_simple_parameterized(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Take_simple_parameterized(a); - AssertSql( - """ + AssertSql( + """ @__p_0='10' SELECT c @@ -729,14 +777,16 @@ FROM root c ORDER BY c["CustomerID"] OFFSET 0 LIMIT @__p_0 """); - } + }); - public override async Task Take_simple_projection(bool async) - { - await base.Take_simple_projection(async); + public override Task Take_simple_projection(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Take_simple_projection(a); - AssertSql( - """ + AssertSql( + """ @__p_0='10' SELECT c["City"] @@ -745,14 +795,16 @@ FROM root c ORDER BY c["CustomerID"] OFFSET 0 LIMIT @__p_0 """); - } + }); - public override async Task Take_subquery_projection(bool async) - { - await base.Take_subquery_projection(async); + public override Task Take_subquery_projection(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Take_subquery_projection(a); - AssertSql( - """ + AssertSql( + """ @__p_0='2' SELECT c["City"] @@ -761,7 +813,7 @@ FROM root c ORDER BY c["CustomerID"] OFFSET 0 LIMIT @__p_0 """); - } + }); public override async Task OrderBy_Take_Count(bool async) { @@ -1215,12 +1267,14 @@ public override async Task Skip_Distinct(bool async) AssertSql(); } - public override async Task Skip_Take_Distinct(bool async) - { - await base.Skip_Take_Distinct(async); + public override Task Skip_Take_Distinct(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Skip_Take_Distinct(a); - AssertSql( - """ + AssertSql( + """ @__p_0='5' @__p_1='10' @@ -1230,7 +1284,7 @@ FROM root c ORDER BY c["ContactName"] OFFSET @__p_0 LIMIT @__p_1 """); - } + }); public override async Task Skip_Take_Any(bool async) { @@ -1272,57 +1326,70 @@ public override async Task Take_Any_with_predicate(bool async) AssertSql(); } - public override async Task OrderBy(bool async) - { - await base.OrderBy(async); + public override Task OrderBy(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.OrderBy(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Customer") ORDER BY c["CustomerID"] """); - } + }); public override async Task OrderBy_true(bool async) { - // Cosmos client evaluation. Issue #17246. - await Assert.ThrowsAsync( - async () => await base.OrderBy_true(async)); + // Always throws for sync. + if (async) + { + // Cosmos client evaluation. Issue #17246. + await Assert.ThrowsAsync( + async () => await base.OrderBy_true(async)); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Customer") ORDER BY true """); + } } public override async Task OrderBy_integer(bool async) { - // Cosmos client evaluation. Issue #17246. - await Assert.ThrowsAsync( - async () => await base.OrderBy_integer(async)); + // Always throws for sync. + if (async) + { + // Cosmos client evaluation. Issue #17246. + await Assert.ThrowsAsync( + async () => await base.OrderBy_integer(async)); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Customer") ORDER BY 3 """); + } } public override async Task OrderBy_parameter(bool async) { - // Cosmos client evaluation. Issue #17246. - await Assert.ThrowsAsync( - async () => await base.OrderBy_parameter(async)); + // Always throws for sync. + if (async) + { + // Cosmos client evaluation. Issue #17246. + await Assert.ThrowsAsync( + async () => await base.OrderBy_parameter(async)); - AssertSql( - """ + AssertSql( + """ @__param_0='5' SELECT c @@ -1330,33 +1397,38 @@ FROM root c WHERE (c["Discriminator"] = "Customer") ORDER BY @__param_0 """); + } } - public override async Task OrderBy_anon(bool async) - { - await base.OrderBy_anon(async); + public override Task OrderBy_anon(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.OrderBy_anon(a); - AssertSql( - """ + AssertSql( + """ SELECT c["CustomerID"] FROM root c WHERE (c["Discriminator"] = "Customer") ORDER BY c["CustomerID"] """); - } + }); - public override async Task OrderBy_anon2(bool async) - { - await base.OrderBy_anon2(async); + public override Task OrderBy_anon2(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.OrderBy_anon2(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Customer") ORDER BY c["CustomerID"] """); - } + }); public override async Task OrderBy_client_mixed(bool async) { @@ -1372,12 +1444,14 @@ public override async Task OrderBy_multiple_queries(bool async) AssertSql(); } - public override async Task Take_Distinct(bool async) - { - await base.Take_Distinct(async); + public override Task Take_Distinct(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Take_Distinct(a); - AssertSql( - """ + AssertSql( + """ @__p_0='5' SELECT DISTINCT c @@ -1386,7 +1460,7 @@ FROM root c ORDER BY c["OrderID"] OFFSET 0 LIMIT @__p_0 """); - } + }); public override async Task Distinct_Take(bool async) { @@ -1408,32 +1482,40 @@ public override async Task Distinct_Take_Count(bool async) public override async Task OrderBy_shadow(bool async) { - // Cosmos client evaluation. Issue #17246. - await Assert.ThrowsAsync( - async () => await base.OrderBy_shadow(async)); + // Always throws for sync. + if (async) + { + // Cosmos client evaluation. Issue #17246. + await Assert.ThrowsAsync( + async () => await base.OrderBy_shadow(async)); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Employee") ORDER BY c["Title"], c["EmployeeID"] """); + } } public override async Task OrderBy_multiple(bool async) { - // Cosmos client evaluation. Issue #17246. - await Assert.ThrowsAsync( - async () => await base.OrderBy_multiple(async)); + // Always throws for sync. + if (async) + { + // Cosmos client evaluation. Issue #17246. + await Assert.ThrowsAsync( + async () => await base.OrderBy_multiple(async)); - AssertSql( - """ + AssertSql( + """ SELECT c["City"] FROM root c WHERE ((c["Discriminator"] = "Customer") AND STARTSWITH(c["CustomerID"], "A")) ORDER BY c["Country"], c["City"] """); + } } public override async Task OrderBy_ThenBy_Any(bool async) @@ -1475,74 +1557,88 @@ public override async Task Where_query_composition4(bool async) AssertSql(); } - public override async Task Where_subquery_expression(bool async) - { - // Cosmos client evaluation. Issue #17246. - Assert.Equal( - CoreStrings.ExpressionParameterizationExceptionSensitive( - "value(Microsoft.EntityFrameworkCore.Query.NorthwindMiscellaneousQueryTestBase`1+<>c__DisplayClass107_0[Microsoft.EntityFrameworkCore.Query.NorthwindQueryCosmosFixture`1[Microsoft.EntityFrameworkCore.TestUtilities.NoopModelCustomizer]]).ss.Set().Where(value(Microsoft.EntityFrameworkCore.Query.NorthwindMiscellaneousQueryTestBase`1+<>c__DisplayClass107_0[Microsoft.EntityFrameworkCore.Query.NorthwindQueryCosmosFixture`1[Microsoft.EntityFrameworkCore.TestUtilities.NoopModelCustomizer]]).expr).Any()"), - (await Assert.ThrowsAsync( - () => base.Where_subquery_expression(async))).Message); + [ConditionalTheory(Skip = "Always does sync evaluation.")] + public override Task Where_subquery_expression(bool async) + => Fixture.NoSyncTest( + async, async a => + { + // Cosmos client evaluation. Issue #17246. + Assert.Equal( + CoreStrings.ExpressionParameterizationExceptionSensitive( + "value(Microsoft.EntityFrameworkCore.Query.NorthwindMiscellaneousQueryTestBase`1+<>c__DisplayClass107_0[Microsoft.EntityFrameworkCore.Query.NorthwindQueryCosmosFixture`1[Microsoft.EntityFrameworkCore.TestUtilities.NoopModelCustomizer]]).ss.Set().Where(value(Microsoft.EntityFrameworkCore.Query.NorthwindMiscellaneousQueryTestBase`1+<>c__DisplayClass107_0[Microsoft.EntityFrameworkCore.Query.NorthwindQueryCosmosFixture`1[Microsoft.EntityFrameworkCore.TestUtilities.NoopModelCustomizer]]).expr).Any()"), + (await Assert.ThrowsAsync( + () => base.Where_subquery_expression(async))).Message); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Order") OFFSET 0 LIMIT 1 """); - } + }); + [ConditionalTheory(Skip = "Always does sync evaluation.")] public override async Task Where_subquery_expression_same_parametername(bool async) { - // Cosmos client evaluation. Issue #17246. - await AssertTranslationFailed(() => base.Where_subquery_expression_same_parametername(async)); + // Always throws + if (async) + { + // Cosmos client evaluation. Issue #17246. + await AssertTranslationFailed(() => base.Where_subquery_expression_same_parametername(async)); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Order") ORDER BY c["OrderID"] OFFSET 0 LIMIT 1 """); + } } - public override async Task Select_DTO_distinct_translated_to_server(bool async) - { - await base.Select_DTO_distinct_translated_to_server(async); + public override Task Select_DTO_distinct_translated_to_server(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_DTO_distinct_translated_to_server(a); - AssertSql( - """ + AssertSql( + """ SELECT DISTINCT 1 FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderID"] < 10300)) """); - } + }); - public override async Task Select_DTO_constructor_distinct_translated_to_server(bool async) - { - await base.Select_DTO_constructor_distinct_translated_to_server(async); + public override Task Select_DTO_constructor_distinct_translated_to_server(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_DTO_constructor_distinct_translated_to_server(a); - AssertSql( - """ + AssertSql( + """ SELECT DISTINCT c["CustomerID"] FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderID"] < 10300)) """); - } + }); - public override async Task Select_DTO_with_member_init_distinct_translated_to_server(bool async) - { - await base.Select_DTO_with_member_init_distinct_translated_to_server(async); + public override Task Select_DTO_with_member_init_distinct_translated_to_server(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_DTO_with_member_init_distinct_translated_to_server(a); - AssertSql( - """ + AssertSql( + """ SELECT DISTINCT VALUE {"Id" : c["CustomerID"], "Count" : c["OrderID"]} FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderID"] < 10300)) """); - } + }); public override async Task Select_nested_collection_count_using_DTO(bool async) { @@ -1627,100 +1723,122 @@ public override async Task Select_many_cross_join_same_collection(bool async) public override async Task OrderBy_null_coalesce_operator(bool async) { - // Cosmos client evaluation. Issue #17246. - await Assert.ThrowsAsync( - async () => await base.OrderBy_null_coalesce_operator(async)); + // Always throws for sync. + if (async) + { + // Cosmos client evaluation. Issue #17246. + await Assert.ThrowsAsync( + async () => await base.OrderBy_null_coalesce_operator(async)); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Customer") ORDER BY ((c["Region"] != null) ? c["Region"] : "ZZ"), c["CustomerID"] """); + } } public override async Task Select_null_coalesce_operator(bool async) { - // Cosmos client evaluation. Issue #17246. - await Assert.ThrowsAsync( - async () => await base.Select_null_coalesce_operator(async)); + // Always throws for sync. + if (async) + { + // Cosmos client evaluation. Issue #17246. + await Assert.ThrowsAsync( + async () => await base.Select_null_coalesce_operator(async)); - AssertSql( - """ + AssertSql( + """ SELECT VALUE {"CustomerID" : c["CustomerID"], "CompanyName" : c["CompanyName"], "Region" : ((c["Region"] != null) ? c["Region"] : "ZZ")} FROM root c WHERE (c["Discriminator"] = "Customer") ORDER BY ((c["Region"] != null) ? c["Region"] : "ZZ"), c["CustomerID"] """); + } } public override async Task OrderBy_conditional_operator(bool async) { - // Cosmos client evaluation. Issue #17246. - await Assert.ThrowsAsync( - async () => await base.OrderBy_conditional_operator(async)); + // Always throws for sync. + if (async) + { + // Cosmos client evaluation. Issue #17246. + await Assert.ThrowsAsync( + async () => await base.OrderBy_conditional_operator(async)); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Customer") ORDER BY ((c["Region"] = null) ? "ZZ" : c["Region"]), c["CustomerID"] """); + } } - public override async Task OrderBy_conditional_operator_where_condition_false(bool async) - { - await base.OrderBy_conditional_operator_where_condition_false(async); + public override Task OrderBy_conditional_operator_where_condition_false(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.OrderBy_conditional_operator_where_condition_false(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Customer") ORDER BY c["City"] """); - } + }); public override async Task OrderBy_comparison_operator(bool async) { - // Cosmos client evaluation. Issue #17246. - await Assert.ThrowsAsync( - async () => await base.OrderBy_comparison_operator(async)); + // Always throws for sync. + if (async) + { + // Cosmos client evaluation. Issue #17246. + await Assert.ThrowsAsync( + async () => await base.OrderBy_comparison_operator(async)); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Customer") ORDER BY (c["Region"] = "ASK") """); + } } - public override async Task Projection_null_coalesce_operator(bool async) - { - await base.Projection_null_coalesce_operator(async); + public override Task Projection_null_coalesce_operator(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Projection_null_coalesce_operator(a); - AssertSql( - """ + AssertSql( + """ SELECT VALUE {"CustomerID" : c["CustomerID"], "CompanyName" : c["CompanyName"], "Region" : ((c["Region"] != null) ? c["Region"] : "ZZ")} FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); - public override async Task Filter_coalesce_operator(bool async) - { - await base.Filter_coalesce_operator(async); + public override Task Filter_coalesce_operator(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Filter_coalesce_operator(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (((c["CompanyName"] != null) ? c["CompanyName"] : c["ContactName"]) = "The Big Cheese")) """); - } + }); public override async Task Take_skip_null_coalesce_operator(bool async) { @@ -1734,12 +1852,15 @@ await AssertTranslationFailedWithDetails( public override async Task Select_take_null_coalesce_operator(bool async) { - // Subquery pushdown. Issue #16156. - await Assert.ThrowsAsync( - async () => await base.Select_take_null_coalesce_operator(async)); + // Always throws for sync. + if (async) + { + // Subquery pushdown. Issue #16156. + await Assert.ThrowsAsync( + async () => await base.Select_take_null_coalesce_operator(async)); - AssertSql( - """ + AssertSql( + """ @__p_0='5' SELECT VALUE {"CustomerID" : c["CustomerID"], "CompanyName" : c["CompanyName"], "Region" : ((c["Region"] != null) ? c["Region"] : "ZZ")} @@ -1748,6 +1869,7 @@ FROM root c ORDER BY ((c["Region"] != null) ? c["Region"] : "ZZ") OFFSET 0 LIMIT @__p_0 """); + } } public override async Task Select_take_skip_null_coalesce_operator(bool async) @@ -1782,78 +1904,90 @@ await AssertTranslationFailedWithDetails( public override async Task Selected_column_can_coalesce(bool async) { - // Unsupported ORDER BY clause. - await Assert.ThrowsAsync( - () => base.Selected_column_can_coalesce(async)); + // Always throws for sync. + if (async) + { + // Unsupported ORDER BY clause. + await Assert.ThrowsAsync( + () => base.Selected_column_can_coalesce(async)); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Customer") ORDER BY ((c["Region"] != null) ? c["Region"] : "ZZ") """); + } } - public override async Task DateTime_parse_is_inlined(bool async) - { - await base.DateTime_parse_is_inlined(async); + public override Task DateTime_parse_is_inlined(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.DateTime_parse_is_inlined(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderDate"] > "1998-01-01T12:00:00")) """); - } + }); - public override async Task DateTime_parse_is_parameterized_when_from_closure(bool async) - { - await base.DateTime_parse_is_parameterized_when_from_closure(async); + public override Task DateTime_parse_is_parameterized_when_from_closure(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.DateTime_parse_is_parameterized_when_from_closure(a); - AssertSql( - """ + AssertSql( + """ @__Parse_0='1998-01-01T12:00:00' SELECT c FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderDate"] > @__Parse_0)) """); - } + }); - public override async Task New_DateTime_is_inlined(bool async) - { - await base.New_DateTime_is_inlined(async); + public override Task New_DateTime_is_inlined(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.New_DateTime_is_inlined(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderDate"] > "1998-01-01T12:00:00")) """); - } + }); - public override async Task New_DateTime_is_parameterized_when_from_closure(bool async) - { - await base.New_DateTime_is_parameterized_when_from_closure(async); + public override Task New_DateTime_is_parameterized_when_from_closure(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.New_DateTime_is_parameterized_when_from_closure(a); - AssertSql( - """ + AssertSql( + """ @__p_0='1998-01-01T12:00:00' SELECT c FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderDate"] > @__p_0)) """, - // - """ + // + """ @__p_0='1998-01-01T11:00:00' SELECT c FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderDate"] > @__p_0)) """); - } + }); public override async Task Random_next_is_not_funcletized_1(bool async) { @@ -1903,22 +2037,24 @@ public override async Task Random_next_is_not_funcletized_6(bool async) AssertSql(); } - public override async Task Environment_newline_is_funcletized(bool async) - { - await base.Environment_newline_is_funcletized(async); + public override Task Environment_newline_is_funcletized(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Environment_newline_is_funcletized(a); - var sql = Fixture.TestSqlLoggerFactory.SqlStatements[0]; - Assert.StartsWith("@__NewLine_0='", sql); - Assert.EndsWith( - """ + var sql = Fixture.TestSqlLoggerFactory.SqlStatements[0]; + Assert.StartsWith("@__NewLine_0='", sql); + Assert.EndsWith( + """ ' SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND CONTAINS(c["CustomerID"], @__NewLine_0)) """, - sql); - } + sql); + }); public override async Task String_concat_with_navigation1(bool async) { @@ -1938,174 +2074,216 @@ public override async Task String_concat_with_navigation2(bool async) public override async Task Select_bitwise_or(bool async) { - // Bitwise operators on booleans. Issue #13168. - await Assert.ThrowsAsync(() => base.Select_bitwise_or(async)); + // Always throws for sync. + if (async) + { + // Bitwise operators on booleans. Issue #13168. + await Assert.ThrowsAsync(() => base.Select_bitwise_or(async)); - AssertSql( - """ + AssertSql( + """ SELECT VALUE {"CustomerID" : c["CustomerID"], "Value" : ((c["CustomerID"] = "ALFKI") | (c["CustomerID"] = "ANATR"))} FROM root c WHERE (c["Discriminator"] = "Customer") ORDER BY c["CustomerID"] """); + } } public override async Task Select_bitwise_or_multiple(bool async) { - // Bitwise operators on booleans. Issue #13168. - await Assert.ThrowsAsync(() => base.Select_bitwise_or_multiple(async)); + // Always throws for sync. + if (async) + { + // Bitwise operators on booleans. Issue #13168. + await Assert.ThrowsAsync(() => base.Select_bitwise_or_multiple(async)); - AssertSql( - """ + AssertSql( + """ SELECT VALUE {"CustomerID" : c["CustomerID"], "Value" : (((c["CustomerID"] = "ALFKI") | (c["CustomerID"] = "ANATR")) | (c["CustomerID"] = "ANTON"))} FROM root c WHERE (c["Discriminator"] = "Customer") ORDER BY c["CustomerID"] """); + } } public override async Task Select_bitwise_and(bool async) { - // Bitwise operators on booleans. Issue #13168. - await Assert.ThrowsAsync(() => base.Select_bitwise_and(async)); + // Always throws for sync. + if (async) + { + // Bitwise operators on booleans. Issue #13168. + await Assert.ThrowsAsync(() => base.Select_bitwise_and(async)); - AssertSql( - """ + AssertSql( + """ SELECT VALUE {"CustomerID" : c["CustomerID"], "Value" : ((c["CustomerID"] = "ALFKI") & (c["CustomerID"] = "ANATR"))} FROM root c WHERE (c["Discriminator"] = "Customer") ORDER BY c["CustomerID"] """); + } } public override async Task Select_bitwise_and_or(bool async) { - // Bitwise operators on booleans. Issue #13168. - await Assert.ThrowsAsync(() => base.Select_bitwise_and_or(async)); + // Always throws for sync. + if (async) + { + // Bitwise operators on booleans. Issue #13168. + await Assert.ThrowsAsync(() => base.Select_bitwise_and_or(async)); - AssertSql( - """ + AssertSql( + """ SELECT VALUE {"CustomerID" : c["CustomerID"], "Value" : (((c["CustomerID"] = "ALFKI") & (c["CustomerID"] = "ANATR")) | (c["CustomerID"] = "ANTON"))} FROM root c WHERE (c["Discriminator"] = "Customer") ORDER BY c["CustomerID"] """); + } } public override async Task Where_bitwise_or_with_logical_or(bool async) { - // Bitwise operators on booleans. Issue #13168. - await Assert.ThrowsAsync(() => base.Where_bitwise_or_with_logical_or(async)); + // Always throws for sync. + if (async) + { + // Bitwise operators on booleans. Issue #13168. + await Assert.ThrowsAsync(() => base.Where_bitwise_or_with_logical_or(async)); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (((c["CustomerID"] = "ALFKI") | (c["CustomerID"] = "ANATR")) OR (c["CustomerID"] = "ANTON"))) """); + } } - public override async Task Where_bitwise_and_with_logical_and(bool async) - { - await base.Where_bitwise_and_with_logical_and(async); + public override Task Where_bitwise_and_with_logical_and(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_bitwise_and_with_logical_and(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (((c["CustomerID"] = "ALFKI") & (c["CustomerID"] = "ANATR")) AND (c["CustomerID"] = "ANTON"))) """); - } + }); public override async Task Where_bitwise_or_with_logical_and(bool async) { - // Bitwise operators on booleans. Issue #13168. - await Assert.ThrowsAsync(() => base.Where_bitwise_or_with_logical_and(async)); + // Always throws for sync. + if (async) + { + // Bitwise operators on booleans. Issue #13168. + await Assert.ThrowsAsync(() => base.Where_bitwise_or_with_logical_and(async)); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (((c["CustomerID"] = "ALFKI") | (c["CustomerID"] = "ANATR")) AND (c["Country"] = "Germany"))) """); + } } - public override async Task Where_bitwise_and_with_logical_or(bool async) - { - await base.Where_bitwise_and_with_logical_or(async); + public override Task Where_bitwise_and_with_logical_or(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_bitwise_and_with_logical_or(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (((c["CustomerID"] = "ALFKI") & (c["CustomerID"] = "ANATR")) OR (c["CustomerID"] = "ANTON"))) """); - } + }); - public override async Task Where_bitwise_binary_not(bool async) - { - await base.Where_bitwise_binary_not(async); + public override Task Where_bitwise_binary_not(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_bitwise_binary_not(a); - AssertSql( - """ + AssertSql( + """ @__negatedId_0='-10249' SELECT c FROM root c WHERE ((c["Discriminator"] = "Order") AND (~(c["OrderID"]) = @__negatedId_0)) """); - } + }); - public override async Task Where_bitwise_binary_and(bool async) - { - await base.Where_bitwise_binary_and(async); + public override Task Where_bitwise_binary_and(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_bitwise_binary_and(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Order") AND ((c["OrderID"] & 10248) = 10248)) """); - } + }); - public override async Task Where_bitwise_binary_or(bool async) - { - await base.Where_bitwise_binary_or(async); + public override Task Where_bitwise_binary_or(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_bitwise_binary_or(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Order") AND ((c["OrderID"] | 10248) = 10248)) """); - } + }); public override async Task Select_bitwise_or_with_logical_or(bool async) { - // Bitwise operators on booleans. Issue #13168. - await Assert.ThrowsAsync(() => base.Select_bitwise_or_with_logical_or(async)); + // Always throws for sync. + if (async) + { + // Bitwise operators on booleans. Issue #13168. + await Assert.ThrowsAsync(() => base.Select_bitwise_or_with_logical_or(async)); - AssertSql( - """ + AssertSql( + """ SELECT VALUE {"CustomerID" : c["CustomerID"], "Value" : (((c["CustomerID"] = "ALFKI") | (c["CustomerID"] = "ANATR")) OR (c["CustomerID"] = "ANTON"))} FROM root c WHERE (c["Discriminator"] = "Customer") ORDER BY c["CustomerID"] """); + } } public override async Task Select_bitwise_and_with_logical_and(bool async) { - // Bitwise operators on booleans. Issue #13168. - await Assert.ThrowsAsync(() => base.Select_bitwise_and_with_logical_and(async)); + // Always throws for sync. + if (async) + { + // Bitwise operators on booleans. Issue #13168. + await Assert.ThrowsAsync(() => base.Select_bitwise_and_with_logical_and(async)); - AssertSql( - """ + AssertSql( + """ SELECT VALUE {"CustomerID" : c["CustomerID"], "Value" : (((c["CustomerID"] = "ALFKI") & (c["CustomerID"] = "ANATR")) AND (c["CustomerID"] = "ANTON"))} FROM root c WHERE (c["Discriminator"] = "Customer") ORDER BY c["CustomerID"] """); + } } public override async Task Handle_materialization_properly_when_more_than_two_query_sources_are_involved(bool async) @@ -2156,168 +2334,194 @@ public override async Task Query_expression_with_to_string_and_contains(bool asy AssertSql(); } - public override async Task Select_expression_long_to_string(bool async) - { - await base.Select_expression_long_to_string(async); + public override Task Select_expression_long_to_string(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_expression_long_to_string(a); - AssertSql( - """ + AssertSql( + """ SELECT c["OrderID"] FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderDate"] != null)) """); - } + }); - public override async Task Select_expression_int_to_string(bool async) - { - await base.Select_expression_int_to_string(async); + public override Task Select_expression_int_to_string(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_expression_int_to_string(a); - AssertSql( - """ + AssertSql( + """ SELECT c["OrderID"] FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderDate"] != null)) """); - } + }); - public override async Task ToString_with_formatter_is_evaluated_on_the_client(bool async) - { - await base.ToString_with_formatter_is_evaluated_on_the_client(async); + public override Task ToString_with_formatter_is_evaluated_on_the_client(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.ToString_with_formatter_is_evaluated_on_the_client(a); - AssertSql( - """ + AssertSql( + """ SELECT c["OrderID"] FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderDate"] != null)) """, - // - """ + // + """ SELECT c["OrderID"] FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderDate"] != null)) """); - } + }); - public override async Task Select_expression_other_to_string(bool async) - { - await base.Select_expression_other_to_string(async); + public override Task Select_expression_other_to_string(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_expression_other_to_string(a); - AssertSql( - """ + AssertSql( + """ SELECT c["OrderDate"] FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderDate"] != null)) """); - } + }); - public override async Task Select_expression_date_add_year(bool async) - { - await base.Select_expression_date_add_year(async); + public override Task Select_expression_date_add_year(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_expression_date_add_year(a); - AssertSql( - """ + AssertSql( + """ SELECT c["OrderDate"] FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderDate"] != null)) """); - } + }); - public override async Task Select_expression_datetime_add_month(bool async) - { - await base.Select_expression_datetime_add_month(async); + public override Task Select_expression_datetime_add_month(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_expression_datetime_add_month(a); - AssertSql( - """ + AssertSql( + """ SELECT c["OrderDate"] FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderDate"] != null)) """); - } + }); - public override async Task Select_expression_datetime_add_hour(bool async) - { - await base.Select_expression_datetime_add_hour(async); + public override Task Select_expression_datetime_add_hour(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_expression_datetime_add_hour(a); - AssertSql( - """ + AssertSql( + """ SELECT c["OrderDate"] FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderDate"] != null)) """); - } + }); - public override async Task Select_expression_datetime_add_minute(bool async) - { - await base.Select_expression_datetime_add_minute(async); + public override Task Select_expression_datetime_add_minute(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_expression_datetime_add_minute(a); - AssertSql( - """ + AssertSql( + """ SELECT c["OrderDate"] FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderDate"] != null)) """); - } + }); - public override async Task Select_expression_datetime_add_second(bool async) - { - await base.Select_expression_datetime_add_second(async); + public override Task Select_expression_datetime_add_second(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_expression_datetime_add_second(a); - AssertSql( - """ + AssertSql( + """ SELECT c["OrderDate"] FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderDate"] != null)) """); - } + }); - public override async Task Select_expression_date_add_milliseconds_above_the_range(bool async) - { - await base.Select_expression_date_add_milliseconds_above_the_range(async); + public override Task Select_expression_date_add_milliseconds_above_the_range(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_expression_date_add_milliseconds_above_the_range(a); - AssertSql( - """ + AssertSql( + """ SELECT c["OrderDate"] FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderDate"] != null)) """); - } + }); - public override async Task Select_expression_date_add_milliseconds_below_the_range(bool async) - { - await base.Select_expression_date_add_milliseconds_below_the_range(async); + public override Task Select_expression_date_add_milliseconds_below_the_range(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_expression_date_add_milliseconds_below_the_range(a); - AssertSql( - """ + AssertSql( + """ SELECT c["OrderDate"] FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderDate"] != null)) """); - } + }); - public override async Task Select_expression_date_add_milliseconds_large_number_divided(bool async) - { - await base.Select_expression_date_add_milliseconds_large_number_divided(async); + public override Task Select_expression_date_add_milliseconds_large_number_divided(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_expression_date_add_milliseconds_large_number_divided(a); - AssertSql( - """ + AssertSql( + """ SELECT c["OrderDate"] FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderDate"] != null)) """); - } + }); - public override async Task Add_minutes_on_constant_value(bool async) - { - await base.Add_minutes_on_constant_value(async); + public override Task Add_minutes_on_constant_value(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Add_minutes_on_constant_value(a); - AssertSql( - """ + AssertSql( + """ SELECT VALUE {"c" : (c["OrderID"] % 25)} FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderID"] < 10500)) ORDER BY c["OrderID"] """); - } + }); public override async Task Select_expression_references_are_updated_correctly_with_subquery(bool async) { @@ -2369,12 +2573,15 @@ public override async Task DefaultIfEmpty_in_subquery_nested_filter_order_compar public override async Task OrderBy_skip_take(bool async) { - // Cosmos client evaluation. Issue #17246. - await Assert.ThrowsAsync( - async () => await base.OrderBy_skip_take(async)); + // Always throws for sync. + if (async) + { + // Cosmos client evaluation. Issue #17246. + await Assert.ThrowsAsync( + async () => await base.OrderBy_skip_take(async)); - AssertSql( - """ + AssertSql( + """ @__p_0='5' @__p_1='8' @@ -2384,6 +2591,7 @@ FROM root c ORDER BY c["ContactTitle"], c["ContactName"] OFFSET @__p_0 LIMIT @__p_1 """); + } } public override async Task OrderBy_skip_skip_take(bool async) @@ -2428,12 +2636,15 @@ await AssertTranslationFailedWithDetails( public override async Task OrderBy_skip_take_distinct(bool async) { - // Cosmos client evaluation. Issue #17246. - await Assert.ThrowsAsync( - async () => await base.OrderBy_skip_take_distinct(async)); + // Always throws for sync. + if (async) + { + // Cosmos client evaluation. Issue #17246. + await Assert.ThrowsAsync( + async () => await base.OrderBy_skip_take_distinct(async)); - AssertSql( - """ + AssertSql( + """ @__p_0='5' @__p_1='15' @@ -2443,16 +2654,20 @@ FROM root c ORDER BY c["ContactTitle"], c["ContactName"] OFFSET @__p_0 LIMIT @__p_1 """); + } } public override async Task OrderBy_coalesce_take_distinct(bool async) { - // Cosmos client evaluation. Issue #17246. - await Assert.ThrowsAsync( - async () => await base.OrderBy_coalesce_take_distinct(async)); + // Always throws for sync. + if (async) + { + // Cosmos client evaluation. Issue #17246. + await Assert.ThrowsAsync( + async () => await base.OrderBy_coalesce_take_distinct(async)); - AssertSql( - """ + AssertSql( + """ @__p_0='15' SELECT DISTINCT c @@ -2461,16 +2676,20 @@ FROM root c ORDER BY ((c["UnitPrice"] != null) ? c["UnitPrice"] : 0.0) OFFSET 0 LIMIT @__p_0 """); + } } public override async Task OrderBy_coalesce_skip_take_distinct(bool async) { - // Cosmos client evaluation. Issue #17246. - await Assert.ThrowsAsync( - async () => await base.OrderBy_coalesce_skip_take_distinct(async)); + // Always throws for sync. + if (async) + { + // Cosmos client evaluation. Issue #17246. + await Assert.ThrowsAsync( + async () => await base.OrderBy_coalesce_skip_take_distinct(async)); - AssertSql( - """ + AssertSql( + """ @__p_0='5' @__p_1='15' @@ -2480,6 +2699,7 @@ FROM root c ORDER BY ((c["UnitPrice"] != null) ? c["UnitPrice"] : 0.0) OFFSET @__p_0 LIMIT @__p_1 """); + } } public override async Task OrderBy_coalesce_skip_take_distinct_take(bool async) @@ -2572,17 +2792,19 @@ public override async Task Complex_query_with_repeated_nested_query_model_compil AssertSql(); } - public override async Task Anonymous_member_distinct_where(bool async) - { - await base.Anonymous_member_distinct_where(async); + public override Task Anonymous_member_distinct_where(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Anonymous_member_distinct_where(a); - AssertSql( - """ + AssertSql( + """ SELECT DISTINCT c["CustomerID"] FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = "ALFKI")) """); - } + }); public override async Task Anonymous_member_distinct_orderby(bool async) { @@ -2602,17 +2824,19 @@ public override async Task Anonymous_member_distinct_result(bool async) AssertSql(); } - public override async Task Anonymous_complex_distinct_where(bool async) - { - await base.Anonymous_complex_distinct_where(async); + public override Task Anonymous_complex_distinct_where(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Anonymous_complex_distinct_where(a); - AssertSql( - """ + AssertSql( + """ SELECT DISTINCT VALUE {"A" : (c["CustomerID"] || c["City"])} FROM root c WHERE ((c["Discriminator"] = "Customer") AND ((c["CustomerID"] || c["City"]) = "ALFKIBerlin")) """); - } + }); public override async Task Anonymous_complex_distinct_orderby(bool async) { @@ -2634,16 +2858,20 @@ public override async Task Anonymous_complex_distinct_result(bool async) public override async Task Anonymous_complex_orderby(bool async) { - await Assert.ThrowsAsync( - async () => await base.Anonymous_complex_orderby(async)); + // Always throws for sync. + if (async) + { + await Assert.ThrowsAsync( + async () => await base.Anonymous_complex_orderby(async)); - AssertSql( - """ + AssertSql( + """ SELECT VALUE {"A" : (c["CustomerID"] || c["City"])} FROM root c WHERE (c["Discriminator"] = "Customer") ORDER BY (c["CustomerID"] || c["City"]) """); + } } public override async Task Anonymous_subquery_orderby(bool async) @@ -2654,17 +2882,19 @@ public override async Task Anonymous_subquery_orderby(bool async) AssertSql(); } - public override async Task DTO_member_distinct_where(bool async) - { - await base.DTO_member_distinct_where(async); + public override Task DTO_member_distinct_where(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.DTO_member_distinct_where(a); - AssertSql( - """ + AssertSql( + """ SELECT DISTINCT VALUE {"Property" : c["CustomerID"]} FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = "ALFKI")) """); - } + }); public override async Task DTO_member_distinct_orderby(bool async) { @@ -2684,17 +2914,19 @@ public override async Task DTO_member_distinct_result(bool async) AssertSql(); } - public override async Task DTO_complex_distinct_where(bool async) - { - await base.DTO_complex_distinct_where(async); + public override Task DTO_complex_distinct_where(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.DTO_complex_distinct_where(a); - AssertSql( - """ + AssertSql( + """ SELECT DISTINCT VALUE {"Property" : (c["CustomerID"] || c["City"])} FROM root c WHERE ((c["Discriminator"] = "Customer") AND ((c["CustomerID"] || c["City"]) = "ALFKIBerlin")) """); - } + }); public override async Task DTO_complex_distinct_orderby(bool async) { @@ -2716,17 +2948,21 @@ public override async Task DTO_complex_distinct_result(bool async) public override async Task DTO_complex_orderby(bool async) { - // Cosmos client evaluation. Issue #17246. - await Assert.ThrowsAsync( - async () => await base.DTO_complex_orderby(async)); + // Always throws for sync. + if (async) + { + // Cosmos client evaluation. Issue #17246. + await Assert.ThrowsAsync( + async () => await base.DTO_complex_orderby(async)); - AssertSql( - """ + AssertSql( + """ SELECT VALUE {"Property" : (c["CustomerID"] || c["City"])} FROM root c WHERE (c["Discriminator"] = "Customer") ORDER BY (c["CustomerID"] || c["City"]) """); + } } public override async Task DTO_subquery_orderby(bool async) @@ -2750,17 +2986,19 @@ public override async Task Include_with_orderby_skip_preserves_ordering(bool asy AssertSql(); } - public override async Task Int16_parameter_can_be_used_for_int_column(bool async) - { - await base.Int16_parameter_can_be_used_for_int_column(async); + public override Task Int16_parameter_can_be_used_for_int_column(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Int16_parameter_can_be_used_for_int_column(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderID"] = 10300)) """); - } + }); public override async Task Subquery_is_null_translated_correctly(bool async) { @@ -2954,19 +3192,21 @@ public override async Task Select_distinct_sum(bool async) AssertSql(); } - public override async Task Comparing_to_fixed_string_parameter(bool async) - { - await base.Comparing_to_fixed_string_parameter(async); + public override Task Comparing_to_fixed_string_parameter(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Comparing_to_fixed_string_parameter(a); - AssertSql( - """ + AssertSql( + """ @__prefix_0='A' SELECT c["CustomerID"] FROM root c WHERE ((c["Discriminator"] = "Customer") AND STARTSWITH(c["CustomerID"], @__prefix_0)) """); - } + }); public override async Task Comparing_entities_using_Equals(bool async) { @@ -2984,18 +3224,20 @@ public override async Task Comparing_different_entity_types_using_Equals(bool as AssertSql(); } - public override async Task Comparing_entity_to_null_using_Equals(bool async) - { - await base.Comparing_entity_to_null_using_Equals(async); + public override Task Comparing_entity_to_null_using_Equals(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Comparing_entity_to_null_using_Equals(a); - AssertSql( - """ + AssertSql( + """ SELECT c["CustomerID"] FROM root c WHERE (((c["Discriminator"] = "Customer") AND STARTSWITH(c["CustomerID"], "A")) AND NOT((c["CustomerID"] = null))) ORDER BY c["CustomerID"] """); - } + }); public override async Task Comparing_navigations_using_Equals(bool async) { @@ -3029,17 +3271,19 @@ public override async Task Comparing_non_matching_collection_navigations_using_E AssertSql(); } - public override async Task Comparing_collection_navigation_to_null(bool async) - { - await base.Comparing_collection_navigation_to_null(async); + public override Task Comparing_collection_navigation_to_null(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Comparing_collection_navigation_to_null(a); - AssertSql( - """ + AssertSql( + """ SELECT c["CustomerID"] FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = null)) """); - } + }); public override async Task Comparing_collection_navigation_to_null_complex(bool async) { @@ -3049,17 +3293,19 @@ public override async Task Comparing_collection_navigation_to_null_complex(bool AssertSql(); } - public override async Task Compare_collection_navigation_with_itself(bool async) - { - await base.Compare_collection_navigation_with_itself(async); + public override Task Compare_collection_navigation_with_itself(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Compare_collection_navigation_with_itself(a); - AssertSql( - """ + AssertSql( + """ SELECT c["CustomerID"] FROM root c WHERE (((c["Discriminator"] = "Customer") AND STARTSWITH(c["CustomerID"], "A")) AND (c["CustomerID"] = c["CustomerID"])) """); - } + }); public override async Task Compare_two_collection_navigations_with_different_query_sources(bool async) { @@ -3085,31 +3331,35 @@ public override async Task Compare_two_collection_navigations_with_different_pro AssertSql(); } - public override async Task OrderBy_ThenBy_same_column_different_direction(bool async) - { - await base.OrderBy_ThenBy_same_column_different_direction(async); + public override Task OrderBy_ThenBy_same_column_different_direction(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.OrderBy_ThenBy_same_column_different_direction(a); - AssertSql( - """ + AssertSql( + """ SELECT c["CustomerID"] FROM root c WHERE ((c["Discriminator"] = "Customer") AND STARTSWITH(c["CustomerID"], "A")) ORDER BY c["CustomerID"] """); - } + }); - public override async Task OrderBy_OrderBy_same_column_different_direction(bool async) - { - await base.OrderBy_OrderBy_same_column_different_direction(async); + public override Task OrderBy_OrderBy_same_column_different_direction(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.OrderBy_OrderBy_same_column_different_direction(a); - AssertSql( - """ + AssertSql( + """ SELECT c["CustomerID"] FROM root c WHERE ((c["Discriminator"] = "Customer") AND STARTSWITH(c["CustomerID"], "A")) ORDER BY c["CustomerID"] DESC """); - } + }); public override async Task Complex_nested_query_doesnt_try_binding_to_grandparent_when_parent_returns_complex_result(bool async) { @@ -3129,12 +3379,14 @@ await AssertTranslationFailed( AssertSql(); } - public override async Task OrderBy_Dto_projection_skip_take(bool async) - { - await base.OrderBy_Dto_projection_skip_take(async); + public override Task OrderBy_Dto_projection_skip_take(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.OrderBy_Dto_projection_skip_take(a); - AssertSql( - """ + AssertSql( + """ @__p_0='5' @__p_1='10' @@ -3144,7 +3396,7 @@ FROM root c ORDER BY c["CustomerID"] OFFSET @__p_0 LIMIT @__p_1 """); - } + }); public override async Task Join_take_count_works(bool async) { @@ -3156,30 +3408,38 @@ public override async Task Join_take_count_works(bool async) public override async Task OrderBy_empty_list_contains(bool async) { - await Assert.ThrowsAsync( - async () => await base.OrderBy_empty_list_contains(async)); + // Always throws for sync. + if (async) + { + await Assert.ThrowsAsync( + async () => await base.OrderBy_empty_list_contains(async)); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Customer") ORDER BY (true = false) """); + } } public override async Task OrderBy_empty_list_does_not_contains(bool async) { - await Assert.ThrowsAsync( - async () => await base.OrderBy_empty_list_does_not_contains(async)); + // Always throws for sync. + if (async) + { + await Assert.ThrowsAsync( + async () => await base.OrderBy_empty_list_does_not_contains(async)); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Customer") ORDER BY NOT((true = false)) """); + } } public override async Task Manual_expression_tree_typed_null_equality(bool async) @@ -3268,37 +3528,43 @@ public override async Task Entity_equality_through_subquery(bool async) AssertSql(); } - public override async Task Can_convert_manually_build_expression_with_default(bool async) - { - await base.Can_convert_manually_build_expression_with_default(async); + public override Task Can_convert_manually_build_expression_with_default(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Can_convert_manually_build_expression_with_default(a); - AssertSql( - """ + AssertSql( + """ SELECT COUNT(1) AS c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["City"] != null)) """, - // - """ + // + """ SELECT COUNT(1) AS c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["City"] != null)) """); - } + }); public override async Task Entity_equality_orderby_descending_composite_key(bool async) { - // Cosmos client evaluation. Issue #17246. - await Assert.ThrowsAsync( - async () => await base.Entity_equality_orderby_descending_composite_key(async)); + // Always throws for sync. + if (async) + { + // Cosmos client evaluation. Issue #17246. + await Assert.ThrowsAsync( + async () => await base.Entity_equality_orderby_descending_composite_key(async)); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "OrderDetail") ORDER BY c["OrderID"] DESC, c["ProductID"] DESC """); + } } public override async Task Entity_equality_orderby_subquery(bool async) @@ -3327,32 +3593,40 @@ public override async Task Null_Coalesce_Short_Circuit(bool async) public override async Task OrderByDescending_ThenBy(bool async) { - // Cosmos client evaluation. Issue #17246. - await Assert.ThrowsAsync( - async () => await base.OrderByDescending_ThenBy(async)); + // Always throws for sync. + if (async) + { + // Cosmos client evaluation. Issue #17246. + await Assert.ThrowsAsync( + async () => await base.OrderByDescending_ThenBy(async)); - AssertSql( - """ + AssertSql( + """ SELECT c["City"] FROM root c WHERE (c["Discriminator"] = "Customer") ORDER BY c["CustomerID"] DESC, c["Country"] """); + } } public override async Task OrderByDescending_ThenByDescending(bool async) { - // Cosmos client evaluation. Issue #17246. - await Assert.ThrowsAsync( - async () => await base.OrderByDescending_ThenByDescending(async)); + // Always throws for sync. + if (async) + { + // Cosmos client evaluation. Issue #17246. + await Assert.ThrowsAsync( + async () => await base.OrderByDescending_ThenByDescending(async)); - AssertSql( - """ + AssertSql( + """ SELECT c["City"] FROM root c WHERE (c["Discriminator"] = "Customer") ORDER BY c["CustomerID"] DESC, c["Country"] DESC """); + } } public override async Task OrderBy_Join(bool async) @@ -3365,32 +3639,40 @@ public override async Task OrderBy_Join(bool async) public override async Task OrderBy_ThenBy(bool async) { - // Cosmos client evaluation. Issue #17246. - await Assert.ThrowsAsync( - async () => await base.OrderBy_ThenBy(async)); + // Always throws for sync. + if (async) + { + // Cosmos client evaluation. Issue #17246. + await Assert.ThrowsAsync( + async () => await base.OrderBy_ThenBy(async)); - AssertSql( - """ + AssertSql( + """ SELECT c["City"] FROM root c WHERE (c["Discriminator"] = "Customer") ORDER BY c["CustomerID"], c["Country"] """); + } } public override async Task OrderBy_ThenBy_predicate(bool async) { - // Cosmos client evaluation. Issue #17246. - await Assert.ThrowsAsync( - async () => await base.OrderBy_ThenBy_predicate(async)); + // Always throws for sync. + if (async) + { + // Cosmos client evaluation. Issue #17246. + await Assert.ThrowsAsync( + async () => await base.OrderBy_ThenBy_predicate(async)); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["City"] = "London")) ORDER BY c["City"], c["CustomerID"] """); + } } public override async Task SelectMany_correlated_simple(bool async) @@ -3458,17 +3740,19 @@ await AssertTranslationFailed( AssertSql(); } - public override async Task Select_Property_when_shadow_unconstrained_generic_method(bool async) - { - await base.Select_Property_when_shadow_unconstrained_generic_method(async); + public override Task Select_Property_when_shadow_unconstrained_generic_method(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_Property_when_shadow_unconstrained_generic_method(a); - AssertSql( - """ + AssertSql( + """ SELECT c["Title"] FROM root c WHERE (c["Discriminator"] = "Employee") """); - } + }); public override async Task Skip_orderby_const(bool async) { @@ -3480,19 +3764,21 @@ public override async Task Skip_orderby_const(bool async) AssertSql(); } - public override async Task Where_Property_when_shadow_unconstrained_generic_method(bool async) - { - await base.Where_Property_when_shadow_unconstrained_generic_method(async); + public override Task Where_Property_when_shadow_unconstrained_generic_method(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_Property_when_shadow_unconstrained_generic_method(a); - AssertSql( - """ + AssertSql( + """ @__value_0='Sales Representative' SELECT c FROM root c WHERE ((c["Discriminator"] = "Employee") AND (c["Title"] = @__value_0)) """); - } + }); public override async Task Inner_parameter_in_nested_lambdas_gets_preserved(bool async) { @@ -3684,56 +3970,64 @@ public override async Task Anonymous_projection_skip_take_empty_collection_First AssertSql(); } - public override async Task Checked_context_with_arithmetic_does_not_fail(bool isAsync) - { - await base.Checked_context_with_arithmetic_does_not_fail(isAsync); + public override Task Checked_context_with_arithmetic_does_not_fail(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Checked_context_with_arithmetic_does_not_fail(async); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "OrderDetail") AND ((((c["Quantity"] + 1) = 5) AND ((c["Quantity"] - 1) = 3)) AND ((c["Quantity"] * 1) = c["Quantity"]))) ORDER BY c["OrderID"] """); - } + }); - public override async Task Checked_context_with_case_to_same_nullable_type_does_not_fail(bool isAsync) - { - await base.Checked_context_with_case_to_same_nullable_type_does_not_fail(isAsync); + public override Task Checked_context_with_case_to_same_nullable_type_does_not_fail(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Checked_context_with_case_to_same_nullable_type_does_not_fail(async); - AssertSql( - """ + AssertSql( + """ SELECT MAX(c["Quantity"]) AS c FROM root c WHERE (c["Discriminator"] = "OrderDetail") """); - } + }); - public override async Task Entity_equality_with_null_coalesce_client_side(bool async) - { - await base.Entity_equality_with_null_coalesce_client_side(async); + public override Task Entity_equality_with_null_coalesce_client_side(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Entity_equality_with_null_coalesce_client_side(a); - AssertSql( - """ + AssertSql( + """ @__entity_equality_a_0_CustomerID='ALFKI' SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = @__entity_equality_a_0_CustomerID)) """); - } + }); - public override async Task Entity_equality_contains_with_list_of_null(bool async) - { - await base.Entity_equality_contains_with_list_of_null(async); + public override Task Entity_equality_contains_with_list_of_null(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Entity_equality_contains_with_list_of_null(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] IN ("ALFKI") OR (c["CustomerID"] = null))) """); - } + }); public override async Task Perform_identity_resolution_reuses_same_instances(bool async, bool useAsTracking) { @@ -3924,462 +4218,533 @@ public override async Task Collection_projection_after_DefaultIfEmpty(bool async AssertSql(); } - public override async Task AsEnumerable_over_string(bool async) - { - await base.AsEnumerable_over_string(async); + public override Task AsEnumerable_over_string(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.AsEnumerable_over_string(a); - AssertSql( - """ + AssertSql( + """ SELECT c["City"] FROM root c WHERE (c["Discriminator"] = "Customer") ORDER BY c["CustomerID"] """); - } + }); - public override async Task Select_Property_when_non_shadow(bool async) - { - await base.Select_Property_when_non_shadow(async); + public override Task Select_Property_when_non_shadow(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_Property_when_non_shadow(a); - AssertSql( - """ + AssertSql( + """ SELECT c["OrderID"] FROM root c WHERE (c["Discriminator"] = "Order") """); - } + }); - public override async Task Cast_results_to_object(bool async) - { - await base.Cast_results_to_object(async); + public override Task Cast_results_to_object(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Cast_results_to_object(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); - public override async Task Null_Coalesce_Short_Circuit_with_server_correlated_leftover(bool async) - { - await base.Null_Coalesce_Short_Circuit_with_server_correlated_leftover(async); + public override Task Null_Coalesce_Short_Circuit_with_server_correlated_leftover(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Null_Coalesce_Short_Circuit_with_server_correlated_leftover(a); - AssertSql( - """ + AssertSql( + """ SELECT VALUE {"Result" : false} FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); - public override async Task Concat_int_string(bool async) - { - await base.Concat_int_string(async); + public override Task Concat_int_string(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Concat_int_string(a); - AssertSql( - """ + AssertSql( + """ SELECT c["CustomerID"], c["OrderID"] FROM root c WHERE (c["Discriminator"] = "Order") """); - } + }); - public override async Task Select_expression_datetime_add_ticks(bool async) - { - await base.Select_expression_datetime_add_ticks(async); + public override Task Select_expression_datetime_add_ticks(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_expression_datetime_add_ticks(a); - AssertSql( - """ + AssertSql( + """ SELECT c["OrderDate"] FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderDate"] != null)) """); - } + }); public override async Task Throws_on_concurrent_query_first(bool async) { - await base.Throws_on_concurrent_query_first(async); + // Always throws for sync. + if (async) + { + await base.Throws_on_concurrent_query_first(async); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Customer") """); + } } - public override async Task Entity_equality_through_include(bool async) - { - await base.Entity_equality_through_include(async); + public override Task Entity_equality_through_include(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Entity_equality_through_include(a); - AssertSql( - """ + AssertSql( + """ SELECT c["CustomerID"] FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = null)) """); - } + }); - public override async Task Concat_constant_string_int(bool async) - { - await base.Concat_constant_string_int(async); + public override Task Concat_constant_string_int(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Concat_constant_string_int(a); - AssertSql( - """ + AssertSql( + """ SELECT c["OrderID"] FROM root c WHERE (c["Discriminator"] = "Order") """); - } + }); - public override async Task OrderBy_scalar_primitive(bool async) - { - await base.OrderBy_scalar_primitive(async); + public override Task OrderBy_scalar_primitive(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.OrderBy_scalar_primitive(a); - AssertSql( - """ + AssertSql( + """ SELECT c["EmployeeID"] FROM root c WHERE (c["Discriminator"] = "Employee") ORDER BY c["EmployeeID"] """); - } + }); - public override async Task Where_Property_when_non_shadow(bool async) - { - await base.Where_Property_when_non_shadow(async); + public override Task Where_Property_when_non_shadow(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_Property_when_non_shadow(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderID"] = 10248)) """); - } + }); - public override async Task OrderBy_Select(bool async) - { - await base.OrderBy_Select(async); + public override Task OrderBy_Select(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.OrderBy_Select(a); - AssertSql( - """ + AssertSql( + """ SELECT c["ContactName"] FROM root c WHERE (c["Discriminator"] = "Customer") ORDER BY c["CustomerID"] """); - } + }); - public override async Task Concat_string_int(bool async) - { - await base.Concat_string_int(async); + public override Task Concat_string_int(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Concat_string_int(a); - AssertSql( - """ + AssertSql( + """ SELECT c["OrderID"], c["CustomerID"] FROM root c WHERE (c["Discriminator"] = "Order") """); - } + }); public override async Task Non_nullable_property_through_optional_navigation(bool async) { - await base.Non_nullable_property_through_optional_navigation(async); + // Always throws for sync. + if (async) + { + await base.Non_nullable_property_through_optional_navigation(async); - AssertSql( - """ + AssertSql( + """ SELECT LENGTH(c["Region"]) AS Length FROM root c WHERE (c["Discriminator"] = "Customer") """); + } } - public override async Task ToList_over_string(bool async) - { - await base.ToList_over_string(async); + public override Task ToList_over_string(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.ToList_over_string(a); - AssertSql( - """ + AssertSql( + """ SELECT c["City"] FROM root c WHERE (c["Discriminator"] = "Customer") ORDER BY c["CustomerID"] """); - } + }); - public override async Task Entity_equality_not_null_composite_key(bool async) - { - await base.Entity_equality_not_null_composite_key(async); + public override Task Entity_equality_not_null_composite_key(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Entity_equality_not_null_composite_key(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "OrderDetail") AND ((c["OrderID"] != null) AND (c["ProductID"] != null))) """); - } + }); public override void Query_composition_against_ienumerable_set() - { - base.Query_composition_against_ienumerable_set(); - - AssertSql( - """ -SELECT c -FROM root c -WHERE (c["Discriminator"] = "Order") -"""); - } - - public override async Task ToListAsync_with_canceled_token() - { - await base.ToListAsync_with_canceled_token(); - - AssertSql( - """ + => Fixture.NoSyncTest( + () => + { + base.Query_composition_against_ienumerable_set(); + }); + + public override Task ToListAsync_with_canceled_token() + => Fixture.NoSyncTest( + true, async _ => + { + await base.ToListAsync_with_canceled_token(); + + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Employee") """); - } + }); - public override async Task Ternary_should_not_evaluate_both_sides(bool async) - { - await base.Ternary_should_not_evaluate_both_sides(async); + public override Task Ternary_should_not_evaluate_both_sides(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Ternary_should_not_evaluate_both_sides(a); - AssertSql( - """ + AssertSql( + """ SELECT VALUE {"CustomerID" : c["CustomerID"], "Data1" : "none"} FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); - public override async Task Entity_equality_orderby(bool async) - { - await base.Entity_equality_orderby(async); + public override Task Entity_equality_orderby(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Entity_equality_orderby(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Customer") ORDER BY c["CustomerID"] """); - } + }); - public override async Task Load_should_track_results(bool async) - { - await base.Load_should_track_results(async); + public override Task Load_should_track_results(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Load_should_track_results(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); - public override async Task Null_parameter_name_works(bool async) - { - await base.Null_parameter_name_works(async); + public override Task Null_parameter_name_works(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Null_parameter_name_works(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = null)) """); - } + }); - public override async Task Where_Property_shadow_closure(bool async) - { - await base.Where_Property_shadow_closure(async); + public override Task Where_Property_shadow_closure(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_Property_shadow_closure(a); - AssertSql( - """ + AssertSql( + """ @__value_0='Sales Representative' SELECT c FROM root c WHERE ((c["Discriminator"] = "Employee") AND (c["Title"] = @__value_0)) """, - // - """ + // + """ @__value_0='Steven' SELECT c FROM root c WHERE ((c["Discriminator"] = "Employee") AND (c["FirstName"] = @__value_0)) """); - } + }); - public override async Task Entity_equality_local_double_check(bool async) - { - await base.Entity_equality_local_double_check(async); + public override Task Entity_equality_local_double_check(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Entity_equality_local_double_check(a); - AssertSql( - """ + AssertSql( + """ @__entity_equality_local_0_CustomerID='ANATR' SELECT c["CustomerID"] FROM root c WHERE ((c["Discriminator"] = "Customer") AND ((c["CustomerID"] = @__entity_equality_local_0_CustomerID) AND (@__entity_equality_local_0_CustomerID = c["CustomerID"]))) """); - } + }); - public override async Task ToArray_over_string(bool async) - { - await base.ToArray_over_string(async); + public override Task ToArray_over_string(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.ToArray_over_string(a); - AssertSql( - """ + AssertSql( + """ SELECT c["City"] FROM root c WHERE (c["Discriminator"] = "Customer") ORDER BY c["CustomerID"] """); - } + }); - public override async Task MemberInitExpression_NewExpression_is_funcletized_even_when_bindings_are_not_evaluatable(bool async) - { - await base.MemberInitExpression_NewExpression_is_funcletized_even_when_bindings_are_not_evaluatable(async); + public override Task MemberInitExpression_NewExpression_is_funcletized_even_when_bindings_are_not_evaluatable(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.MemberInitExpression_NewExpression_is_funcletized_even_when_bindings_are_not_evaluatable(a); - AssertSql( - """ + AssertSql( + """ SELECT c["CustomerID"] FROM root c WHERE ((c["Discriminator"] = "Customer") AND STARTSWITH(c["CustomerID"], "A")) """); - } + }); - public override async Task Entity_equality_null_composite_key(bool async) - { - await base.Entity_equality_null_composite_key(async); + public override Task Entity_equality_null_composite_key(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Entity_equality_null_composite_key(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "OrderDetail") AND ((c["OrderID"] = null) OR (c["ProductID"] = null))) """); - } + }); - public override async Task Concat_parameter_string_int(bool async) - { - await base.Concat_parameter_string_int(async); + public override Task Concat_parameter_string_int(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Concat_parameter_string_int(a); - AssertSql( - """ + AssertSql( + """ SELECT c["OrderID"] FROM root c WHERE (c["Discriminator"] = "Order") """); - } + }); // ReSharper disable once RedundantOverriddenMember public override Task ToListAsync_can_be_canceled() // May or may not generate SQL depending on when cancellation happens. => base.ToListAsync_can_be_canceled(); - public override async Task Where_Property_when_shadow(bool async) - { - await base.Where_Property_when_shadow(async); + public override Task Where_Property_when_shadow(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_Property_when_shadow(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Employee") AND (c["Title"] = "Sales Representative")) """); - } + }); public override async Task Throws_on_concurrent_query_list(bool async) { - await base.Throws_on_concurrent_query_list(async); + // Always throws for sync. + if (async) + { + await base.Throws_on_concurrent_query_list(async); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Customer") """); + } } - public override async Task Convert_to_nullable_on_nullable_value_is_ignored(bool async) - { - await base.Convert_to_nullable_on_nullable_value_is_ignored(async); + public override Task Convert_to_nullable_on_nullable_value_is_ignored(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Convert_to_nullable_on_nullable_value_is_ignored(a); - AssertSql( - """ + AssertSql( + """ SELECT c["OrderDate"] FROM root c WHERE (c["Discriminator"] = "Order") """); - } + }); - public override async Task Ternary_should_not_evaluate_both_sides_with_parameter(bool async) - { - await base.Ternary_should_not_evaluate_both_sides_with_parameter(async); + public override Task Ternary_should_not_evaluate_both_sides_with_parameter(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Ternary_should_not_evaluate_both_sides_with_parameter(a); - AssertSql( - """ + AssertSql( + """ SELECT VALUE {"Data1" : true} FROM root c WHERE (c["Discriminator"] = "Order") """); - } + }); - public override async Task Context_based_client_method(bool async) - { - await base.Context_based_client_method(async); + public override Task Context_based_client_method(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Context_based_client_method(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Customer") """, - // - """ + // + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); - public override async Task OrderByDescending(bool async) - { - await base.OrderByDescending(async); + public override Task OrderByDescending(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.OrderByDescending(a); - AssertSql( - """ + AssertSql( + """ SELECT c["City"] FROM root c WHERE (c["Discriminator"] = "Customer") ORDER BY c["CustomerID"] DESC """); - } + }); - public override async Task Select_Property_when_shadow(bool async) - { - await base.Select_Property_when_shadow(async); + public override Task Select_Property_when_shadow(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_Property_when_shadow(a); - AssertSql( - """ + AssertSql( + """ SELECT c["Title"] FROM root c WHERE (c["Discriminator"] = "Employee") """); - } + }); - public override async Task Skip_0_Take_0_works_when_parameter(bool async) - { - await base.Skip_0_Take_0_works_when_parameter(async); + public override Task Skip_0_Take_0_works_when_parameter(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Skip_0_Take_0_works_when_parameter(a); - AssertSql( - """ + AssertSql( + """ @__p_0='0' SELECT c @@ -4388,8 +4753,8 @@ FROM root c ORDER BY c["CustomerID"] OFFSET @__p_0 LIMIT @__p_0 """, - // - """ + // + """ @__p_0='1' SELECT c @@ -4398,25 +4763,10 @@ FROM root c ORDER BY c["CustomerID"] OFFSET @__p_0 LIMIT @__p_0 """); - } - - public override async Task Mixed_sync_async_in_query_cache() - { - await base.Mixed_sync_async_in_query_cache(); + }); - AssertSql( - """ -SELECT c -FROM root c -WHERE (c["Discriminator"] = "Customer") -""", - // - """ -SELECT c -FROM root c -WHERE (c["Discriminator"] = "Customer") -"""); - } + public override Task Mixed_sync_async_in_query_cache() + => Task.CompletedTask; // No sync on Cosmos public override async Task Client_code_using_instance_method_throws(bool async) { @@ -4641,29 +4991,33 @@ await AssertTranslationFailed( AssertSql(); } - public override async Task Contains_over_concatenated_columns_with_different_sizes(bool async) - { - await base.Contains_over_concatenated_columns_with_different_sizes(async); + public override Task Contains_over_concatenated_columns_with_different_sizes(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Contains_over_concatenated_columns_with_different_sizes(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] || c["CompanyName"]) IN ("ALFKIAlfreds Futterkiste", "ANATRAna Trujillo Emparedados y helados")) """); - } + }); - public override async Task Contains_over_concatenated_column_and_constant(bool async) - { - await base.Contains_over_concatenated_column_and_constant(async); + public override Task Contains_over_concatenated_column_and_constant(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Contains_over_concatenated_column_and_constant(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] || "SomeConstant") IN ("ALFKISomeConstant", "ANATRSomeConstant", "ALFKIX")) """); - } + }); public override async Task Contains_over_concatenated_columns_both_fixed_length(bool async) { @@ -4673,40 +5027,46 @@ await AssertTranslationFailed( AssertSql(); } - public override async Task Contains_over_concatenated_column_and_parameter(bool async) - { - await base.Contains_over_concatenated_column_and_parameter(async); + public override Task Contains_over_concatenated_column_and_parameter(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Contains_over_concatenated_column_and_parameter(a); - AssertSql( - """ + AssertSql( + """ @__someVariable_0='SomeVariable' SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] || @__someVariable_0) IN ("ALFKISomeVariable", "ANATRSomeVariable", "ALFKIX")) """); - } + }); - public override async Task Contains_over_concatenated_parameter_and_constant(bool async) - { - await base.Contains_over_concatenated_parameter_and_constant(async); + public override Task Contains_over_concatenated_parameter_and_constant(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Contains_over_concatenated_parameter_and_constant(a); - AssertSql( - """ + AssertSql( + """ @__Contains_0='true' SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND @__Contains_0) """); - } + }); - public override async Task Compiler_generated_local_closure_produces_valid_parameter_name(bool async) - { - await base.Compiler_generated_local_closure_produces_valid_parameter_name(async); + public override Task Compiler_generated_local_closure_produces_valid_parameter_name(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Compiler_generated_local_closure_produces_valid_parameter_name(a); - AssertSql( -""" + AssertSql( + """ @__customerId_0='ALFKI' @__details_City_1='Berlin' @@ -4714,21 +5074,23 @@ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND ((c["CustomerID"] = @__customerId_0) AND (c["City"] = @__details_City_1))) """); - } + }); - public override async Task Static_member_access_gets_parameterized_within_larger_evaluatable(bool async) - { - await base.Static_member_access_gets_parameterized_within_larger_evaluatable(async); + public override Task Static_member_access_gets_parameterized_within_larger_evaluatable(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Static_member_access_gets_parameterized_within_larger_evaluatable(a); - AssertSql( - """ + AssertSql( + """ @__p_0='ALFKI' SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = @__p_0)) """); - } + }); private void AssertSql(params string[] expected) => Fixture.TestSqlLoggerFactory.AssertBaseline(expected); diff --git a/test/EFCore.Cosmos.FunctionalTests/Query/NorthwindQueryCosmosFixture.cs b/test/EFCore.Cosmos.FunctionalTests/Query/NorthwindQueryCosmosFixture.cs index 3fbfcd0c2a7..8e928c2d234 100644 --- a/test/EFCore.Cosmos.FunctionalTests/Query/NorthwindQueryCosmosFixture.cs +++ b/test/EFCore.Cosmos.FunctionalTests/Query/NorthwindQueryCosmosFixture.cs @@ -22,6 +22,12 @@ public TestSqlLoggerFactory TestSqlLoggerFactory protected override bool ShouldLogCategory(string logCategory) => logCategory == DbLoggerCategory.Query.Name; + public Task NoSyncTest(bool async, Func testCode) + => CosmosTestHelpers.Instance.NoSyncTest(async, testCode); + + public void NoSyncTest(Action testCode) + => CosmosTestHelpers.Instance.NoSyncTest(testCode); + protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext context) { base.OnModelCreating(modelBuilder, context); diff --git a/test/EFCore.Cosmos.FunctionalTests/Query/NorthwindSelectQueryCosmosTest.cs b/test/EFCore.Cosmos.FunctionalTests/Query/NorthwindSelectQueryCosmosTest.cs index adf4f0670db..fecf0a5be64 100644 --- a/test/EFCore.Cosmos.FunctionalTests/Query/NorthwindSelectQueryCosmosTest.cs +++ b/test/EFCore.Cosmos.FunctionalTests/Query/NorthwindSelectQueryCosmosTest.cs @@ -26,44 +26,50 @@ public virtual void Check_all_tests_overridden() [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual async Task Projection_with_Value_Property(bool async) - { - await AssertQuery( - async, - ss => ss.Set().Select(o => new { Value = o.OrderID }), - e => e.Value); - - AssertSql( - """ + public virtual Task Projection_with_Value_Property(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await AssertQuery( + async, + ss => ss.Set().Select(o => new { Value = o.OrderID }), + e => e.Value); + + AssertSql( + """ SELECT VALUE {"Value" : c["OrderID"]} FROM root c WHERE (c["Discriminator"] = "Order") """); - } + }); - public override async Task Projection_when_arithmetic_expression_precedence(bool async) - { - await base.Projection_when_arithmetic_expression_precedence(async); + public override Task Projection_when_arithmetic_expression_precedence(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Projection_when_arithmetic_expression_precedence(a); - AssertSql( - """ + AssertSql( + """ SELECT VALUE {"A" : (c["OrderID"] / (c["OrderID"] / 2)), "B" : ((c["OrderID"] / c["OrderID"]) / 2)} FROM root c WHERE (c["Discriminator"] = "Order") """); - } + }); - public override async Task Projection_when_arithmetic_expressions(bool async) - { - await base.Projection_when_arithmetic_expressions(async); + public override Task Projection_when_arithmetic_expressions(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Projection_when_arithmetic_expressions(a); - AssertSql( - """ + AssertSql( + """ SELECT VALUE {"OrderID" : c["OrderID"], "Double" : (c["OrderID"] * 2), "Add" : (c["OrderID"] + 23), "Sub" : (100000 - c["OrderID"]), "Divide" : (c["OrderID"] / (c["OrderID"] / 2)), "Literal" : 42, "o" : c} FROM root c WHERE (c["Discriminator"] = "Order") """); - } + }); public override async Task Projection_when_arithmetic_mixed(bool async) { @@ -81,17 +87,19 @@ public override async Task Projection_when_arithmetic_mixed_subqueries(bool asyn AssertSql(); } - public override async Task Projection_when_null_value(bool async) - { - await base.Projection_when_null_value(async); + public override Task Projection_when_null_value(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Projection_when_null_value(a); - AssertSql( - """ + AssertSql( + """ SELECT c["Region"] FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); public override async Task Projection_when_client_evald_subquery(bool async) { @@ -101,30 +109,34 @@ public override async Task Projection_when_client_evald_subquery(bool async) AssertSql(); } - public override async Task Project_to_object_array(bool async) - { - await base.Project_to_object_array(async); + public override Task Project_to_object_array(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Project_to_object_array(a); - AssertSql( - """ + AssertSql( + """ SELECT c["EmployeeID"], c["ReportsTo"], c["Title"] FROM root c WHERE ((c["Discriminator"] = "Employee") AND (c["EmployeeID"] = 1)) """); - } + }); - public override async Task Projection_of_entity_type_into_object_array(bool async) - { - await base.Projection_of_entity_type_into_object_array(async); + public override Task Projection_of_entity_type_into_object_array(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Projection_of_entity_type_into_object_array(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND STARTSWITH(c["CustomerID"], "A")) ORDER BY c["CustomerID"] """); - } + }); public override async Task Projection_of_multiple_entity_types_into_object_array(bool async) { @@ -134,30 +146,34 @@ public override async Task Projection_of_multiple_entity_types_into_object_array AssertSql(); } - public override async Task Projection_of_entity_type_into_object_list(bool async) - { - await base.Projection_of_entity_type_into_object_list(async); + public override Task Projection_of_entity_type_into_object_list(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Projection_of_entity_type_into_object_list(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Customer") ORDER BY c["CustomerID"] """); - } + }); - public override async Task Project_to_int_array(bool async) - { - await base.Project_to_int_array(async); + public override Task Project_to_int_array(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Project_to_int_array(a); - AssertSql( - """ + AssertSql( + """ SELECT c["EmployeeID"], c["ReportsTo"] FROM root c WHERE ((c["Discriminator"] = "Employee") AND (c["EmployeeID"] = 1)) """); - } + }); public override async Task Select_bool_closure_with_order_by_property_with_cast_to_nullable(bool async) { @@ -169,11 +185,14 @@ public override async Task Select_bool_closure_with_order_by_property_with_cast_ public override async Task Select_bool_closure_with_order_parameter_with_cast_to_nullable(bool async) { - await Assert.ThrowsAsync( - () => base.Select_bool_closure_with_order_parameter_with_cast_to_nullable(async)); + // Always throws for sync. + if (async) + { + await Assert.ThrowsAsync( + () => base.Select_bool_closure_with_order_parameter_with_cast_to_nullable(async)); - AssertSql( - """ + AssertSql( + """ @__boolean_0='false' SELECT VALUE {"c" : @__boolean_0} @@ -181,148 +200,173 @@ FROM root c WHERE (c["Discriminator"] = "Customer") ORDER BY @__boolean_0 """); + } } - public override async Task Select_scalar(bool async) - { - await base.Select_scalar(async); + public override Task Select_scalar(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_scalar(a); - AssertSql( - """ + AssertSql( + """ SELECT c["City"] FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); - public override async Task Select_anonymous_one(bool async) - { - await base.Select_anonymous_one(async); + public override Task Select_anonymous_one(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_anonymous_one(a); - AssertSql( - """ + AssertSql( + """ SELECT c["City"] FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); - public override async Task Select_anonymous_two(bool async) - { - await base.Select_anonymous_two(async); + public override Task Select_anonymous_two(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_anonymous_two(a); - AssertSql( - """ + AssertSql( + """ SELECT c["City"], c["Phone"] FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); - public override async Task Select_anonymous_three(bool async) - { - await base.Select_anonymous_three(async); + public override Task Select_anonymous_three(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_anonymous_three(a); - AssertSql( - """ + AssertSql( + """ SELECT c["City"], c["Phone"], c["Country"] FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); - public override async Task Select_anonymous_bool_constant_true(bool async) - { - await base.Select_anonymous_bool_constant_true(async); + public override Task Select_anonymous_bool_constant_true(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_anonymous_bool_constant_true(a); - AssertSql( - """ + AssertSql( + """ SELECT VALUE {"CustomerID" : c["CustomerID"], "ConstantTrue" : true} FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); - public override async Task Select_anonymous_constant_in_expression(bool async) - { - await base.Select_anonymous_constant_in_expression(async); + public override Task Select_anonymous_constant_in_expression(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_anonymous_constant_in_expression(a); - AssertSql( - """ + AssertSql( + """ SELECT VALUE {"CustomerID" : c["CustomerID"], "Expression" : (LENGTH(c["CustomerID"]) + 5)} FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); - public override async Task Select_anonymous_conditional_expression(bool async) - { - await base.Select_anonymous_conditional_expression(async); + public override Task Select_anonymous_conditional_expression(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_anonymous_conditional_expression(a); - AssertSql( - """ + AssertSql( + """ SELECT VALUE {"ProductID" : c["ProductID"], "IsAvailable" : (c["UnitsInStock"] > 0)} FROM root c WHERE (c["Discriminator"] = "Product") """); - } + }); - public override async Task Select_anonymous_with_object(bool async) - { - await base.Select_anonymous_with_object(async); + public override Task Select_anonymous_with_object(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_anonymous_with_object(a); - AssertSql( - """ + AssertSql( + """ SELECT c["City"], c FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); - public override async Task Select_constant_int(bool async) - { - await base.Select_constant_int(async); + public override Task Select_constant_int(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_constant_int(a); - AssertSql( - """ + AssertSql( + """ SELECT VALUE {"c" : 0} FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); - public override async Task Select_constant_null_string(bool async) - { - await base.Select_constant_null_string(async); + public override Task Select_constant_null_string(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_constant_null_string(a); - AssertSql( - """ + AssertSql( + """ SELECT VALUE {"c" : null} FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); - public override async Task Select_local(bool async) - { - await base.Select_local(async); + public override Task Select_local(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_local(a); - AssertSql( - """ + AssertSql( + """ @__x_0='10' SELECT VALUE {"c" : @__x_0} FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); - public override async Task Select_scalar_primitive_after_take(bool async) - { - await base.Select_scalar_primitive_after_take(async); + public override Task Select_scalar_primitive_after_take(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_scalar_primitive_after_take(a); - AssertSql( - """ + AssertSql( + """ @__p_0='9' SELECT c["EmployeeID"] @@ -330,31 +374,35 @@ FROM root c WHERE (c["Discriminator"] = "Employee") OFFSET 0 LIMIT @__p_0 """); - } + }); - public override async Task Select_project_filter(bool async) - { - await base.Select_project_filter(async); + public override Task Select_project_filter(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_project_filter(a); - AssertSql( - """ + AssertSql( + """ SELECT c["CompanyName"] FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["City"] = "London")) """); - } + }); - public override async Task Select_project_filter2(bool async) - { - await base.Select_project_filter2(async); + public override Task Select_project_filter2(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_project_filter2(a); - AssertSql( - """ + AssertSql( + """ SELECT c["City"] FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["City"] = "London")) """); - } + }); public override async Task Select_nested_collection(bool async) { @@ -420,161 +468,185 @@ public override async Task Select_nested_collection_count_using_anonymous_type(b AssertSql(); } - public override async Task New_date_time_in_anonymous_type_works(bool async) - { - await base.New_date_time_in_anonymous_type_works(async); + public override Task New_date_time_in_anonymous_type_works(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.New_date_time_in_anonymous_type_works(a); - AssertSql( - """ + AssertSql( + """ SELECT 1 FROM root c WHERE ((c["Discriminator"] = "Customer") AND STARTSWITH(c["CustomerID"], "A")) """); - } + }); - public override async Task Select_non_matching_value_types_int_to_long_introduces_explicit_cast(bool async) - { - await base.Select_non_matching_value_types_int_to_long_introduces_explicit_cast(async); + public override Task Select_non_matching_value_types_int_to_long_introduces_explicit_cast(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_non_matching_value_types_int_to_long_introduces_explicit_cast(a); - AssertSql( - """ + AssertSql( + """ SELECT c["OrderID"] FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["CustomerID"] = "ALFKI")) ORDER BY c["OrderID"] """); - } + }); - public override async Task Select_non_matching_value_types_nullable_int_to_long_introduces_explicit_cast(bool async) - { - await base.Select_non_matching_value_types_nullable_int_to_long_introduces_explicit_cast(async); + public override Task Select_non_matching_value_types_nullable_int_to_long_introduces_explicit_cast(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_non_matching_value_types_nullable_int_to_long_introduces_explicit_cast(a); - AssertSql( - """ + AssertSql( + """ SELECT c["EmployeeID"] FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["CustomerID"] = "ALFKI")) ORDER BY c["OrderID"] """); - } + }); - public override async Task Select_non_matching_value_types_nullable_int_to_int_doesnt_introduce_explicit_cast(bool async) - { - await base.Select_non_matching_value_types_nullable_int_to_int_doesnt_introduce_explicit_cast(async); + public override Task Select_non_matching_value_types_nullable_int_to_int_doesnt_introduce_explicit_cast(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_non_matching_value_types_nullable_int_to_int_doesnt_introduce_explicit_cast(a); - AssertSql( - """ + AssertSql( + """ SELECT c["EmployeeID"] FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["CustomerID"] = "ALFKI")) ORDER BY c["OrderID"] """); - } + }); - public override async Task Select_non_matching_value_types_int_to_nullable_int_doesnt_introduce_explicit_cast(bool async) - { - await base.Select_non_matching_value_types_int_to_nullable_int_doesnt_introduce_explicit_cast(async); + public override Task Select_non_matching_value_types_int_to_nullable_int_doesnt_introduce_explicit_cast(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_non_matching_value_types_int_to_nullable_int_doesnt_introduce_explicit_cast(a); - AssertSql( - """ + AssertSql( + """ SELECT c["OrderID"] FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["CustomerID"] = "ALFKI")) ORDER BY c["OrderID"] """); - } + }); - public override async Task Select_non_matching_value_types_from_binary_expression_introduces_explicit_cast(bool async) - { - await base.Select_non_matching_value_types_from_binary_expression_introduces_explicit_cast(async); + public override Task Select_non_matching_value_types_from_binary_expression_introduces_explicit_cast(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_non_matching_value_types_from_binary_expression_introduces_explicit_cast(a); - AssertSql( - """ + AssertSql( + """ SELECT VALUE {"c" : (c["OrderID"] + c["OrderID"])} FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["CustomerID"] = "ALFKI")) ORDER BY c["OrderID"] """); - } + }); - public override async Task Select_non_matching_value_types_from_binary_expression_nested_introduces_top_level_explicit_cast( + public override Task Select_non_matching_value_types_from_binary_expression_nested_introduces_top_level_explicit_cast( bool async) - { - await base.Select_non_matching_value_types_from_binary_expression_nested_introduces_top_level_explicit_cast(async); + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_non_matching_value_types_from_binary_expression_nested_introduces_top_level_explicit_cast(a); - AssertSql( - """ + AssertSql( + """ SELECT c["OrderID"] FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["CustomerID"] = "ALFKI")) ORDER BY c["OrderID"] """); - } + }); - public override async Task Select_non_matching_value_types_from_unary_expression_introduces_explicit_cast1(bool async) - { - await base.Select_non_matching_value_types_from_unary_expression_introduces_explicit_cast1(async); + public override Task Select_non_matching_value_types_from_unary_expression_introduces_explicit_cast1(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_non_matching_value_types_from_unary_expression_introduces_explicit_cast1(a); - AssertSql( - """ + AssertSql( + """ SELECT VALUE {"c" : -(c["OrderID"])} FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["CustomerID"] = "ALFKI")) ORDER BY c["OrderID"] """); - } + }); - public override async Task Select_non_matching_value_types_from_unary_expression_introduces_explicit_cast2(bool async) - { - await base.Select_non_matching_value_types_from_unary_expression_introduces_explicit_cast2(async); + public override Task Select_non_matching_value_types_from_unary_expression_introduces_explicit_cast2(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_non_matching_value_types_from_unary_expression_introduces_explicit_cast2(a); - AssertSql( - """ + AssertSql( + """ SELECT c["OrderID"] FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["CustomerID"] = "ALFKI")) ORDER BY c["OrderID"] """); - } + }); - public override async Task Select_non_matching_value_types_from_length_introduces_explicit_cast(bool async) - { - await base.Select_non_matching_value_types_from_length_introduces_explicit_cast(async); + public override Task Select_non_matching_value_types_from_length_introduces_explicit_cast(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_non_matching_value_types_from_length_introduces_explicit_cast(a); - AssertSql( - """ + AssertSql( + """ SELECT LENGTH(c["CustomerID"]) AS c FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["CustomerID"] = "ALFKI")) ORDER BY c["OrderID"] """); - } + }); - public override async Task Select_non_matching_value_types_from_method_call_introduces_explicit_cast(bool async) - { - await base.Select_non_matching_value_types_from_method_call_introduces_explicit_cast(async); + public override Task Select_non_matching_value_types_from_method_call_introduces_explicit_cast(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_non_matching_value_types_from_method_call_introduces_explicit_cast(a); - AssertSql( - """ + AssertSql( + """ SELECT ABS(c["OrderID"]) AS c FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["CustomerID"] = "ALFKI")) ORDER BY c["OrderID"] """); - } + }); - public override async Task Select_non_matching_value_types_from_anonymous_type_introduces_explicit_cast(bool async) - { - await base.Select_non_matching_value_types_from_anonymous_type_introduces_explicit_cast(async); + public override Task Select_non_matching_value_types_from_anonymous_type_introduces_explicit_cast(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_non_matching_value_types_from_anonymous_type_introduces_explicit_cast(a); - AssertSql( - """ + AssertSql( + """ SELECT c["OrderID"] FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["CustomerID"] = "ALFKI")) ORDER BY c["OrderID"] """); - } + }); public override async Task Project_single_element_from_collection_with_OrderBy_Distinct_and_FirstOrDefault_followed_by_projecting_length(bool async) @@ -587,17 +659,19 @@ await AssertTranslationFailed( AssertSql(); } - public override async Task Select_conditional_with_null_comparison_in_test(bool async) - { - await base.Select_conditional_with_null_comparison_in_test(async); + public override Task Select_conditional_with_null_comparison_in_test(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_conditional_with_null_comparison_in_test(a); - AssertSql( - """ + AssertSql( + """ SELECT VALUE {"c" : ((c["CustomerID"] = null) ? true : (c["OrderID"] < 100))} FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["CustomerID"] = "ALFKI")) """); - } + }); public override async Task Projection_in_a_subquery_should_be_liftable(bool async) { @@ -609,17 +683,19 @@ public override async Task Projection_in_a_subquery_should_be_liftable(bool asyn AssertSql(); } - public override async Task Projection_containing_DateTime_subtraction(bool async) - { - await base.Projection_containing_DateTime_subtraction(async); + public override Task Projection_containing_DateTime_subtraction(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Projection_containing_DateTime_subtraction(a); - AssertSql( - """ + AssertSql( + """ SELECT c["OrderDate"] FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderID"] < 10300)) """); - } + }); public override async Task Project_single_element_from_collection_with_OrderBy_Take_and_FirstOrDefault(bool async) { @@ -712,162 +788,188 @@ await AssertTranslationFailed( AssertSql(); } - public override async Task Select_datetime_year_component(bool async) - { - await base.Select_datetime_year_component(async); + public override Task Select_datetime_year_component(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_datetime_year_component(a); - AssertSql( - """ + AssertSql( + """ SELECT c["OrderDate"] FROM root c WHERE (c["Discriminator"] = "Order") """); - } + }); - public override async Task Select_datetime_month_component(bool async) - { - await base.Select_datetime_month_component(async); + public override Task Select_datetime_month_component(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_datetime_month_component(a); - AssertSql( - """ + AssertSql( + """ SELECT c["OrderDate"] FROM root c WHERE (c["Discriminator"] = "Order") """); - } + }); - public override async Task Select_datetime_day_of_year_component(bool async) - { - await base.Select_datetime_day_of_year_component(async); + public override Task Select_datetime_day_of_year_component(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_datetime_day_of_year_component(a); - AssertSql( - """ + AssertSql( + """ SELECT c["OrderDate"] FROM root c WHERE (c["Discriminator"] = "Order") """); - } + }); - public override async Task Select_datetime_day_component(bool async) - { - await base.Select_datetime_day_component(async); + public override Task Select_datetime_day_component(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_datetime_day_component(a); - AssertSql( - """ + AssertSql( + """ SELECT c["OrderDate"] FROM root c WHERE (c["Discriminator"] = "Order") """); - } + }); - public override async Task Select_datetime_hour_component(bool async) - { - await base.Select_datetime_hour_component(async); + public override Task Select_datetime_hour_component(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_datetime_hour_component(a); - AssertSql( - """ + AssertSql( + """ SELECT c["OrderDate"] FROM root c WHERE (c["Discriminator"] = "Order") """); - } + }); - public override async Task Select_datetime_minute_component(bool async) - { - await base.Select_datetime_minute_component(async); + public override Task Select_datetime_minute_component(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_datetime_minute_component(a); - AssertSql( - """ + AssertSql( + """ SELECT c["OrderDate"] FROM root c WHERE (c["Discriminator"] = "Order") """); - } + }); - public override async Task Select_datetime_second_component(bool async) - { - await base.Select_datetime_second_component(async); + public override Task Select_datetime_second_component(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_datetime_second_component(a); - AssertSql( - """ + AssertSql( + """ SELECT c["OrderDate"] FROM root c WHERE (c["Discriminator"] = "Order") """); - } + }); - public override async Task Select_datetime_millisecond_component(bool async) - { - await base.Select_datetime_millisecond_component(async); + public override Task Select_datetime_millisecond_component(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_datetime_millisecond_component(a); - AssertSql( - """ + AssertSql( + """ SELECT c["OrderDate"] FROM root c WHERE (c["Discriminator"] = "Order") """); - } + }); - public override async Task Select_byte_constant(bool async) - { - await base.Select_byte_constant(async); + public override Task Select_byte_constant(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_byte_constant(a); - AssertSql( - """ + AssertSql( + """ SELECT VALUE {"c" : ((c["CustomerID"] = "ALFKI") ? 1 : 2)} FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); - public override async Task Select_short_constant(bool async) - { - await base.Select_short_constant(async); + public override Task Select_short_constant(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_short_constant(a); - AssertSql( - """ + AssertSql( + """ SELECT VALUE {"c" : ((c["CustomerID"] = "ALFKI") ? 1 : 2)} FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); - public override async Task Select_bool_constant(bool async) - { - await base.Select_bool_constant(async); + public override Task Select_bool_constant(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_bool_constant(a); - AssertSql( - """ + AssertSql( + """ SELECT VALUE {"c" : ((c["CustomerID"] = "ALFKI") ? true : false)} FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); - public override async Task Anonymous_projection_AsNoTracking_Selector(bool async) - { - await base.Anonymous_projection_AsNoTracking_Selector(async); + public override Task Anonymous_projection_AsNoTracking_Selector(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Anonymous_projection_AsNoTracking_Selector(a); - AssertSql( - """ + AssertSql( + """ SELECT c["OrderDate"] FROM root c WHERE (c["Discriminator"] = "Order") """); - } + }); - public override async Task Anonymous_projection_with_repeated_property_being_ordered(bool async) - { - await base.Anonymous_projection_with_repeated_property_being_ordered(async); + public override Task Anonymous_projection_with_repeated_property_being_ordered(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Anonymous_projection_with_repeated_property_being_ordered(a); - AssertSql( - """ + AssertSql( + """ SELECT VALUE {"A" : c["CustomerID"]} FROM root c WHERE (c["Discriminator"] = "Customer") ORDER BY c["CustomerID"] """); - } + }); public override async Task Anonymous_projection_with_repeated_property_being_ordered_2(bool async) { @@ -877,17 +979,19 @@ public override async Task Anonymous_projection_with_repeated_property_being_ord AssertSql(); } - public override async Task Select_GetValueOrDefault_on_DateTime(bool async) - { - await base.Select_GetValueOrDefault_on_DateTime(async); + public override Task Select_GetValueOrDefault_on_DateTime(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_GetValueOrDefault_on_DateTime(a); - AssertSql( - """ + AssertSql( + """ SELECT c["OrderDate"] FROM root c WHERE (c["Discriminator"] = "Order") """); - } + }); public override async Task Select_GetValueOrDefault_on_DateTime_with_null_values(bool async) { @@ -897,29 +1001,33 @@ public override async Task Select_GetValueOrDefault_on_DateTime_with_null_values AssertSql(); } - public override async Task Client_method_in_projection_requiring_materialization_1(bool async) - { - await base.Client_method_in_projection_requiring_materialization_1(async); + public override Task Client_method_in_projection_requiring_materialization_1(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Client_method_in_projection_requiring_materialization_1(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND STARTSWITH(c["CustomerID"], "A")) """); - } + }); - public override async Task Client_method_in_projection_requiring_materialization_2(bool async) - { - await base.Client_method_in_projection_requiring_materialization_2(async); + public override Task Client_method_in_projection_requiring_materialization_2(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Client_method_in_projection_requiring_materialization_2(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND STARTSWITH(c["CustomerID"], "A")) """); - } + }); public override async Task Multiple_select_many_with_predicate(bool async) { @@ -1065,17 +1173,19 @@ public override async Task Select_entity_compared_to_null(bool async) AssertSql(); } - public override async Task Explicit_cast_in_arithmetic_operation_is_preserved(bool async) - { - await base.Explicit_cast_in_arithmetic_operation_is_preserved(async); + public override Task Explicit_cast_in_arithmetic_operation_is_preserved(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Explicit_cast_in_arithmetic_operation_is_preserved(a); - AssertSql( - """ + AssertSql( + """ SELECT VALUE {"OrderID" : c["OrderID"], "c" : (c["OrderID"] + 1000)} FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderID"] = 10250)) """); - } + }); public override async Task SelectMany_whose_selector_references_outer_source(bool async) { @@ -1125,17 +1235,19 @@ public override async Task Collection_projection_AsNoTracking_OrderBy(bool async AssertSql(); } - public override async Task Coalesce_over_nullable_uint(bool async) - { - await base.Coalesce_over_nullable_uint(async); + public override Task Coalesce_over_nullable_uint(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Coalesce_over_nullable_uint(a); - AssertSql( - """ + AssertSql( + """ SELECT VALUE {"c" : ((c["EmployeeID"] != null) ? c["EmployeeID"] : 0)} FROM root c WHERE (c["Discriminator"] = "Order") """); - } + }); public override async Task Project_uint_through_collection_FirstOrDefault(bool async) { @@ -1153,31 +1265,35 @@ public override async Task Project_keyless_entity_FirstOrDefault_without_orderby AssertSql(); } - public override async Task Reverse_changes_asc_order_to_desc(bool async) - { - await base.Reverse_changes_asc_order_to_desc(async); + public override Task Reverse_changes_asc_order_to_desc(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Reverse_changes_asc_order_to_desc(a); - AssertSql( - """ + AssertSql( + """ SELECT c["EmployeeID"] FROM root c WHERE (c["Discriminator"] = "Employee") ORDER BY c["EmployeeID"] DESC """); - } + }); - public override async Task Reverse_changes_desc_order_to_asc(bool async) - { - await base.Reverse_changes_desc_order_to_asc(async); + public override Task Reverse_changes_desc_order_to_asc(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Reverse_changes_desc_order_to_asc(a); - AssertSql( - """ + AssertSql( + """ SELECT c["EmployeeID"] FROM root c WHERE (c["Discriminator"] = "Employee") ORDER BY c["EmployeeID"] """); - } + }); public override async Task Projection_AsEnumerable_projection(bool async) { @@ -1187,18 +1303,20 @@ public override async Task Projection_AsEnumerable_projection(bool async) AssertSql(); } - public override async Task Projection_custom_type_in_both_sides_of_ternary(bool async) - { - await base.Projection_custom_type_in_both_sides_of_ternary(async); + public override Task Projection_custom_type_in_both_sides_of_ternary(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Projection_custom_type_in_both_sides_of_ternary(a); - AssertSql( - """ + AssertSql( + """ SELECT VALUE {"c" : (c["City"] = "Seattle")} FROM root c WHERE (c["Discriminator"] = "Customer") ORDER BY c["CustomerID"] """); - } + }); public override async Task Projecting_multiple_collection_with_same_constant_works(bool async) { @@ -1284,12 +1402,14 @@ await AssertTranslationFailed( AssertSql(); } - public override async Task Projection_take_predicate_projection(bool async) - { - await base.Projection_take_predicate_projection(async); + public override Task Projection_take_predicate_projection(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Projection_take_predicate_projection(a); - AssertSql( - """ + AssertSql( + """ @__p_0='10' SELECT VALUE {"Aggregate" : ((c["CustomerID"] || " ") || c["City"])} @@ -1298,14 +1418,16 @@ FROM root c ORDER BY c["CustomerID"] OFFSET 0 LIMIT @__p_0 """); - } + }); - public override async Task Projection_take_projection_doesnt_project_intermittent_column(bool async) - { - await base.Projection_take_projection_doesnt_project_intermittent_column(async); + public override Task Projection_take_projection_doesnt_project_intermittent_column(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Projection_take_projection_doesnt_project_intermittent_column(a); - AssertSql( - """ + AssertSql( + """ @__p_0='10' SELECT VALUE {"Aggregate" : ((c["CustomerID"] || " ") || c["City"])} @@ -1314,7 +1436,7 @@ FROM root c ORDER BY c["CustomerID"] OFFSET 0 LIMIT @__p_0 """); - } + }); public override async Task Projection_skip_projection_doesnt_project_intermittent_column(bool async) { @@ -1378,18 +1500,20 @@ await AssertTranslationFailed( AssertSql(); } - public override async Task Ternary_in_client_eval_assigns_correct_types(bool async) - { - await base.Ternary_in_client_eval_assigns_correct_types(async); + public override Task Ternary_in_client_eval_assigns_correct_types(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Ternary_in_client_eval_assigns_correct_types(a); - AssertSql( - """ + AssertSql( + """ SELECT VALUE {"CustomerID" : c["CustomerID"], "OrderDate" : c["OrderDate"], "c" : (c["OrderID"] - 10000)} FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderID"] < 10300)) ORDER BY c["OrderID"] """); - } + }); public override async Task Collection_include_over_result_of_single_non_scalar(bool async) { @@ -1543,16 +1667,20 @@ public override async Task Reverse_in_projection_scalar_subquery(bool async) public override async Task Reverse_after_orderby_thenby(bool async) { - await Assert.ThrowsAsync( - () => base.Reverse_after_orderby_thenby(async)); + // Always throws for sync. + if (async) + { + await Assert.ThrowsAsync( + () => base.Reverse_after_orderby_thenby(async)); - AssertSql( - """ + AssertSql( + """ SELECT c["EmployeeID"] FROM root c WHERE (c["Discriminator"] = "Employee") ORDER BY c["EmployeeID"] DESC, c["City"] """); + } } public override async Task Reverse_after_orderBy_and_take(bool async) @@ -1583,252 +1711,295 @@ await AssertTranslationFailed( AssertSql(); } - public override async Task Select_bool_closure(bool async) - { - await base.Select_bool_closure(async); + public override Task Select_bool_closure(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_bool_closure(a); - AssertSql( - """ + AssertSql( + """ SELECT 1 FROM root c WHERE (c["Discriminator"] = "Customer") """, - // - """ + // + """ SELECT 1 FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); - public override async Task Select_datetime_DayOfWeek_component(bool async) - { - await base.Select_datetime_DayOfWeek_component(async); + public override Task Select_datetime_DayOfWeek_component(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_datetime_DayOfWeek_component(a); - AssertSql( - """ + AssertSql( + """ SELECT c["OrderDate"] FROM root c WHERE (c["Discriminator"] = "Order") """); - } + }); - public override async Task Reverse_after_multiple_orderbys(bool async) - { - await base.Reverse_after_multiple_orderbys(async); + public override Task Reverse_after_multiple_orderbys(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Reverse_after_multiple_orderbys(a); - AssertSql( - """ + AssertSql( + """ SELECT c["EmployeeID"] FROM root c WHERE (c["Discriminator"] = "Employee") ORDER BY c["EmployeeID"] """); - } + }); + [ConditionalTheory(Skip = "Always does sync evaluation.")] public override async Task VisitLambda_should_not_be_visited_trivially(bool async) { - await base.VisitLambda_should_not_be_visited_trivially(async); + // Always throws for sync. + if (async) + { + await base.VisitLambda_should_not_be_visited_trivially(async); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Order") AND STARTSWITH(c["CustomerID"], "A")) """); + } } - public override async Task Projecting_nullable_struct(bool async) - { - await base.Projecting_nullable_struct(async); + public override Task Projecting_nullable_struct(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Projecting_nullable_struct(a); - AssertSql( - """ + AssertSql( + """ SELECT c["CustomerID"], (c["CustomerID"] = "ALFKI") AS c, c["OrderID"], LENGTH(c["CustomerID"]) AS c0 FROM root c WHERE (c["Discriminator"] = "Order") """); - } + }); - public override async Task Select_customer_identity(bool async) - { - await base.Select_customer_identity(async); + public override Task Select_customer_identity(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_customer_identity(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); - public override async Task Projection_with_parameterized_constructor(bool async) - { - await base.Projection_with_parameterized_constructor(async); + public override Task Projection_with_parameterized_constructor(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Projection_with_parameterized_constructor(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = "ALFKI")) """); - } + }); - public override async Task Select_anonymous_nested(bool async) - { - await base.Select_anonymous_nested(async); + public override Task Select_anonymous_nested(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_anonymous_nested(a); - AssertSql( - """ + AssertSql( + """ SELECT c["City"], c["Country"] FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); - public override async Task Cast_on_top_level_projection_brings_explicit_Cast(bool async) - { - await base.Cast_on_top_level_projection_brings_explicit_Cast(async); + public override Task Cast_on_top_level_projection_brings_explicit_Cast(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Cast_on_top_level_projection_brings_explicit_Cast(a); - AssertSql( - """ + AssertSql( + """ SELECT c["OrderID"] FROM root c WHERE (c["Discriminator"] = "Order") """); - } + }); - public override async Task Select_anonymous_empty(bool async) - { - await base.Select_anonymous_empty(async); + public override Task Select_anonymous_empty(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_anonymous_empty(a); - AssertSql( - """ + AssertSql( + """ SELECT 1 FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); - public override async Task Select_scalar_primitive(bool async) - { - await base.Select_scalar_primitive(async); + public override Task Select_scalar_primitive(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_scalar_primitive(a); - AssertSql( - """ + AssertSql( + """ SELECT c["EmployeeID"] FROM root c WHERE (c["Discriminator"] = "Employee") """); - } + }); - public override async Task Select_into(bool async) - { - await base.Select_into(async); + public override Task Select_into(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_into(a); - AssertSql( - """ + AssertSql( + """ SELECT c["CustomerID"] FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = "ALFKI")) """); - } + }); - public override async Task Projection_with_parameterized_constructor_with_member_assignment(bool async) - { - await base.Projection_with_parameterized_constructor_with_member_assignment(async); + public override Task Projection_with_parameterized_constructor_with_member_assignment(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Projection_with_parameterized_constructor_with_member_assignment(a); - AssertSql( - """ + AssertSql( + """ SELECT c, c["City"] FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = "ALFKI")) """); - } + }); - public override async Task Select_datetime_TimeOfDay_component(bool async) - { - await base.Select_datetime_TimeOfDay_component(async); + public override Task Select_datetime_TimeOfDay_component(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_datetime_TimeOfDay_component(a); - AssertSql( - """ + AssertSql( + """ SELECT c["OrderDate"] FROM root c WHERE (c["Discriminator"] = "Order") """); - } + }); - public override async Task Select_with_complex_expression_that_can_be_funcletized(bool async) - { - await base.Select_with_complex_expression_that_can_be_funcletized(async); + public override Task Select_with_complex_expression_that_can_be_funcletized(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_with_complex_expression_that_can_be_funcletized(a); - AssertSql( - """ + AssertSql( + """ SELECT INDEX_OF(c["ContactName"], "") AS c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = "ALFKI")) """); - } + }); - public override async Task Select_datetime_Ticks_component(bool async) - { - await base.Select_datetime_Ticks_component(async); + public override Task Select_datetime_Ticks_component(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_datetime_Ticks_component(a); - AssertSql( - """ + AssertSql( + """ SELECT c["OrderDate"] FROM root c WHERE (c["Discriminator"] = "Order") """); - } + }); - public override async Task Select_anonymous_literal(bool async) - { - await base.Select_anonymous_literal(async); + public override Task Select_anonymous_literal(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_anonymous_literal(a); - AssertSql( - """ + AssertSql( + """ SELECT VALUE {"X" : 10} FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); - public override async Task Select_customer_table(bool async) - { - await base.Select_customer_table(async); + public override Task Select_customer_table(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_customer_table(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); - public override async Task Select_over_10_nested_ternary_condition(bool async) - { - await base.Select_over_10_nested_ternary_condition(async); + public override Task Select_over_10_nested_ternary_condition(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Select_over_10_nested_ternary_condition(a); - AssertSql( - """ + AssertSql( + """ SELECT VALUE {"c" : ((c["CustomerID"] = "1") ? "01" : ((c["CustomerID"] = "2") ? "02" : ((c["CustomerID"] = "3") ? "03" : ((c["CustomerID"] = "4") ? "04" : ((c["CustomerID"] = "5") ? "05" : ((c["CustomerID"] = "6") ? "06" : ((c["CustomerID"] = "7") ? "07" : ((c["CustomerID"] = "8") ? "08" : ((c["CustomerID"] = "9") ? "09" : ((c["CustomerID"] = "10") ? "10" : ((c["CustomerID"] = "11") ? "11" : null)))))))))))} FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); - public override async Task Using_enumerable_parameter_in_projection(bool async) - { - await base.Using_enumerable_parameter_in_projection(async); + public override Task Using_enumerable_parameter_in_projection(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Using_enumerable_parameter_in_projection(a); - AssertSql( - """ + AssertSql( + """ SELECT c["CustomerID"] FROM root c WHERE ((c["Discriminator"] = "Customer") AND STARTSWITH(c["CustomerID"], "F")) """); - } + }); [ConditionalTheory(Skip = "Cross collection join Issue#17246")] public override Task List_from_result_of_single_result(bool async) @@ -1842,17 +2013,19 @@ public override Task List_from_result_of_single_result_2(bool async) public override Task List_from_result_of_single_result_3(bool async) => base.List_from_result_of_single_result_3(async); - public override async Task Entity_passed_to_DTO_constructor_works(bool async) - { - await base.Entity_passed_to_DTO_constructor_works(async); + public override Task Entity_passed_to_DTO_constructor_works(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Entity_passed_to_DTO_constructor_works(a); - AssertSql( -""" + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); public override async Task Set_operation_in_pending_collection(bool async) { diff --git a/test/EFCore.Cosmos.FunctionalTests/Query/NorthwindWhereQueryCosmosTest.cs b/test/EFCore.Cosmos.FunctionalTests/Query/NorthwindWhereQueryCosmosTest.cs index be6a5056181..f155b73d375 100644 --- a/test/EFCore.Cosmos.FunctionalTests/Query/NorthwindWhereQueryCosmosTest.cs +++ b/test/EFCore.Cosmos.FunctionalTests/Query/NorthwindWhereQueryCosmosTest.cs @@ -26,108 +26,128 @@ public virtual void Check_all_tests_overridden() [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual async Task Where_add(bool async) - { - await AssertQuery( - async, - ss => ss.Set().Where(o => o.OrderID + 10 == 10258)); + public virtual Task Where_add(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await AssertQuery( + a, + ss => ss.Set().Where(o => o.OrderID + 10 == 10258)); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Order") AND ((c["OrderID"] + 10) = 10258)) """); - } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual async Task Where_subtract(bool async) - { - await AssertQuery( - async, - ss => ss.Set().Where(o => o.OrderID - 10 == 10238)); + public virtual Task Where_subtract(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await AssertQuery( + a, + ss => ss.Set().Where(o => o.OrderID - 10 == 10238)); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Order") AND ((c["OrderID"] - 10) = 10238)) """); - } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual async Task Where_multiply(bool async) - { - await AssertQuery( - async, - ss => ss.Set().Where(o => o.OrderID * 1 == 10248)); + public virtual Task Where_multiply(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await AssertQuery( + a, + ss => ss.Set().Where(o => o.OrderID * 1 == 10248)); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Order") AND ((c["OrderID"] * 1) = 10248)) """); - } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual async Task Where_divide(bool async) - { - await AssertQuery( - async, - ss => ss.Set().Where(o => o.OrderID / 1 == 10248)); + public virtual Task Where_divide(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await AssertQuery( + a, + ss => ss.Set().Where(o => o.OrderID / 1 == 10248)); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Order") AND ((c["OrderID"] / 1) = 10248)) """); - } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual async Task Where_modulo(bool async) - { - await AssertQuery( - async, - ss => ss.Set().Where(o => o.OrderID % 10248 == 0)); + public virtual Task Where_modulo(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await AssertQuery( + a, + ss => ss.Set().Where(o => o.OrderID % 10248 == 0)); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Order") AND ((c["OrderID"] % 10248) = 0)) """); - } + }); public override async Task Where_bitwise_or(bool async) { - // Bitwise operators on booleans. Issue #13168. - await Assert.ThrowsAsync(() => base.Where_bitwise_or(async)); + // Always throws for sync. + if (async) + { + await Fixture.NoSyncTest( + async, async a => + { + // Bitwise operators on booleans. Issue #13168. + await Assert.ThrowsAsync(() => base.Where_bitwise_or(async)); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND ((c["CustomerID"] = "ALFKI") | (c["CustomerID"] = "ANATR"))) """); + }); + } } - public override async Task Where_bitwise_and(bool async) - { - await base.Where_bitwise_and(async); + public override Task Where_bitwise_and(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_bitwise_and(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND ((c["CustomerID"] = "ALFKI") & (c["CustomerID"] = "ANATR"))) """); - } + }); public override async Task Where_bitwise_xor(bool async) { @@ -141,273 +161,307 @@ public override async Task Where_bitwise_xor(bool async) [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual async Task Where_bitwise_leftshift(bool async) - { - await AssertQuery( - async, - ss => ss.Set().Where(o => (o.OrderID << 1) == 20496)); + public virtual Task Where_bitwise_leftshift(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await AssertQuery( + a, + ss => ss.Set().Where(o => (o.OrderID << 1) == 20496)); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Order") AND ((c["OrderID"] << 1) = 20496)) """); - } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual async Task Where_bitwise_rightshift(bool async) - { - await AssertQuery( - async, - ss => ss.Set().Where(o => (o.OrderID >> 1) == 5124)); + public virtual Task Where_bitwise_rightshift(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await AssertQuery( + a, + ss => ss.Set().Where(o => (o.OrderID >> 1) == 5124)); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Order") AND ((c["OrderID"] >> 1) = 5124)) """); - } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual async Task Where_logical_and(bool async) - { - await AssertQuery( - async, - ss => ss.Set().Where(c => c.City == "Seattle" && c.ContactTitle == "Owner")); + public virtual Task Where_logical_and(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await AssertQuery( + a, + ss => ss.Set().Where(c => c.City == "Seattle" && c.ContactTitle == "Owner")); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND ((c["City"] = "Seattle") AND (c["ContactTitle"] = "Owner"))) """); - } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual async Task Where_logical_or(bool async) - { - await AssertQuery( - async, - ss => ss.Set().Where(c => c.CustomerID == "ALFKI" || c.CustomerID == "ANATR")); + public virtual Task Where_logical_or(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await AssertQuery( + a, + ss => ss.Set().Where(c => c.CustomerID == "ALFKI" || c.CustomerID == "ANATR")); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND ((c["CustomerID"] = "ALFKI") OR (c["CustomerID"] = "ANATR"))) """); - } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual async Task Where_logical_not(bool async) - { - await AssertQuery( - async, - ss => ss.Set().Where(c => !(c.City != "Seattle"))); + public virtual Task Where_logical_not(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await AssertQuery( + a, + ss => ss.Set().Where(c => !(c.City != "Seattle"))); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND NOT((c["City"] != "Seattle"))) """); - } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual async Task Where_equality(bool async) - { - await AssertQuery( - async, - ss => ss.Set().Where(e => e.ReportsTo == 2)); + public virtual Task Where_equality(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await AssertQuery( + a, + ss => ss.Set().Where(e => e.ReportsTo == 2)); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Employee") AND (c["ReportsTo"] = 2)) """); - } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual async Task Where_inequality(bool async) - { - await AssertQuery( - async, - ss => ss.Set().Where(e => e.ReportsTo != 2)); + public virtual Task Where_inequality(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await AssertQuery( + a, + ss => ss.Set().Where(e => e.ReportsTo != 2)); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Employee") AND (c["ReportsTo"] != 2)) """); - } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual async Task Where_greaterthan(bool async) - { - await AssertQuery( - async, - ss => ss.Set().Where(e => e.ReportsTo > 2)); + public virtual Task Where_greaterthan(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await AssertQuery( + a, + ss => ss.Set().Where(e => e.ReportsTo > 2)); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Employee") AND (c["ReportsTo"] > 2)) """); - } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual async Task Where_greaterthanorequal(bool async) - { - await AssertQuery( - async, - ss => ss.Set().Where(e => e.ReportsTo >= 2)); + public virtual Task Where_greaterthanorequal(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await AssertQuery( + a, + ss => ss.Set().Where(e => e.ReportsTo >= 2)); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Employee") AND (c["ReportsTo"] >= 2)) """); - } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual async Task Where_lessthan(bool async) - { - await AssertQuery( - async, - ss => ss.Set().Where(e => e.ReportsTo < 3)); + public virtual Task Where_lessthan(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await AssertQuery( + a, + ss => ss.Set().Where(e => e.ReportsTo < 3)); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Employee") AND (c["ReportsTo"] < 3)) """); - } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual async Task Where_lessthanorequal(bool async) - { - await AssertQuery( - async, - ss => ss.Set().Where(e => e.ReportsTo <= 2)); + public virtual Task Where_lessthanorequal(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await AssertQuery( + a, + ss => ss.Set().Where(e => e.ReportsTo <= 2)); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Employee") AND (c["ReportsTo"] <= 2)) """); - } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual async Task Where_string_concat(bool async) - { - await AssertQuery( - async, - ss => ss.Set().Where(c => c.CustomerID + "END" == "ALFKIEND")); + public virtual Task Where_string_concat(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await AssertQuery( + a, + ss => ss.Set().Where(c => c.CustomerID + "END" == "ALFKIEND")); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND ((c["CustomerID"] || "END") = "ALFKIEND")) """); - } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual async Task Where_unary_minus(bool async) - { - await AssertQuery( - async, - ss => ss.Set().Where(o => -o.OrderID == -10248)); + public virtual Task Where_unary_minus(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await AssertQuery( + a, + ss => ss.Set().Where(o => -o.OrderID == -10248)); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Order") AND (-(c["OrderID"]) = -10248)) """); - } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual async Task Where_bitwise_not(bool async) - { - await AssertQuery( - async, - ss => ss.Set().Where(o => ~o.OrderID == -10249)); + public virtual Task Where_bitwise_not(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await AssertQuery( + a, + ss => ss.Set().Where(o => ~o.OrderID == -10249)); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Order") AND (~(c["OrderID"]) = -10249)) """); - } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual async Task Where_ternary(bool async) - { - await AssertQuery( - async, + public virtual Task Where_ternary(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await AssertQuery( + a, #pragma warning disable IDE0029 // Use coalesce expression - ss => ss.Set().Where(c => (c.Region != null ? c.Region : "SP") == "BC")); + ss => ss.Set().Where(c => (c.Region != null ? c.Region : "SP") == "BC")); #pragma warning restore IDE0029 // Use coalesce expression - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (((c["Region"] != null) ? c["Region"] : "SP") = "BC")) """); - } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual async Task Where_coalesce(bool async) - { - await AssertQuery( - async, - ss => ss.Set().Where(c => (c.Region ?? "SP") == "BC")); + public virtual Task Where_coalesce(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await AssertQuery( + a, + ss => ss.Set().Where(c => (c.Region ?? "SP") == "BC")); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (((c["Region"] != null) ? c["Region"] : "SP") = "BC")) """); - } + }); - public override async Task Where_simple(bool async) - { - await base.Where_simple(async); + public override Task Where_simple(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_simple(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["City"] = "London")) """); - } + }); private static readonly Expression> _filter = o => o.CustomerID == "ALFKI"; @@ -421,10 +475,13 @@ public override async Task Where_as_queryable_expression(bool async) public override async Task Where_simple_closure(bool async) { - var queryString = await base.Where_simple_closure(async); + await Fixture.NoSyncTest( + async, async a => + { + var queryString = await base.Where_simple_closure(a); - AssertSql( - """ + AssertSql( + """ @__city_0='London' SELECT c @@ -432,109 +489,122 @@ FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["City"] = @__city_0)) """); - Assert.Equal( - """ + Assert.Equal( + """ -- @__city_0='London' SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["City"] = @__city_0)) """, queryString, ignoreLineEndingDifferences: true, - ignoreWhiteSpaceDifferences: true); + ignoreWhiteSpaceDifferences: true); + }); return null; } - public override async Task Where_indexer_closure(bool async) - { - await base.Where_indexer_closure(async); + public override Task Where_indexer_closure(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_indexer_closure(a); - AssertSql( - """ + AssertSql( + """ @__p_0='London' SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["City"] = @__p_0)) """); - } + }); - public override async Task Where_dictionary_key_access_closure(bool async) - { - await base.Where_dictionary_key_access_closure(async); + public override Task Where_dictionary_key_access_closure(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_dictionary_key_access_closure(a); - AssertSql( - """ + AssertSql( + """ @__get_Item_0='London' SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["City"] = @__get_Item_0)) """); - } + }); - public override async Task Where_tuple_item_closure(bool async) - { - await base.Where_tuple_item_closure(async); + public override Task Where_tuple_item_closure(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_tuple_item_closure(a); - AssertSql( - """ + AssertSql( + """ @__predicateTuple_Item2_0='London' SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["City"] = @__predicateTuple_Item2_0)) """); - } + }); - public override async Task Where_named_tuple_item_closure(bool async) - { - await base.Where_named_tuple_item_closure(async); + public override Task Where_named_tuple_item_closure(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_named_tuple_item_closure(a); - AssertSql( - """ + AssertSql( + """ @__predicateTuple_Item2_0='London' SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["City"] = @__predicateTuple_Item2_0)) """); - } + }); - public override async Task Where_simple_closure_constant(bool async) - { - await base.Where_simple_closure_constant(async); + public override Task Where_simple_closure_constant(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_simple_closure_constant(a); - AssertSql( - """ + AssertSql( + """ @__predicate_0='true' SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND @__predicate_0) """); - } + }); - public override async Task Where_simple_closure_via_query_cache(bool async) - { - await base.Where_simple_closure_via_query_cache(async); + public override Task Where_simple_closure_via_query_cache(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_simple_closure_via_query_cache(a); - AssertSql( - """ + AssertSql( + """ @__city_0='London' SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["City"] = @__city_0)) """, - // - """ + // + """ @__city_0='Seattle' SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["City"] = @__city_0)) """); - } + }); public override async Task Where_method_call_nullable_type_closure_via_query_cache(bool async) { @@ -552,203 +622,221 @@ public override async Task Where_method_call_nullable_type_reverse_closure_via_q AssertSql(); } - public override async Task Where_method_call_closure_via_query_cache(bool async) - { - await base.Where_method_call_closure_via_query_cache(async); + public override Task Where_method_call_closure_via_query_cache(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_method_call_closure_via_query_cache(a); - AssertSql( - """ + AssertSql( + """ @__GetCity_0='London' SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["City"] = @__GetCity_0)) """, - // - """ + // + """ @__GetCity_0='Seattle' SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["City"] = @__GetCity_0)) """); - } + }); - public override async Task Where_field_access_closure_via_query_cache(bool async) - { - await base.Where_field_access_closure_via_query_cache(async); + public override Task Where_field_access_closure_via_query_cache(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_field_access_closure_via_query_cache(a); - AssertSql( - """ + AssertSql( + """ @__city_InstanceFieldValue_0='London' SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["City"] = @__city_InstanceFieldValue_0)) """, - // - """ + // + """ @__city_InstanceFieldValue_0='Seattle' SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["City"] = @__city_InstanceFieldValue_0)) """); - } + }); - public override async Task Where_property_access_closure_via_query_cache(bool async) - { - await base.Where_property_access_closure_via_query_cache(async); + public override Task Where_property_access_closure_via_query_cache(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_property_access_closure_via_query_cache(a); - AssertSql( - """ + AssertSql( + """ @__city_InstancePropertyValue_0='London' SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["City"] = @__city_InstancePropertyValue_0)) """, - // - """ + // + """ @__city_InstancePropertyValue_0='Seattle' SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["City"] = @__city_InstancePropertyValue_0)) """); - } + }); - public override async Task Where_static_field_access_closure_via_query_cache(bool async) - { - await base.Where_static_field_access_closure_via_query_cache(async); + public override Task Where_static_field_access_closure_via_query_cache(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_static_field_access_closure_via_query_cache(a); - AssertSql( - """ + AssertSql( + """ @__StaticFieldValue_0='London' SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["City"] = @__StaticFieldValue_0)) """, - // - """ + // + """ @__StaticFieldValue_0='Seattle' SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["City"] = @__StaticFieldValue_0)) """); - } + }); - public override async Task Where_static_property_access_closure_via_query_cache(bool async) - { - await base.Where_static_property_access_closure_via_query_cache(async); + public override Task Where_static_property_access_closure_via_query_cache(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_static_property_access_closure_via_query_cache(a); - AssertSql( - """ + AssertSql( + """ @__StaticPropertyValue_0='London' SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["City"] = @__StaticPropertyValue_0)) """, - // - """ + // + """ @__StaticPropertyValue_0='Seattle' SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["City"] = @__StaticPropertyValue_0)) """); - } + }); - public override async Task Where_nested_field_access_closure_via_query_cache(bool async) - { - await base.Where_nested_field_access_closure_via_query_cache(async); + public override Task Where_nested_field_access_closure_via_query_cache(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_nested_field_access_closure_via_query_cache(a); - AssertSql( - """ + AssertSql( + """ @__city_Nested_InstanceFieldValue_0='London' SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["City"] = @__city_Nested_InstanceFieldValue_0)) """, - // - """ + // + """ @__city_Nested_InstanceFieldValue_0='Seattle' SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["City"] = @__city_Nested_InstanceFieldValue_0)) """); - } + }); - public override async Task Where_nested_property_access_closure_via_query_cache(bool async) - { - await base.Where_nested_property_access_closure_via_query_cache(async); + public override Task Where_nested_property_access_closure_via_query_cache(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_nested_property_access_closure_via_query_cache(a); - AssertSql( - """ + AssertSql( + """ @__city_Nested_InstancePropertyValue_0='London' SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["City"] = @__city_Nested_InstancePropertyValue_0)) """, - // - """ + // + """ @__city_Nested_InstancePropertyValue_0='Seattle' SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["City"] = @__city_Nested_InstancePropertyValue_0)) """); - } + }); - public override async Task Where_new_instance_field_access_query_cache(bool async) - { - await base.Where_new_instance_field_access_query_cache(async); + public override Task Where_new_instance_field_access_query_cache(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_new_instance_field_access_query_cache(a); - AssertSql( - """ + AssertSql( + """ @__InstanceFieldValue_0='London' SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["City"] = @__InstanceFieldValue_0)) """, - // - """ + // + """ @__InstanceFieldValue_0='Seattle' SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["City"] = @__InstanceFieldValue_0)) """); - } + }); - public override async Task Where_new_instance_field_access_closure_via_query_cache(bool async) - { - await base.Where_new_instance_field_access_closure_via_query_cache(async); + public override Task Where_new_instance_field_access_closure_via_query_cache(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_new_instance_field_access_closure_via_query_cache(a); - AssertSql( - """ + AssertSql( + """ @__InstanceFieldValue_0='London' SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["City"] = @__InstanceFieldValue_0)) """, - // - """ + // + """ @__InstanceFieldValue_0='Seattle' SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["City"] = @__InstanceFieldValue_0)) """); - } + }); public override async Task Where_simple_closure_via_query_cache_nullable_type(bool async) { @@ -766,44 +854,50 @@ public override async Task Where_simple_closure_via_query_cache_nullable_type_re AssertSql(); } - public override async Task Where_subquery_closure_via_query_cache(bool async) - { - // Cosmos client evaluation. Issue #17246. - await AssertTranslationFailed(() => base.Where_subquery_closure_via_query_cache(async)); - - AssertSql(); - } + [ConditionalTheory(Skip = "Always uses sync code.")] + public override Task Where_subquery_closure_via_query_cache(bool async) + => Task.CompletedTask; - public override async Task Where_simple_shadow(bool async) - { - await base.Where_simple_shadow(async); + public override Task Where_simple_shadow(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_simple_shadow(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Employee") AND (c["Title"] = "Sales Representative")) """); - } + }); - public override async Task Where_simple_shadow_projection(bool async) - { - await base.Where_simple_shadow_projection(async); + public override Task Where_simple_shadow_projection(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_simple_shadow_projection(a); - AssertSql( - """ + AssertSql( + """ SELECT c["Title"] FROM root c WHERE ((c["Discriminator"] = "Employee") AND (c["Title"] = "Sales Representative")) """); - } + }); public override async Task Where_simple_shadow_subquery(bool async) { - await Assert.ThrowsAsync(() => base.Where_simple_shadow_subquery(async)); + // Always throws for sync. + if (async) + { + await Fixture.NoSyncTest( + async, async a => + { + await Assert.ThrowsAsync(() => base.Where_simple_shadow_subquery(a)); - AssertSql( - """ + AssertSql( + """ @__p_0='5' SELECT c @@ -812,6 +906,8 @@ FROM root c ORDER BY c["EmployeeID"] OFFSET 0 LIMIT @__p_0 """); + }); + } } public override async Task Where_shadow_subquery_FirstOrDefault(bool async) @@ -872,241 +968,273 @@ public override async Task Where_client_deep_inside_predicate_and_server_top_lev AssertSql(); } - public override async Task Where_equals_method_string(bool async) - { - await base.Where_equals_method_string(async); + public override Task Where_equals_method_string(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_equals_method_string(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["City"] = "London")) """); - } + }); - public override async Task Where_equals_method_string_with_ignore_case(bool async) - { - await base.Where_equals_method_string_with_ignore_case(async); + public override Task Where_equals_method_string_with_ignore_case(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_equals_method_string_with_ignore_case(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND STRINGEQUALS(c["City"], "London", true)) """); - } + }); - public override async Task Where_equals_method_int(bool async) - { - await base.Where_equals_method_int(async); + public override Task Where_equals_method_int(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_equals_method_int(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Employee") AND (c["EmployeeID"] = 1)) """); - } + }); - public override async Task Where_equals_using_object_overload_on_mismatched_types(bool async) - { - await base.Where_equals_using_object_overload_on_mismatched_types(async); + public override Task Where_equals_using_object_overload_on_mismatched_types(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_equals_using_object_overload_on_mismatched_types(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Employee") AND false) """); - } + }); - public override async Task Where_equals_using_int_overload_on_mismatched_types(bool async) - { - await base.Where_equals_using_int_overload_on_mismatched_types(async); + public override Task Where_equals_using_int_overload_on_mismatched_types(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_equals_using_int_overload_on_mismatched_types(a); - AssertSql( - """ + AssertSql( + """ @__p_0='1' SELECT c FROM root c WHERE ((c["Discriminator"] = "Employee") AND (c["EmployeeID"] = @__p_0)) """); - } + }); - public override async Task Where_equals_on_mismatched_types_nullable_int_long(bool async) - { - await base.Where_equals_on_mismatched_types_nullable_int_long(async); + public override Task Where_equals_on_mismatched_types_nullable_int_long(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_equals_on_mismatched_types_nullable_int_long(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Employee") AND false) """, - // - """ + // + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Employee") AND false) """); - } + }); - public override async Task Where_equals_on_mismatched_types_nullable_long_nullable_int(bool async) - { - await base.Where_equals_on_mismatched_types_nullable_long_nullable_int(async); + public override Task Where_equals_on_mismatched_types_nullable_long_nullable_int(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_equals_on_mismatched_types_nullable_long_nullable_int(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Employee") AND false) """, - // - """ + // + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Employee") AND false) """); - } + }); - public override async Task Where_equals_on_mismatched_types_int_nullable_int(bool async) - { - await base.Where_equals_on_mismatched_types_int_nullable_int(async); + public override Task Where_equals_on_mismatched_types_int_nullable_int(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_equals_on_mismatched_types_int_nullable_int(a); - AssertSql( - """ + AssertSql( + """ @__intPrm_0='2' SELECT c FROM root c WHERE ((c["Discriminator"] = "Employee") AND (c["ReportsTo"] = @__intPrm_0)) """, - // - """ + // + """ @__intPrm_0='2' SELECT c FROM root c WHERE ((c["Discriminator"] = "Employee") AND (@__intPrm_0 = c["ReportsTo"])) """); - } + }); - public override async Task Where_equals_on_matched_nullable_int_types(bool async) - { - await base.Where_equals_on_matched_nullable_int_types(async); + public override Task Where_equals_on_matched_nullable_int_types(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_equals_on_matched_nullable_int_types(a); - AssertSql( - """ + AssertSql( + """ @__nullableIntPrm_0='2' SELECT c FROM root c WHERE ((c["Discriminator"] = "Employee") AND (@__nullableIntPrm_0 = c["ReportsTo"])) """, - // - """ + // + """ @__nullableIntPrm_0='2' SELECT c FROM root c WHERE ((c["Discriminator"] = "Employee") AND (c["ReportsTo"] = @__nullableIntPrm_0)) """); - } + }); - public override async Task Where_equals_on_null_nullable_int_types(bool async) - { - await base.Where_equals_on_null_nullable_int_types(async); + public override Task Where_equals_on_null_nullable_int_types(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_equals_on_null_nullable_int_types(a); - AssertSql( - """ + AssertSql( + """ @__nullableIntPrm_0=null SELECT c FROM root c WHERE ((c["Discriminator"] = "Employee") AND (@__nullableIntPrm_0 = c["ReportsTo"])) """, - // - """ + // + """ @__nullableIntPrm_0=null SELECT c FROM root c WHERE ((c["Discriminator"] = "Employee") AND (c["ReportsTo"] = @__nullableIntPrm_0)) """); - } + }); - public override async Task Where_comparison_nullable_type_not_null(bool async) - { - await base.Where_comparison_nullable_type_not_null(async); + public override Task Where_comparison_nullable_type_not_null(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_comparison_nullable_type_not_null(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Employee") AND (c["ReportsTo"] = 2)) """); - } + }); - public override async Task Where_comparison_nullable_type_null(bool async) - { - await base.Where_comparison_nullable_type_null(async); + public override Task Where_comparison_nullable_type_null(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_comparison_nullable_type_null(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Employee") AND (c["ReportsTo"] = null)) """); - } + }); - public override async Task Where_string_length(bool async) - { - await base.Where_string_length(async); + public override Task Where_string_length(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_string_length(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (LENGTH(c["City"]) = 6)) """); - } + }); - public override async Task Where_string_indexof(bool async) - { - await base.Where_string_indexof(async); + public override Task Where_string_indexof(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_string_indexof(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (INDEX_OF(c["City"], "Sea") != -1)) """); - } + }); - public override async Task Where_string_replace(bool async) - { - await base.Where_string_replace(async); + public override Task Where_string_replace(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_string_replace(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (REPLACE(c["City"], "Sea", "Rea") = "Reattle")) """); - } + }); - public override async Task Where_string_substring(bool async) - { - await base.Where_string_substring(async); + public override Task Where_string_substring(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_string_substring(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (SUBSTRING(c["City"], 1, 2) = "ea")) """); - } + }); public override async Task Where_datetime_now(bool async) { @@ -1116,33 +1244,37 @@ public override async Task Where_datetime_now(bool async) AssertSql(); } - public override async Task Where_datetime_utcnow(bool async) - { - await base.Where_datetime_utcnow(async); + public override Task Where_datetime_utcnow(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_datetime_utcnow(a); - AssertSql( - """ + AssertSql( + """ @__myDatetime_0='2015-04-10T00:00:00' SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (GetCurrentDateTime() != @__myDatetime_0)) """); - } + }); - public override async Task Where_datetimeoffset_utcnow(bool async) - { - await base.Where_datetimeoffset_utcnow(async); + public override Task Where_datetimeoffset_utcnow(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_datetimeoffset_utcnow(a); - AssertSql( - """ + AssertSql( + """ @__myDatetimeOffset_0='2015-04-10T00:00:00-08:00' SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (GetCurrentDateTime() != @__myDatetimeOffset_0)) """); - } + }); public override async Task Where_datetime_today(bool async) { @@ -1248,101 +1380,117 @@ public override async Task Where_datetimeoffset_utcnow_component(bool async) AssertSql(); } - public override async Task Where_simple_reversed(bool async) - { - await base.Where_simple_reversed(async); + public override Task Where_simple_reversed(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_simple_reversed(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND ("London" = c["City"])) """); - } + }); - public override async Task Where_is_null(bool async) - { - await base.Where_is_null(async); + public override Task Where_is_null(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_is_null(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["Region"] = null)) """); - } + }); - public override async Task Where_null_is_null(bool async) - { - await base.Where_null_is_null(async); + public override Task Where_null_is_null(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_null_is_null(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); - public override async Task Where_constant_is_null(bool async) - { - await base.Where_constant_is_null(async); + public override Task Where_constant_is_null(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_constant_is_null(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND false) """); - } + }); - public override async Task Where_is_not_null(bool async) - { - await base.Where_is_not_null(async); + public override Task Where_is_not_null(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_is_not_null(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["City"] != null)) """); - } + }); - public override async Task Where_null_is_not_null(bool async) - { - await base.Where_null_is_not_null(async); + public override Task Where_null_is_not_null(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_null_is_not_null(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND false) """); - } + }); - public override async Task Where_constant_is_not_null(bool async) - { - await base.Where_constant_is_not_null(async); + public override Task Where_constant_is_not_null(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_constant_is_not_null(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); - public override async Task Where_identity_comparison(bool async) - { - await base.Where_identity_comparison(async); + public override Task Where_identity_comparison(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_identity_comparison(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["City"] = c["City"])) """); - } + }); public override async Task Where_in_optimization_multiple(bool async) { @@ -1392,12 +1540,14 @@ public override async Task Where_select_many_and(bool async) AssertSql(); } - public override async Task Where_primitive(bool async) - { - await base.Where_primitive(async); + public override Task Where_primitive(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_primitive(a); - AssertSql( - """ + AssertSql( + """ @__p_0='9' SELECT c["EmployeeID"] @@ -1405,31 +1555,35 @@ FROM root c WHERE ((c["Discriminator"] = "Employee") AND (c["EmployeeID"] = 5)) OFFSET 0 LIMIT @__p_0 """); - } + }); - public override async Task Where_bool_member(bool async) - { - await base.Where_bool_member(async); + public override Task Where_bool_member(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_bool_member(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Product") AND c["Discontinued"]) """); - } + }); - public override async Task Where_bool_member_false(bool async) - { - await base.Where_bool_member_false(async); + public override Task Where_bool_member_false(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_bool_member_false(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Product") AND NOT(c["Discontinued"])) """); - } + }); public override async Task Where_bool_client_side_negated(bool async) { @@ -1439,293 +1593,337 @@ public override async Task Where_bool_client_side_negated(bool async) AssertSql(); } - public override async Task Where_bool_member_negated_twice(bool async) - { - await base.Where_bool_member_negated_twice(async); + public override Task Where_bool_member_negated_twice(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_bool_member_negated_twice(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Product") AND NOT(NOT((c["Discontinued"] = true)))) """); - } + }); - public override async Task Where_bool_member_shadow(bool async) - { - await base.Where_bool_member_shadow(async); + public override Task Where_bool_member_shadow(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_bool_member_shadow(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Product") AND c["Discontinued"]) """); - } + }); - public override async Task Where_bool_member_false_shadow(bool async) - { - await base.Where_bool_member_false_shadow(async); + public override Task Where_bool_member_false_shadow(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_bool_member_false_shadow(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Product") AND NOT(c["Discontinued"])) """); - } + }); - public override async Task Where_bool_member_equals_constant(bool async) - { - await base.Where_bool_member_equals_constant(async); + public override Task Where_bool_member_equals_constant(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_bool_member_equals_constant(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Product") AND (c["Discontinued"] = true)) """); - } + }); - public override async Task Where_bool_member_in_complex_predicate(bool async) - { - await base.Where_bool_member_in_complex_predicate(async); + public override Task Where_bool_member_in_complex_predicate(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_bool_member_in_complex_predicate(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Product") AND (((c["ProductID"] > 100) AND c["Discontinued"]) OR (c["Discontinued"] = true))) """); - } + }); - public override async Task Where_bool_member_compared_to_binary_expression(bool async) - { - await base.Where_bool_member_compared_to_binary_expression(async); + public override Task Where_bool_member_compared_to_binary_expression(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_bool_member_compared_to_binary_expression(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Product") AND (c["Discontinued"] = (c["ProductID"] > 50))) """); - } + }); - public override async Task Where_not_bool_member_compared_to_not_bool_member(bool async) - { - await base.Where_not_bool_member_compared_to_not_bool_member(async); + public override Task Where_not_bool_member_compared_to_not_bool_member(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_not_bool_member_compared_to_not_bool_member(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Product") AND (NOT(c["Discontinued"]) = NOT(c["Discontinued"]))) """); - } + }); - public override async Task Where_negated_boolean_expression_compared_to_another_negated_boolean_expression(bool async) - { - await base.Where_negated_boolean_expression_compared_to_another_negated_boolean_expression(async); + public override Task Where_negated_boolean_expression_compared_to_another_negated_boolean_expression(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_negated_boolean_expression_compared_to_another_negated_boolean_expression(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Product") AND (NOT((c["ProductID"] > 50)) = NOT((c["ProductID"] > 20)))) """); - } + }); - public override async Task Where_not_bool_member_compared_to_binary_expression(bool async) - { - await base.Where_not_bool_member_compared_to_binary_expression(async); + public override Task Where_not_bool_member_compared_to_binary_expression(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_not_bool_member_compared_to_binary_expression(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Product") AND (NOT(c["Discontinued"]) = (c["ProductID"] > 50))) """); - } + }); - public override async Task Where_bool_parameter(bool async) - { - await base.Where_bool_parameter(async); + public override Task Where_bool_parameter(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_bool_parameter(a); - AssertSql( - """ + AssertSql( + """ @__prm_0='true' SELECT c FROM root c WHERE ((c["Discriminator"] = "Product") AND @__prm_0) """); - } + }); - public override async Task Where_bool_parameter_compared_to_binary_expression(bool async) - { - await base.Where_bool_parameter_compared_to_binary_expression(async); + public override Task Where_bool_parameter_compared_to_binary_expression(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_bool_parameter_compared_to_binary_expression(a); - AssertSql( - """ + AssertSql( + """ @__prm_0='true' SELECT c FROM root c WHERE ((c["Discriminator"] = "Product") AND ((c["ProductID"] > 50) != @__prm_0)) """); - } + }); - public override async Task Where_bool_member_and_parameter_compared_to_binary_expression_nested(bool async) - { - await base.Where_bool_member_and_parameter_compared_to_binary_expression_nested(async); + public override Task Where_bool_member_and_parameter_compared_to_binary_expression_nested(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_bool_member_and_parameter_compared_to_binary_expression_nested(a); - AssertSql( - """ + AssertSql( + """ @__prm_0='true' SELECT c FROM root c WHERE ((c["Discriminator"] = "Product") AND (c["Discontinued"] = ((c["ProductID"] > 50) != @__prm_0))) """); - } + }); - public override async Task Where_de_morgan_or_optimized(bool async) - { - await base.Where_de_morgan_or_optimized(async); + public override Task Where_de_morgan_or_optimized(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_de_morgan_or_optimized(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Product") AND NOT((c["Discontinued"] OR (c["ProductID"] < 20)))) """); - } + }); - public override async Task Where_de_morgan_and_optimized(bool async) - { - await base.Where_de_morgan_and_optimized(async); + public override Task Where_de_morgan_and_optimized(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_de_morgan_and_optimized(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Product") AND NOT((c["Discontinued"] AND (c["ProductID"] < 20)))) """); - } + }); - public override async Task Where_complex_negated_expression_optimized(bool async) - { - await base.Where_complex_negated_expression_optimized(async); + public override Task Where_complex_negated_expression_optimized(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_complex_negated_expression_optimized(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Product") AND NOT((NOT((NOT(c["Discontinued"]) AND (c["ProductID"] < 60))) OR NOT((c["ProductID"] > 30))))) """); - } + }); - public override async Task Where_short_member_comparison(bool async) - { - await base.Where_short_member_comparison(async); + public override Task Where_short_member_comparison(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_short_member_comparison(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Product") AND (c["UnitsInStock"] > 10)) """); - } + }); - public override async Task Where_comparison_to_nullable_bool(bool async) - { - await base.Where_comparison_to_nullable_bool(async); + public override Task Where_comparison_to_nullable_bool(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_comparison_to_nullable_bool(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (ENDSWITH(c["CustomerID"], "KI") = true)) """); - } + }); - public override async Task Where_true(bool async) - { - await base.Where_true(async); + public override Task Where_true(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_true(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); - public override async Task Where_false(bool async) - { - await base.Where_false(async); + public override Task Where_false(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_false(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND false) """); - } + }); - public override async Task Where_bool_closure(bool async) - { - await base.Where_bool_closure(async); + public override Task Where_bool_closure(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_bool_closure(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND false) """, - // - """ + // + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = "ALFKI")) """, - // - """ + // + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = "ALFKI")) """, - // - """ + // + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); - public override async Task Where_default(bool async) - { - await base.Where_default(async); + public override Task Where_default(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_default(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["Fax"] = null)) """); - } + }); - public override async Task Where_expression_invoke_1(bool async) - { - await base.Where_expression_invoke_1(async); + public override Task Where_expression_invoke_1(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_expression_invoke_1(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = "ALFKI")) """); - } + }); public override async Task Where_expression_invoke_2(bool async) { @@ -1735,17 +1933,19 @@ public override async Task Where_expression_invoke_2(bool async) AssertSql(); } - public override async Task Where_expression_invoke_3(bool async) - { - await base.Where_expression_invoke_3(async); + public override Task Where_expression_invoke_3(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_expression_invoke_3(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = "ALFKI")) """); - } + }); public override async Task Where_concat_string_int_comparison1(bool async) { @@ -1779,26 +1979,30 @@ public override async Task Where_concat_string_int_comparison4(bool async) AssertSql(); } - public override async Task Where_string_concat_method_comparison(bool async) - { - await base.Where_string_concat_method_comparison(async); + public override Task Where_string_concat_method_comparison(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_string_concat_method_comparison(a); - AssertSql( - """ + AssertSql( + """ @__i_0='A' SELECT c["CustomerID"] FROM root c WHERE ((c["Discriminator"] = "Customer") AND ((@__i_0 || c["CustomerID"]) = "AAROUT")) """); - } + }); - public override async Task Where_string_concat_method_comparison_2(bool async) - { - await base.Where_string_concat_method_comparison_2(async); + public override Task Where_string_concat_method_comparison_2(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_string_concat_method_comparison_2(a); - AssertSql( - """ + AssertSql( + """ @__i_0='A' @__j_1='B' @@ -1806,14 +2010,16 @@ SELECT c["CustomerID"] FROM root c WHERE ((c["Discriminator"] = "Customer") AND ((@__i_0 || (@__j_1 || c["CustomerID"])) = "ABANATR")) """); - } + }); - public override async Task Where_string_concat_method_comparison_3(bool async) - { - await base.Where_string_concat_method_comparison_3(async); + public override Task Where_string_concat_method_comparison_3(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_string_concat_method_comparison_3(a); - AssertSql( - """ + AssertSql( + """ @__i_0='A' @__j_1='B' @__k_2='C' @@ -1822,69 +2028,79 @@ SELECT c["CustomerID"] FROM root c WHERE ((c["Discriminator"] = "Customer") AND ((@__i_0 || (@__j_1 || (@__k_2 || c["CustomerID"]))) = "ABCANTON")) """); - } + }); - public override async Task Where_ternary_boolean_condition_true(bool async) - { - await base.Where_ternary_boolean_condition_true(async); + public override Task Where_ternary_boolean_condition_true(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_ternary_boolean_condition_true(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Product") AND (c["UnitsInStock"] >= 20)) """); - } + }); - public override async Task Where_ternary_boolean_condition_false(bool async) - { - await base.Where_ternary_boolean_condition_false(async); + public override Task Where_ternary_boolean_condition_false(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_ternary_boolean_condition_false(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Product") AND (c["UnitsInStock"] < 20)) """); - } + }); - public override async Task Where_ternary_boolean_condition_with_another_condition(bool async) - { - await base.Where_ternary_boolean_condition_with_another_condition(async); + public override Task Where_ternary_boolean_condition_with_another_condition(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_ternary_boolean_condition_with_another_condition(a); - AssertSql( - """ + AssertSql( + """ @__productId_0='15' SELECT c FROM root c WHERE ((c["Discriminator"] = "Product") AND ((c["ProductID"] < @__productId_0) AND (c["UnitsInStock"] >= 20))) """); - } + }); - public override async Task Where_ternary_boolean_condition_with_false_as_result_true(bool async) - { - await base.Where_ternary_boolean_condition_with_false_as_result_true(async); + public override Task Where_ternary_boolean_condition_with_false_as_result_true(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_ternary_boolean_condition_with_false_as_result_true(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Product") AND (c["UnitsInStock"] >= 20)) """); - } + }); - public override async Task Where_ternary_boolean_condition_with_false_as_result_false(bool async) - { - await base.Where_ternary_boolean_condition_with_false_as_result_false(async); + public override Task Where_ternary_boolean_condition_with_false_as_result_false(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_ternary_boolean_condition_with_false_as_result_false(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Product") AND false) """); - } + }); public override async Task Where_compare_constructed_equal(bool async) { @@ -1958,41 +2174,47 @@ public override async Task Where_compare_tuple_create_constructed_multi_value_no AssertSql(); } - public override async Task Where_compare_null(bool async) - { - await base.Where_compare_null(async); + public override Task Where_compare_null(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_compare_null(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND ((c["Region"] = null) AND (c["Country"] = "UK"))) """); - } + }); - public override async Task Where_Is_on_same_type(bool async) - { - await base.Where_Is_on_same_type(async); + public override Task Where_Is_on_same_type(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_Is_on_same_type(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); - public override async Task Where_chain(bool async) - { - await base.Where_chain(async); + public override Task Where_chain(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_chain(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (((c["Discriminator"] = "Order") AND (c["CustomerID"] = "QUICK")) AND (c["OrderDate"] > "1998-01-01T00:00:00")) """); - } + }); public override async Task Where_navigation_contains(bool async) { @@ -2007,19 +2229,21 @@ public override async Task Where_navigation_contains(bool async) AssertSql(); } - public override async Task Where_array_index(bool async) - { - await base.Where_array_index(async); + public override Task Where_array_index(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_array_index(a); - AssertSql( - """ + AssertSql( + """ @__p_0='ALFKI' SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = @__p_0)) """); - } + }); public override async Task Where_multiple_contains_in_subquery_with_or(bool async) { @@ -2061,31 +2285,35 @@ public override async Task Where_subquery_FirstOrDefault_compared_to_entity(bool AssertSql(); } - public override async Task Time_of_day_datetime(bool async) - { - await base.Time_of_day_datetime(async); + public override Task Time_of_day_datetime(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Time_of_day_datetime(a); - AssertSql( - """ + AssertSql( + """ SELECT c["OrderDate"] FROM root c WHERE (c["Discriminator"] = "Order") """); - } + }); - public override async Task TypeBinary_short_circuit(bool async) - { - await base.TypeBinary_short_circuit(async); + public override Task TypeBinary_short_circuit(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.TypeBinary_short_circuit(a); - AssertSql( - """ + AssertSql( + """ @__p_0='false' SELECT c FROM root c WHERE ((c["Discriminator"] = "Order") AND @__p_0) """); - } + }); public override async Task Decimal_cast_to_double_works(bool async) { @@ -2095,17 +2323,19 @@ public override async Task Decimal_cast_to_double_works(bool async) AssertSql(); } - public override async Task Where_is_conditional(bool async) - { - await base.Where_is_conditional(async); + public override Task Where_is_conditional(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_is_conditional(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Product") AND (true ? false : true)) """); - } + }); public override async Task Filter_non_nullable_value_after_FirstOrDefault_on_empty_collection(bool async) { @@ -2275,53 +2505,61 @@ public override async Task Where_Queryable_AsEnumerable_Contains_negated(bool as AssertSql(); } - public override async Task Where_list_object_contains_over_value_type(bool async) - { - await base.Where_list_object_contains_over_value_type(async); + public override Task Where_list_object_contains_over_value_type(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_list_object_contains_over_value_type(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Order") AND c["OrderID"] IN (10248, 10249)) """); - } + }); - public override async Task Where_array_of_object_contains_over_value_type(bool async) - { - await base.Where_array_of_object_contains_over_value_type(async); + public override Task Where_array_of_object_contains_over_value_type(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_array_of_object_contains_over_value_type(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Order") AND c["OrderID"] IN (10248, 10249)) """); - } + }); - public override async Task Filter_with_EF_Property_using_closure_for_property_name(bool async) - { - await base.Filter_with_EF_Property_using_closure_for_property_name(async); + public override Task Filter_with_EF_Property_using_closure_for_property_name(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Filter_with_EF_Property_using_closure_for_property_name(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = "ALFKI")) """); - } + }); - public override async Task Filter_with_EF_Property_using_function_for_property_name(bool async) - { - await base.Filter_with_EF_Property_using_function_for_property_name(async); + public override Task Filter_with_EF_Property_using_function_for_property_name(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Filter_with_EF_Property_using_function_for_property_name(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = "ALFKI")) """); - } + }); public override async Task FirstOrDefault_over_scalar_projection_compared_to_null(bool async) { @@ -2451,29 +2689,33 @@ public override async Task Last_over_custom_projection_compared_to_not_null(bool AssertSql(); } - public override async Task Where_Contains_and_comparison(bool async) - { - await base.Where_Contains_and_comparison(async); + public override Task Where_Contains_and_comparison(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_Contains_and_comparison(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] IN ("ALFKI", "FISSA", "WHITC") AND (c["City"] = "Seattle"))) """); - } + }); - public override async Task Where_Contains_or_comparison(bool async) - { - await base.Where_Contains_or_comparison(async); + public override Task Where_Contains_or_comparison(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_Contains_or_comparison(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] IN ("ALFKI", "FISSA") OR (c["City"] = "Seattle"))) """); - } + }); public override async Task Where_Like_and_comparison(bool async) { @@ -2489,240 +2731,278 @@ public override async Task Where_Like_or_comparison(bool async) AssertSql(); } - public override async Task GetType_on_non_hierarchy1(bool async) - { - await base.GetType_on_non_hierarchy1(async); + public override Task GetType_on_non_hierarchy1(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.GetType_on_non_hierarchy1(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); - public override async Task GetType_on_non_hierarchy2(bool async) - { - await base.GetType_on_non_hierarchy2(async); + public override Task GetType_on_non_hierarchy2(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.GetType_on_non_hierarchy2(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND false) """); - } + }); - public override async Task GetType_on_non_hierarchy3(bool async) - { - await base.GetType_on_non_hierarchy3(async); + public override Task GetType_on_non_hierarchy3(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.GetType_on_non_hierarchy3(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND false) """); - } + }); - public override async Task GetType_on_non_hierarchy4(bool async) - { - await base.GetType_on_non_hierarchy4(async); + public override Task GetType_on_non_hierarchy4(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.GetType_on_non_hierarchy4(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "Customer") """); - } + }); - public override async Task Case_block_simplification_works_correctly(bool async) - { - await base.Case_block_simplification_works_correctly(async); + public override Task Case_block_simplification_works_correctly(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Case_block_simplification_works_correctly(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (((c["Region"] = null) ? "OR" : c["Region"]) = "OR")) """); - } + }); - public override async Task Where_compare_null_with_cast_to_object(bool async) - { - await base.Where_compare_null_with_cast_to_object(async); + public override Task Where_compare_null_with_cast_to_object(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_compare_null_with_cast_to_object(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["Region"] = null)) """); - } + }); - public override async Task Where_compare_with_both_cast_to_object(bool async) - { - await base.Where_compare_with_both_cast_to_object(async); + public override Task Where_compare_with_both_cast_to_object(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_compare_with_both_cast_to_object(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["City"] = "London")) """); - } + }); - public override async Task Where_projection(bool async) - { - await base.Where_projection(async); + public override Task Where_projection(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_projection(a); - AssertSql( - """ + AssertSql( + """ SELECT c["CompanyName"] FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["City"] = "London")) """); - } + }); - public override async Task Enclosing_class_settable_member_generates_parameter(bool async) - { - await base.Enclosing_class_settable_member_generates_parameter(async); + public override Task Enclosing_class_settable_member_generates_parameter(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Enclosing_class_settable_member_generates_parameter(a); - AssertSql( - """ + AssertSql( + """ @__SettableProperty_0='10274' SELECT c FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderID"] = @__SettableProperty_0)) """, - // - """ + // + """ @__SettableProperty_0='10275' SELECT c FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderID"] = @__SettableProperty_0)) """); - } + }); - public override async Task Enclosing_class_readonly_member_generates_parameter(bool async) - { - await base.Enclosing_class_readonly_member_generates_parameter(async); + public override Task Enclosing_class_readonly_member_generates_parameter(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Enclosing_class_readonly_member_generates_parameter(a); - AssertSql( - """ + AssertSql( + """ @__ReadOnlyProperty_0='10275' SELECT c FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderID"] = @__ReadOnlyProperty_0)) """); - } + }); - public override async Task Enclosing_class_const_member_does_not_generate_parameter(bool async) - { - await base.Enclosing_class_const_member_does_not_generate_parameter(async); + public override Task Enclosing_class_const_member_does_not_generate_parameter(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Enclosing_class_const_member_does_not_generate_parameter(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderID"] = 10274)) """); - } + }); - public override async Task Generic_Ilist_contains_translates_to_server(bool async) - { - await base.Generic_Ilist_contains_translates_to_server(async); + public override Task Generic_Ilist_contains_translates_to_server(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Generic_Ilist_contains_translates_to_server(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND c["City"] IN ("Seattle")) """); - } + }); - public override async Task Multiple_OrElse_on_same_column_converted_to_in_with_overlap(bool async) - { - await base.Multiple_OrElse_on_same_column_converted_to_in_with_overlap(async); + public override Task Multiple_OrElse_on_same_column_converted_to_in_with_overlap(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Multiple_OrElse_on_same_column_converted_to_in_with_overlap(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND ((((c["CustomerID"] = "ALFKI") OR (c["CustomerID"] = "ANATR")) OR (c["CustomerID"] = "ANTON")) OR (c["CustomerID"] = "ANATR"))) """); - } + }); - public override async Task Multiple_OrElse_on_same_column_with_null_constant_comparison_converted_to_in(bool async) - { - await base.Multiple_OrElse_on_same_column_with_null_constant_comparison_converted_to_in(async); + public override Task Multiple_OrElse_on_same_column_with_null_constant_comparison_converted_to_in(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Multiple_OrElse_on_same_column_with_null_constant_comparison_converted_to_in(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND ((((c["Region"] = "WA") OR (c["Region"] = "OR")) OR (c["Region"] = null)) OR (c["Region"] = "BC"))) """); - } + }); - public override async Task Constant_array_Contains_OrElse_comparison_with_constant_gets_combined_to_one_in(bool async) - { - await base.Constant_array_Contains_OrElse_comparison_with_constant_gets_combined_to_one_in(async); + public override Task Constant_array_Contains_OrElse_comparison_with_constant_gets_combined_to_one_in(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Constant_array_Contains_OrElse_comparison_with_constant_gets_combined_to_one_in(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] IN ("ALFKI", "ANATR") OR (c["CustomerID"] = "ANTON"))) """); - } + }); - public override async Task Constant_array_Contains_OrElse_comparison_with_constant_gets_combined_to_one_in_with_overlap(bool async) - { - await base.Constant_array_Contains_OrElse_comparison_with_constant_gets_combined_to_one_in_with_overlap(async); + public override Task Constant_array_Contains_OrElse_comparison_with_constant_gets_combined_to_one_in_with_overlap(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Constant_array_Contains_OrElse_comparison_with_constant_gets_combined_to_one_in_with_overlap(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (((c["CustomerID"] = "ANTON") OR c["CustomerID"] IN ("ALFKI", "ANATR")) OR (c["CustomerID"] = "ALFKI"))) """); - } + }); - public override async Task Constant_array_Contains_OrElse_another_Contains_gets_combined_to_one_in_with_overlap(bool async) - { - await base.Constant_array_Contains_OrElse_another_Contains_gets_combined_to_one_in_with_overlap(async); + public override Task Constant_array_Contains_OrElse_another_Contains_gets_combined_to_one_in_with_overlap(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Constant_array_Contains_OrElse_another_Contains_gets_combined_to_one_in_with_overlap(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] IN ("ALFKI", "ANATR") OR c["CustomerID"] IN ("ALFKI", "ANTON"))) """); - } + }); - public override async Task Constant_array_Contains_AndAlso_another_Contains_gets_combined_to_one_in_with_overlap(bool async) - { - await base.Constant_array_Contains_AndAlso_another_Contains_gets_combined_to_one_in_with_overlap(async); + public override Task Constant_array_Contains_AndAlso_another_Contains_gets_combined_to_one_in_with_overlap(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Constant_array_Contains_AndAlso_another_Contains_gets_combined_to_one_in_with_overlap(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] NOT IN ("ALFKI", "ANATR") AND c["CustomerID"] NOT IN ("ALFKI", "ANTON"))) """); - } + }); - public override async Task Multiple_AndAlso_on_same_column_converted_to_in_using_parameters(bool async) - { - await base.Multiple_AndAlso_on_same_column_converted_to_in_using_parameters(async); + public override Task Multiple_AndAlso_on_same_column_converted_to_in_using_parameters(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Multiple_AndAlso_on_same_column_converted_to_in_using_parameters(a); - AssertSql( - """ + AssertSql( + """ @__prm1_0='ALFKI' @__prm2_1='ANATR' @__prm3_2='ANTON' @@ -2731,14 +3011,16 @@ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (((c["CustomerID"] != @__prm1_0) AND (c["CustomerID"] != @__prm2_1)) AND (c["CustomerID"] != @__prm3_2))) """); - } + }); - public override async Task Array_of_parameters_Contains_OrElse_comparison_with_constant_gets_combined_to_one_in(bool async) - { - await base.Array_of_parameters_Contains_OrElse_comparison_with_constant_gets_combined_to_one_in(async); + public override Task Array_of_parameters_Contains_OrElse_comparison_with_constant_gets_combined_to_one_in(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Array_of_parameters_Contains_OrElse_comparison_with_constant_gets_combined_to_one_in(a); - AssertSql( - """ + AssertSql( + """ @__prm1_0='ALFKI' @__prm2_1='ANATR' @@ -2746,40 +3028,46 @@ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] IN (@__prm1_0, @__prm2_1) OR (c["CustomerID"] = "ANTON"))) """); - } + }); - public override async Task Multiple_OrElse_on_same_column_with_null_parameter_comparison_converted_to_in(bool async) - { - await base.Multiple_OrElse_on_same_column_with_null_parameter_comparison_converted_to_in(async); + public override Task Multiple_OrElse_on_same_column_with_null_parameter_comparison_converted_to_in(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Multiple_OrElse_on_same_column_with_null_parameter_comparison_converted_to_in(a); - AssertSql( - """ + AssertSql( + """ @__prm_0=null SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND ((((c["Region"] = "WA") OR (c["Region"] = "OR")) OR (c["Region"] = @__prm_0)) OR (c["Region"] = "BC"))) """); - } + }); - public override async Task Parameter_array_Contains_OrElse_comparison_with_constant(bool async) - { - await base.Parameter_array_Contains_OrElse_comparison_with_constant(async); + public override Task Parameter_array_Contains_OrElse_comparison_with_constant(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Parameter_array_Contains_OrElse_comparison_with_constant(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] IN ("ALFKI", "ANATR") OR (c["CustomerID"] = "ANTON"))) """); - } + }); - public override async Task Parameter_array_Contains_OrElse_comparison_with_parameter_with_overlap(bool async) - { - await base.Parameter_array_Contains_OrElse_comparison_with_parameter_with_overlap(async); + public override Task Parameter_array_Contains_OrElse_comparison_with_parameter_with_overlap(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Parameter_array_Contains_OrElse_comparison_with_parameter_with_overlap(a); - AssertSql( - """ + AssertSql( + """ @__prm1_0='ANTON' @__prm2_2='ALFKI' @@ -2787,43 +3075,49 @@ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (((c["CustomerID"] = @__prm1_0) OR c["CustomerID"] IN ("ALFKI", "ANATR")) OR (c["CustomerID"] = @__prm2_2))) """); - } + }); - public override async Task Two_sets_of_comparison_combine_correctly(bool async) - { - await base.Two_sets_of_comparison_combine_correctly(async); + public override Task Two_sets_of_comparison_combine_correctly(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Two_sets_of_comparison_combine_correctly(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] IN ("ALFKI", "ANATR") AND ((c["CustomerID"] = "ANATR") OR (c["CustomerID"] = "ANTON")))) """); - } + }); - public override async Task Two_sets_of_comparison_combine_correctly2(bool async) - { - await base.Two_sets_of_comparison_combine_correctly2(async); + public override Task Two_sets_of_comparison_combine_correctly2(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Two_sets_of_comparison_combine_correctly2(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND ((((c["Region"] != "WA") AND (c["Region"] != "OR")) AND (c["Region"] != null)) OR ((c["Region"] != "WA") AND (c["Region"] != null)))) """); - } + }); - public override async Task Filter_with_property_compared_to_null_wrapped_in_explicit_convert_to_object(bool async) - { - await base.Filter_with_property_compared_to_null_wrapped_in_explicit_convert_to_object(async); + public override Task Filter_with_property_compared_to_null_wrapped_in_explicit_convert_to_object(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Filter_with_property_compared_to_null_wrapped_in_explicit_convert_to_object(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["Region"] = null)) """); - } + }); public override async Task Where_nested_field_access_closure_via_query_cache_error_null(bool async) { @@ -2839,24 +3133,28 @@ public override async Task Where_nested_field_access_closure_via_query_cache_err AssertSql(); } - public override async Task Where_simple_shadow_projection_mixed(bool async) - { - await base.Where_simple_shadow_projection_mixed(async); + public override Task Where_simple_shadow_projection_mixed(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_simple_shadow_projection_mixed(a); - AssertSql( - """ + AssertSql( + """ SELECT VALUE {"e" : c, "Title" : c["Title"]} FROM root c WHERE ((c["Discriminator"] = "Employee") AND (c["Title"] = "Sales Representative")) """); - } + }); - public override async Task Where_primitive_tracked(bool async) - { - await base.Where_primitive_tracked(async); + public override Task Where_primitive_tracked(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_primitive_tracked(a); - AssertSql( - """ + AssertSql( + """ @__p_0='9' SELECT c @@ -2864,14 +3162,16 @@ FROM root c WHERE ((c["Discriminator"] = "Employee") AND (c["EmployeeID"] = 5)) OFFSET 0 LIMIT @__p_0 """); - } + }); - public override async Task Where_primitive_tracked2(bool async) - { - await base.Where_primitive_tracked2(async); + public override Task Where_primitive_tracked2(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_primitive_tracked2(a); - AssertSql( - """ + AssertSql( + """ @__p_0='9' SELECT VALUE {"e" : c} @@ -2879,79 +3179,89 @@ FROM root c WHERE ((c["Discriminator"] = "Employee") AND (c["EmployeeID"] = 5)) OFFSET 0 LIMIT @__p_0 """); - } + }); - public override async Task Where_poco_closure(bool async) - { - await base.Where_poco_closure(async); + public override Task Where_poco_closure(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_poco_closure(a); - AssertSql( - """ + AssertSql( + """ @__entity_equality_customer_0_CustomerID='ALFKI' SELECT c["CustomerID"] FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = @__entity_equality_customer_0_CustomerID)) """, - // - """ + // + """ @__entity_equality_customer_0_CustomerID='ANATR' SELECT c["CustomerID"] FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = @__entity_equality_customer_0_CustomerID)) """); - } + }); - public override async Task Where_concat_string_string_comparison(bool async) - { - await base.Where_concat_string_string_comparison(async); + public override Task Where_concat_string_string_comparison(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Where_concat_string_string_comparison(a); - AssertSql( - """ + AssertSql( + """ @__i_0='A' SELECT c["CustomerID"] FROM root c WHERE ((c["Discriminator"] = "Customer") AND ((@__i_0 || c["CustomerID"]) = "AALFKI")) """); - } + }); - public override async Task EF_Constant(bool async) - { - await base.EF_Constant(async); + public override Task EF_Constant(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.EF_Constant(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = "ALFKI")) """); - } + }); - public override async Task EF_Constant_with_subtree(bool async) - { - await base.EF_Constant_with_subtree(async); + public override Task EF_Constant_with_subtree(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.EF_Constant_with_subtree(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = "ALFKI")) """); - } + }); - public override async Task EF_Constant_does_not_parameterized_as_part_of_bigger_subtree(bool async) - { - await base.EF_Constant_does_not_parameterized_as_part_of_bigger_subtree(async); + public override Task EF_Constant_does_not_parameterized_as_part_of_bigger_subtree(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.EF_Constant_does_not_parameterized_as_part_of_bigger_subtree(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = ("ALF" || "KI"))) """); - } + }); public override async Task EF_Constant_with_non_evaluatable_argument_throws(bool async) { @@ -2960,47 +3270,53 @@ public override async Task EF_Constant_with_non_evaluatable_argument_throws(bool AssertSql(); } - public override async Task EF_Parameter(bool async) - { - await base.EF_Parameter(async); + public override Task EF_Parameter(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.EF_Parameter(a); - AssertSql( - """ + AssertSql( + """ @__p_0='ALFKI' SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = @__p_0)) """); - } + }); - public override async Task EF_Parameter_with_subtree(bool async) - { - await base.EF_Parameter_with_subtree(async); + public override Task EF_Parameter_with_subtree(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.EF_Parameter_with_subtree(a); - AssertSql( - """ + AssertSql( + """ @__p_0='ALFKI' SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = @__p_0)) """); - } + }); - public override async Task EF_Parameter_does_not_parameterized_as_part_of_bigger_subtree(bool async) - { - await base.EF_Parameter_does_not_parameterized_as_part_of_bigger_subtree(async); + public override Task EF_Parameter_does_not_parameterized_as_part_of_bigger_subtree(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.EF_Parameter_does_not_parameterized_as_part_of_bigger_subtree(a); - AssertSql( - """ + AssertSql( + """ @__id_0='ALF' SELECT c FROM root c WHERE ((c["Discriminator"] = "Customer") AND (c["CustomerID"] = (@__id_0 || "KI"))) """); - } + }); public override async Task EF_Parameter_with_non_evaluatable_argument_throws(bool async) { @@ -3009,79 +3325,83 @@ public override async Task EF_Parameter_with_non_evaluatable_argument_throws(boo AssertSql(); } - public override async Task Implicit_cast_in_predicate(bool async) - { - await base.Implicit_cast_in_predicate(async); + public override Task Implicit_cast_in_predicate(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Implicit_cast_in_predicate(a); - AssertSql( -""" + AssertSql( + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["CustomerID"] = "1337")) """, - // - """ + // + """ @__prm_Value_0='1337' SELECT c FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["CustomerID"] = @__prm_Value_0)) """, - // - """ + // + """ @__ToString_0='1337' SELECT c FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["CustomerID"] = @__ToString_0)) """, - // - """ + // + """ @__p_0='1337' SELECT c FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["CustomerID"] = @__p_0)) """, - // - """ + // + """ SELECT c FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["CustomerID"] = "1337")) """); - } + }); - public override async Task Interface_casting_though_generic_method(bool async) - { - await base.Interface_casting_though_generic_method(async); + public override Task Interface_casting_though_generic_method(bool async) + => Fixture.NoSyncTest( + async, async a => + { + await base.Interface_casting_though_generic_method(a); - AssertSql( -""" + AssertSql( + """ @__id_0='10252' SELECT VALUE {"Id" : c["OrderID"]} FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderID"] = @__id_0)) """, - // - """ + // + """ SELECT VALUE {"Id" : c["OrderID"]} FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderID"] = 10252)) """, - // - """ + // + """ SELECT VALUE {"Id" : c["OrderID"]} FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderID"] = 10252)) """, - // - """ + // + """ SELECT VALUE {"Id" : c["OrderID"]} FROM root c WHERE ((c["Discriminator"] = "Order") AND (c["OrderID"] = 10252)) """); - } + }); private void AssertSql(params string[] expected) => Fixture.TestSqlLoggerFactory.AssertBaseline(expected); diff --git a/test/EFCore.Cosmos.FunctionalTests/Query/OwnedQueryCosmosTest.cs b/test/EFCore.Cosmos.FunctionalTests/Query/OwnedQueryCosmosTest.cs index 649465f211c..5e8cf8886aa 100644 --- a/test/EFCore.Cosmos.FunctionalTests/Query/OwnedQueryCosmosTest.cs +++ b/test/EFCore.Cosmos.FunctionalTests/Query/OwnedQueryCosmosTest.cs @@ -23,105 +23,123 @@ public override Task Query_with_owned_entity_equality_operator(bool async) => base.Query_with_owned_entity_equality_operator(async); [ConditionalTheory(Skip = "Count #16146")] - public override async Task Navigation_rewrite_on_owned_collection(bool async) - { - await base.Navigation_rewrite_on_owned_collection(async); - - AssertSql( - """ + public override Task Navigation_rewrite_on_owned_collection(bool async) + => CosmosTestHelpers.Instance.NoSyncTest( + async, async a => + { + await base.Navigation_rewrite_on_owned_collection(a); + + AssertSql( + """ SELECT c FROM root c WHERE ((c[""Discriminator""] = ""LeafB"") OR ((c[""Discriminator""] = ""LeafA"") OR ((c[""Discriminator""] = ""Branch"") OR (c[""Discriminator""] = ""OwnedPerson"")))) """); - } + }); [ConditionalTheory(Skip = "Issue#16926")] - public override async Task Navigation_rewrite_on_owned_collection_with_composition(bool async) - { - await base.Navigation_rewrite_on_owned_collection_with_composition(async); + public override Task Navigation_rewrite_on_owned_collection_with_composition(bool async) + => CosmosTestHelpers.Instance.NoSyncTest( + async, async a => + { + await base.Navigation_rewrite_on_owned_collection_with_composition(a); - AssertSql(" "); - } + AssertSql(" "); + }); [ConditionalTheory(Skip = "Issue#16926")] - public override async Task Navigation_rewrite_on_owned_collection_with_composition_complex(bool async) - { - await base.Navigation_rewrite_on_owned_collection_with_composition_complex(async); - - AssertSql(" "); - } - - public override async Task Navigation_rewrite_on_owned_reference_projecting_entity(bool async) - { - await base.Navigation_rewrite_on_owned_reference_projecting_entity(async); - - AssertSql( - """ + public override Task Navigation_rewrite_on_owned_collection_with_composition_complex(bool async) + => CosmosTestHelpers.Instance.NoSyncTest( + async, async a => + { + await base.Navigation_rewrite_on_owned_collection_with_composition_complex(a); + + AssertSql(" "); + }); + + public override Task Navigation_rewrite_on_owned_reference_projecting_entity(bool async) + => CosmosTestHelpers.Instance.NoSyncTest( + async, async a => + { + await base.Navigation_rewrite_on_owned_reference_projecting_entity(a); + + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] IN ("OwnedPerson", "Branch", "LeafB", "LeafA") AND (c["PersonAddress"]["Country"]["Name"] = "USA")) """); - } + }); - public override async Task Navigation_rewrite_on_owned_reference_projecting_scalar(bool async) - { - await base.Navigation_rewrite_on_owned_reference_projecting_scalar(async); + public override Task Navigation_rewrite_on_owned_reference_projecting_scalar(bool async) + => CosmosTestHelpers.Instance.NoSyncTest( + async, async a => + { + await base.Navigation_rewrite_on_owned_reference_projecting_scalar(a); - AssertSql( - """ + AssertSql( + """ SELECT c["PersonAddress"]["Country"]["Name"] FROM root c WHERE (c["Discriminator"] IN ("OwnedPerson", "Branch", "LeafB", "LeafA") AND (c["PersonAddress"]["Country"]["Name"] = "USA")) """); - } + }); - public override async Task Query_for_base_type_loads_all_owned_navs(bool async) - { - await base.Query_for_base_type_loads_all_owned_navs(async); + public override Task Query_for_base_type_loads_all_owned_navs(bool async) + => CosmosTestHelpers.Instance.NoSyncTest( + async, async a => + { + await base.Query_for_base_type_loads_all_owned_navs(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE c["Discriminator"] IN ("OwnedPerson", "Branch", "LeafB", "LeafA") """); - } + }); - public override async Task Query_for_branch_type_loads_all_owned_navs(bool async) - { - await base.Query_for_branch_type_loads_all_owned_navs(async); + public override Task Query_for_branch_type_loads_all_owned_navs(bool async) + => CosmosTestHelpers.Instance.NoSyncTest( + async, async a => + { + await base.Query_for_branch_type_loads_all_owned_navs(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE c["Discriminator"] IN ("Branch", "LeafA") """); - } + }); - public override async Task Query_for_branch_type_loads_all_owned_navs_tracking(bool async) - { - await base.Query_for_branch_type_loads_all_owned_navs_tracking(async); + public override Task Query_for_branch_type_loads_all_owned_navs_tracking(bool async) + => CosmosTestHelpers.Instance.NoSyncTest( + async, async a => + { + await base.Query_for_branch_type_loads_all_owned_navs_tracking(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE c["Discriminator"] IN ("Branch", "LeafA") """); - } + }); - public override async Task Query_for_leaf_type_loads_all_owned_navs(bool async) - { - await base.Query_for_leaf_type_loads_all_owned_navs(async); + public override Task Query_for_leaf_type_loads_all_owned_navs(bool async) + => CosmosTestHelpers.Instance.NoSyncTest( + async, async a => + { + await base.Query_for_leaf_type_loads_all_owned_navs(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] = "LeafA") """); - } + }); [ConditionalTheory(Skip = "LeftJoin #17314")] public override Task Filter_owned_entity_chained_with_regular_entity_followed_by_projecting_owned_collection(bool async) @@ -189,17 +207,19 @@ public override Task Query_with_owned_entity_equality_method(bool async) public override Task Query_with_owned_entity_equality_object_method(bool async) => base.Query_with_owned_entity_equality_object_method(async); - public override async Task Query_with_OfType_eagerly_loads_correct_owned_navigations(bool async) - { - await base.Query_with_OfType_eagerly_loads_correct_owned_navigations(async); + public override Task Query_with_OfType_eagerly_loads_correct_owned_navigations(bool async) + => CosmosTestHelpers.Instance.NoSyncTest( + async, async a => + { + await base.Query_with_OfType_eagerly_loads_correct_owned_navigations(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] IN ("OwnedPerson", "Branch", "LeafB", "LeafA") AND (c["Discriminator"] = "LeafA")) """); - } + }); [ConditionalTheory(Skip = "Distinct ordering #16156")] public override Task Query_when_subquery(bool async) @@ -241,80 +261,89 @@ public override Task Where_collection_navigation_ToArray_Length_member(bool asyn public override Task GroupBy_with_multiple_aggregates_on_owned_navigation_properties(bool async) => base.GroupBy_with_multiple_aggregates_on_owned_navigation_properties(async); - public override async Task Can_query_on_indexer_properties(bool async) - { - await base.Can_query_on_indexer_properties(async); + public override Task Can_query_on_indexer_properties(bool async) + => CosmosTestHelpers.Instance.NoSyncTest( + async, async a => + { + await base.Can_query_on_indexer_properties(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] IN ("OwnedPerson", "Branch", "LeafB", "LeafA") AND (c["Name"] = "Mona Cy")) """); - } + }); - public override async Task Can_query_on_owned_indexer_properties(bool async) - { - await base.Can_query_on_owned_indexer_properties(async); + public override Task Can_query_on_owned_indexer_properties(bool async) + => CosmosTestHelpers.Instance.NoSyncTest( + async, async a => + { + await base.Can_query_on_owned_indexer_properties(a); - AssertSql( - """ + AssertSql( + """ SELECT c["Name"] FROM root c WHERE (c["Discriminator"] IN ("OwnedPerson", "Branch", "LeafB", "LeafA") AND (c["PersonAddress"]["ZipCode"] = 38654)) """); - } + }); - public override async Task Can_query_on_indexer_property_when_property_name_from_closure(bool async) - { - await base.Can_query_on_indexer_property_when_property_name_from_closure(async); + public override Task Can_query_on_indexer_property_when_property_name_from_closure(bool async) + => CosmosTestHelpers.Instance.NoSyncTest( + async, async a => + { + await base.Can_query_on_indexer_property_when_property_name_from_closure(a); - AssertSql( - """ + AssertSql( + """ SELECT c["Name"] FROM root c WHERE (c["Discriminator"] IN ("OwnedPerson", "Branch", "LeafB", "LeafA") AND (c["Name"] = "Mona Cy")) """); - } + }); - public override async Task Can_project_indexer_properties(bool async) - { - await base.Can_project_indexer_properties(async); + public override Task Can_project_indexer_properties(bool async) + => CosmosTestHelpers.Instance.NoSyncTest( + async, async a => + { + await base.Can_project_indexer_properties(a); - AssertSql( - """ + AssertSql( + """ SELECT c["Name"] FROM root c WHERE c["Discriminator"] IN ("OwnedPerson", "Branch", "LeafB", "LeafA") """); - } + }); - public override async Task Can_project_owned_indexer_properties(bool async) - { - await base.Can_project_owned_indexer_properties(async); + public override Task Can_project_owned_indexer_properties(bool async) + => CosmosTestHelpers.Instance.NoSyncTest( + async, async a => + { + await base.Can_project_owned_indexer_properties(a); - AssertSql( - """ + AssertSql( + """ SELECT c["PersonAddress"]["AddressLine"] FROM root c WHERE c["Discriminator"] IN ("OwnedPerson", "Branch", "LeafB", "LeafA") """); - } + }); - public override async Task Can_project_indexer_properties_converted(bool async) - { - await base.Can_project_indexer_properties_converted(async); + public override Task Can_project_indexer_properties_converted(bool async) + => CosmosTestHelpers.Instance.NoSyncTest( + async, async a => + { + await base.Can_project_indexer_properties_converted(a); - AssertSql( - """ + AssertSql( + """ SELECT c["Name"] FROM root c WHERE c["Discriminator"] IN ("OwnedPerson", "Branch", "LeafB", "LeafA") """); - } - - public override async Task Can_project_owned_indexer_properties_converted(bool async) - => await base.Can_project_owned_indexer_properties_converted(async); + }); [ConditionalTheory(Skip = "OrderBy requires composite index #17246")] public override async Task Can_OrderBy_indexer_properties(bool async) @@ -381,36 +410,40 @@ public override async Task Can_group_by_converted_owned_indexer_property(bool is } [ConditionalTheory(Skip = "Join #17246")] - public override async Task Can_join_on_indexer_property_on_query(bool isAsync) + public override async Task Can_join_on_indexer_property_on_query(bool async) { - await base.Can_join_on_indexer_property_on_query(isAsync); + await base.Can_join_on_indexer_property_on_query(async); AssertSql(" "); } - public override async Task Projecting_indexer_property_ignores_include(bool isAsync) - { - await base.Projecting_indexer_property_ignores_include(isAsync); + public override Task Projecting_indexer_property_ignores_include(bool async) + => CosmosTestHelpers.Instance.NoSyncTest( + async, async a => + { + await base.Projecting_indexer_property_ignores_include(a); - AssertSql( - """ + AssertSql( + """ SELECT VALUE {"Nation" : c["PersonAddress"]["ZipCode"]} FROM root c WHERE c["Discriminator"] IN ("OwnedPerson", "Branch", "LeafB", "LeafA") """); - } + }); - public override async Task Projecting_indexer_property_ignores_include_converted(bool isAsync) - { - await base.Projecting_indexer_property_ignores_include_converted(isAsync); + public override Task Projecting_indexer_property_ignores_include_converted(bool async) + => CosmosTestHelpers.Instance.NoSyncTest( + async, async a => + { + await base.Projecting_indexer_property_ignores_include_converted(a); - AssertSql( - """ + AssertSql( + """ SELECT VALUE {"Nation" : c["PersonAddress"]["ZipCode"]} FROM root c WHERE c["Discriminator"] IN ("OwnedPerson", "Branch", "LeafB", "LeafA") """); - } + }); [ConditionalTheory(Skip = "Subquery #17246")] public override async Task Indexer_property_is_pushdown_into_subquery(bool isAsync) @@ -483,32 +516,216 @@ public override async Task GroupBy_aggregate_on_owned_navigation_in_aggregate_se AssertSql(); } - public override async Task Filter_on_indexer_using_closure(bool async) - { - await base.Filter_on_indexer_using_closure(async); + public override Task Filter_on_indexer_using_closure(bool async) + => CosmosTestHelpers.Instance.NoSyncTest( + async, async a => + { + await base.Filter_on_indexer_using_closure(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] IN ("OwnedPerson", "Branch", "LeafB", "LeafA") AND (c["PersonAddress"]["ZipCode"] = 38654)) """); - } + }); - public override async Task Filter_on_indexer_using_function_argument(bool async) - { - await base.Filter_on_indexer_using_function_argument(async); + public override Task Filter_on_indexer_using_function_argument(bool async) + => CosmosTestHelpers.Instance.NoSyncTest( + async, async a => + { + await base.Filter_on_indexer_using_function_argument(a); - AssertSql( - """ + AssertSql( + """ SELECT c FROM root c WHERE (c["Discriminator"] IN ("OwnedPerson", "Branch", "LeafB", "LeafA") AND (c["PersonAddress"]["ZipCode"] = 38654)) """); + }); + + public override Task Preserve_includes_when_applying_skip_take_after_anonymous_type_select(bool async) + => AssertTranslationFailed(() => base.Preserve_includes_when_applying_skip_take_after_anonymous_type_select(async)); + + public override Task Can_project_owned_indexer_properties_converted(bool async) + => CosmosTestHelpers.Instance.NoSyncTest( + async, async a => + { + await base.Can_project_owned_indexer_properties_converted(a); + + AssertSql( + """ +SELECT c["PersonAddress"]["AddressLine"] +FROM root c +WHERE c["Discriminator"] IN ("OwnedPerson", "Branch", "LeafB", "LeafA") +"""); + }); + + public override Task Can_query_owner_with_different_owned_types_having_same_property_name_in_hierarchy(bool async) + => CosmosTestHelpers.Instance.NoSyncTest( + async, async a => + { + await base.Can_query_owner_with_different_owned_types_having_same_property_name_in_hierarchy(a); + + AssertSql( + """ +SELECT c +FROM root c +WHERE c["Discriminator"] IN ("HeliumBalloon", "HydrogenBalloon") +"""); + }); + + public override Task Client_method_skip_take_loads_owned_navigations_variation_2(bool async) + => CosmosTestHelpers.Instance.NoSyncTest( + async, async a => + { + await base.Client_method_skip_take_loads_owned_navigations_variation_2(a); + + AssertSql( + """ +@__p_0='1' +@__p_1='2' + +SELECT c +FROM root c +WHERE c["Discriminator"] IN ("OwnedPerson", "Branch", "LeafB", "LeafA") +ORDER BY c["Id"] +OFFSET @__p_0 LIMIT @__p_1 +"""); + }); + + public override Task Client_method_skip_take_loads_owned_navigations(bool async) + => CosmosTestHelpers.Instance.NoSyncTest( + async, async a => + { + await base.Client_method_skip_take_loads_owned_navigations(a); + + AssertSql( + """ +@__p_0='1' +@__p_1='2' + +SELECT c +FROM root c +WHERE c["Discriminator"] IN ("OwnedPerson", "Branch", "LeafB", "LeafA") +ORDER BY c["Id"] +OFFSET @__p_0 LIMIT @__p_1 +"""); + }); + + public override async Task Non_nullable_property_through_optional_navigation(bool async) + { + // Sync always throws before getting to exception being tested. + if (async) + { + await CosmosTestHelpers.Instance.NoSyncTest( + async, async a => + { + await base.Non_nullable_property_through_optional_navigation(a); + + AssertSql( + """ +SELECT c["Throned"]["Value"] +FROM root c +WHERE (c["Discriminator"] = "Barton") +"""); + }); + } } - public override Task Preserve_includes_when_applying_skip_take_after_anonymous_type_select(bool async) => - AssertTranslationFailed(() => base.Preserve_includes_when_applying_skip_take_after_anonymous_type_select(async)); + public override Task Owned_entity_without_owner_does_not_throw_for_identity_resolution(bool async, bool useAsTracking) + => CosmosTestHelpers.Instance.NoSyncTest( + async, async a => + { + await base.Owned_entity_without_owner_does_not_throw_for_identity_resolution(a, useAsTracking); + + AssertSql( + """ +SELECT c +FROM root c +WHERE c["Discriminator"] IN ("OwnedPerson", "Branch", "LeafB", "LeafA") +"""); + }); + + public override Task Simple_query_entity_with_owned_collection(bool async) + => CosmosTestHelpers.Instance.NoSyncTest( + async, async a => + { + await base.Simple_query_entity_with_owned_collection(a); + + AssertSql( + """ +SELECT c +FROM root c +WHERE (c["Discriminator"] = "Star") +"""); + }); + + public override Task Throw_for_owned_entities_without_owner_in_tracking_query(bool async) + => CosmosTestHelpers.Instance.NoSyncTest( + async, async a => + { + await base.Throw_for_owned_entities_without_owner_in_tracking_query(a); + + AssertSql( + """ +SELECT c +FROM root c +WHERE c["Discriminator"] IN ("OwnedPerson", "Branch", "LeafB", "LeafA") +"""); + }); + + public override Task Unmapped_property_projection_loads_owned_navigations(bool async) + => CosmosTestHelpers.Instance.NoSyncTest( + async, async a => + { + await base.Unmapped_property_projection_loads_owned_navigations(a); + + AssertSql( + """ +SELECT c +FROM root c +WHERE (c["Discriminator"] IN ("OwnedPerson", "Branch", "LeafB", "LeafA") AND (c["Id"] = 1)) +"""); + }); + + public override Task Client_method_take_loads_owned_navigations(bool async) + => CosmosTestHelpers.Instance.NoSyncTest( + async, async a => + { + await base.Client_method_take_loads_owned_navigations(a); + + AssertSql( + """ +@__p_0='2' + +SELECT c +FROM root c +WHERE c["Discriminator"] IN ("OwnedPerson", "Branch", "LeafB", "LeafA") +ORDER BY c["Id"] +OFFSET 0 LIMIT @__p_0 +"""); + }); + + [ConditionalTheory] + [MemberData(nameof(IsAsyncData))] + public override Task Client_method_take_loads_owned_navigations_variation_2(bool async) + => CosmosTestHelpers.Instance.NoSyncTest( + async, async a => + { + await base.Client_method_take_loads_owned_navigations_variation_2(a); + + AssertSql( + """ +@__p_0='2' + +SELECT c +FROM root c +WHERE c["Discriminator"] IN ("OwnedPerson", "Branch", "LeafB", "LeafA") +ORDER BY c["Id"] +OFFSET 0 LIMIT @__p_0 +"""); + }); private void AssertSql(params string[] expected) => Fixture.TestSqlLoggerFactory.AssertBaseline(expected); diff --git a/test/EFCore.Cosmos.FunctionalTests/Query/QueryLoggingCosmosTestBase.cs b/test/EFCore.Cosmos.FunctionalTests/Query/QueryLoggingCosmosTestBase.cs index 37674131ce5..180f222cccf 100644 --- a/test/EFCore.Cosmos.FunctionalTests/Query/QueryLoggingCosmosTestBase.cs +++ b/test/EFCore.Cosmos.FunctionalTests/Query/QueryLoggingCosmosTestBase.cs @@ -24,12 +24,10 @@ protected virtual bool ExpectSensitiveData => true; [ConditionalFact] - public virtual void Queryable_simple() + public virtual async Task Queryable_simple() { using var context = CreateContext(); - var customers - = context.Set() - .ToList(); + var customers = await context.Set().ToListAsync(); Assert.NotNull(customers); @@ -68,7 +66,7 @@ FROM root c } [ConditionalFact] - public virtual void Queryable_with_parameter_outputs_parameter_value_logging_warning() + public virtual async Task Queryable_with_parameter_outputs_parameter_value_logging_warning() { using var context = CreateContext(); context.GetInfrastructure().GetRequiredService>() @@ -76,10 +74,7 @@ public virtual void Queryable_with_parameter_outputs_parameter_value_logging_war // ReSharper disable once ConvertToConstant.Local var city = "Redmond"; - var customers - = context.Customers - .Where(c => c.City == city) - .ToList(); + var customers = await context.Customers.Where(c => c.City == city).ToListAsync(); Assert.NotNull(customers); @@ -117,10 +112,10 @@ FROM root c } [ConditionalFact] - public virtual void Skip_without_order_by() + public virtual async Task Skip_without_order_by() { using var context = CreateContext(); - var customers = context.Set().Skip(85).Take(5).ToList(); + var customers = await context.Set().Skip(85).Take(5).ToListAsync(); Assert.NotNull(customers); @@ -130,10 +125,10 @@ public virtual void Skip_without_order_by() } [ConditionalFact] - public virtual void Take_without_order_by() + public virtual async Task Take_without_order_by() { using var context = CreateContext(); - var customers = context.Set().Take(5).ToList(); + var customers = await context.Set().Take(5).ToListAsync(); Assert.NotNull(customers); diff --git a/test/EFCore.Cosmos.FunctionalTests/QueryExpressionInterceptionWithDiagnosticsCosmosTest.cs b/test/EFCore.Cosmos.FunctionalTests/QueryExpressionInterceptionWithDiagnosticsCosmosTest.cs index 9c8db697fda..02638ce97f9 100644 --- a/test/EFCore.Cosmos.FunctionalTests/QueryExpressionInterceptionWithDiagnosticsCosmosTest.cs +++ b/test/EFCore.Cosmos.FunctionalTests/QueryExpressionInterceptionWithDiagnosticsCosmosTest.cs @@ -5,10 +5,20 @@ namespace Microsoft.EntityFrameworkCore; #nullable disable -public class QueryExpressionInterceptionWithDiagnosticsCosmosTest(QueryExpressionInterceptionWithDiagnosticsCosmosTest.InterceptionCosmosFixture fixture) +public class QueryExpressionInterceptionWithDiagnosticsCosmosTest( + QueryExpressionInterceptionWithDiagnosticsCosmosTest.InterceptionCosmosFixture fixture) : QueryExpressionInterceptionTestBase(fixture), IClassFixture { + public override Task Intercept_query_passively(bool async, bool inject) + => CosmosTestHelpers.Instance.NoSyncTest(async, a => base.Intercept_query_passively(a, inject)); + + public override Task Intercept_query_with_multiple_interceptors(bool async, bool inject) + => CosmosTestHelpers.Instance.NoSyncTest(async, a => base.Intercept_query_with_multiple_interceptors(a, inject)); + + public override Task Intercept_to_change_query_expression(bool async, bool inject) + => CosmosTestHelpers.Instance.NoSyncTest(async, a => base.Intercept_to_change_query_expression(a, inject)); + public class InterceptionCosmosFixture : InterceptionFixtureBase { protected override ITestStoreFactory TestStoreFactory diff --git a/test/EFCore.Cosmos.FunctionalTests/ReloadTest.cs b/test/EFCore.Cosmos.FunctionalTests/ReloadTest.cs index dfc9d2b1fb9..c0ac0f4b6bb 100644 --- a/test/EFCore.Cosmos.FunctionalTests/ReloadTest.cs +++ b/test/EFCore.Cosmos.FunctionalTests/ReloadTest.cs @@ -11,11 +11,10 @@ public class ReloadTest { public static IEnumerable IsAsyncData = new object[][] { [false], [true] }; - [ConditionalTheory] - [MemberData(nameof(IsAsyncData))] - public async Task Entity_reference_can_be_reloaded(bool async) + [ConditionalFact] + public async Task Entity_reference_can_be_reloaded() { - await using var testDatabase = CosmosTestStore.CreateInitialized("ReloadTest"); + await using var testDatabase = await CosmosTestStore.CreateInitializedAsync("ReloadTest"); using var context = new ReloadTestContext(testDatabase); await context.Database.EnsureCreatedAsync(); @@ -27,14 +26,7 @@ public async Task Entity_reference_can_be_reloaded(bool async) var itemJson = entry.Property("__jObject").CurrentValue; itemJson["unmapped"] = 2; - if (async) - { - await entry.ReloadAsync(); - } - else - { - entry.Reload(); - } + await entry.ReloadAsync(); itemJson = entry.Property("__jObject").CurrentValue; Assert.Null(itemJson["unmapped"]); diff --git a/test/EFCore.Cosmos.FunctionalTests/Storage/CosmosDatabaseCreatorTest.cs b/test/EFCore.Cosmos.FunctionalTests/Storage/CosmosDatabaseCreatorTest.cs index d6d6ec15902..b019c8d248b 100644 --- a/test/EFCore.Cosmos.FunctionalTests/Storage/CosmosDatabaseCreatorTest.cs +++ b/test/EFCore.Cosmos.FunctionalTests/Storage/CosmosDatabaseCreatorTest.cs @@ -22,7 +22,7 @@ public async Task EnsureCreated_returns_true_when_database_does_not_exist() } finally { - testDatabase.Initialize(testDatabase.ServiceProvider, () => new BloggingContext(testDatabase)); + await testDatabase.InitializeAsync(testDatabase.ServiceProvider, () => new BloggingContext(testDatabase)); } } @@ -39,44 +39,51 @@ public async Task EnsureCreated_returns_true_when_database_exists_but_collection } finally { - testDatabase.Initialize(testDatabase.ServiceProvider, () => new BloggingContext(testDatabase)); + await testDatabase.InitializeAsync(testDatabase.ServiceProvider, () => new BloggingContext(testDatabase)); } } [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public async Task EnsureCreated_returns_false_when_database_and_collections_exist(bool async) - { - await using var testDatabase = CosmosTestStore.Create("EnsureCreatedReady"); - testDatabase.Initialize(testDatabase.ServiceProvider, testStore => new BloggingContext((CosmosTestStore)testStore)); + public Task EnsureCreated_returns_false_when_database_and_collections_exist(bool async) + => CosmosTestHelpers.Instance.NoSyncTest( + async, async a => + { + await using var testDatabase = CosmosTestStore.Create("EnsureCreatedReady"); + await testDatabase.InitializeAsync( + testDatabase.ServiceProvider, testStore => new BloggingContext((CosmosTestStore)testStore)); - using var context = new BloggingContext(testDatabase); - var creator = context.GetService(); + using var context = new BloggingContext(testDatabase); + var creator = context.GetService(); - Assert.False(async ? await creator.EnsureCreatedAsync() : creator.EnsureCreated()); - } + Assert.False(a ? await creator.EnsureCreatedAsync() : creator.EnsureCreated()); + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public async Task EnsureDeleted_returns_true_when_database_exists(bool async) - { - await using var testDatabase = CosmosTestStore.CreateInitialized("EnsureDeleteBlogging"); - using var context = new BloggingContext(testDatabase); - var creator = context.GetService(); + public Task EnsureDeleted_returns_true_when_database_exists(bool async) + => CosmosTestHelpers.Instance.NoSyncTest( + async, async a => + { + await using var testDatabase = await CosmosTestStore.CreateInitializedAsync("EnsureDeleteBlogging"); + using var context = new BloggingContext(testDatabase); + var creator = context.GetService(); - Assert.True(async ? await creator.EnsureDeletedAsync() : creator.EnsureDeleted()); - } + Assert.True(a ? await creator.EnsureDeletedAsync() : creator.EnsureDeleted()); + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public async Task EnsureDeleted_returns_false_when_database_does_not_exist(bool async) - { - await using var testDatabase = CosmosTestStore.Create("EnsureDeleteBlogging"); - using var context = new BloggingContext(testDatabase); - var creator = context.GetService(); - - Assert.False(async ? await creator.EnsureDeletedAsync() : creator.EnsureDeleted()); - } + public Task EnsureDeleted_returns_false_when_database_does_not_exist(bool async) + => CosmosTestHelpers.Instance.NoSyncTest( + async, async a => + { + await using var testDatabase = CosmosTestStore.Create("EnsureDeleteBlogging"); + using var context = new BloggingContext(testDatabase); + var creator = context.GetService(); + + Assert.False(a ? await creator.EnsureDeletedAsync() : creator.EnsureDeleted()); + }); private class BloggingContext(CosmosTestStore testStore) : DbContext { diff --git a/test/EFCore.Cosmos.FunctionalTests/TestUtilities/CosmosTestHelpers.cs b/test/EFCore.Cosmos.FunctionalTests/TestUtilities/CosmosTestHelpers.cs index 6f77e63a63e..e8f5a343940 100644 --- a/test/EFCore.Cosmos.FunctionalTests/TestUtilities/CosmosTestHelpers.cs +++ b/test/EFCore.Cosmos.FunctionalTests/TestUtilities/CosmosTestHelpers.cs @@ -1,7 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using Microsoft.EntityFrameworkCore.Cosmos.Diagnostics.Internal; // ReSharper disable once CheckNamespace +using Microsoft.EntityFrameworkCore.Cosmos.Internal; namespace Microsoft.EntityFrameworkCore.TestUtilities; @@ -13,7 +15,8 @@ protected CosmosTestHelpers() public static CosmosTestHelpers Instance { get; } = new(); - public override ModelAsserter ModelAsserter => CosmosModelAsserter.Instance; + public override ModelAsserter ModelAsserter + => CosmosModelAsserter.Instance; public override IServiceCollection AddProviderServices(IServiceCollection services) => services.AddEntityFrameworkCosmos(); @@ -23,4 +26,60 @@ public override DbContextOptionsBuilder UseProviderOptions(DbContextOptionsBuild TestEnvironment.DefaultConnection, TestEnvironment.AuthToken, "UnitTests"); + + private static readonly string SyncMessage + = CoreStrings.WarningAsErrorTemplate( + CosmosEventId.SyncNotSupported.ToString(), + CosmosResources.LogSyncNotSupported(new TestLogger()).GenerateMessage(), + "CosmosEventId.SyncNotSupported"); + + public async Task NoSyncTest(bool async, Func testCode) + { + try + { + await testCode(async); + Assert.True(async); + } + catch (InvalidOperationException e) + { + if (e.Message != SyncMessage) + { + throw; + } + + Assert.False(async); + } + catch (DbUpdateException e) + { + if (e.InnerException?.Message != SyncMessage) + { + throw; + } + + Assert.False(async); + } + } + + public void NoSyncTest(Action testCode) + { + try + { + testCode(); + Assert.Fail("Sync code did not fail."); + } + catch (InvalidOperationException e) + { + if (e.Message != SyncMessage) + { + throw; + } + } + catch (DbUpdateException e) + { + if (e.InnerException?.Message != SyncMessage) + { + throw; + } + } + } } diff --git a/test/EFCore.Cosmos.FunctionalTests/TestUtilities/CosmosTestStore.cs b/test/EFCore.Cosmos.FunctionalTests/TestUtilities/CosmosTestStore.cs index d94a532beb3..8e44164411e 100644 --- a/test/EFCore.Cosmos.FunctionalTests/TestUtilities/CosmosTestStore.cs +++ b/test/EFCore.Cosmos.FunctionalTests/TestUtilities/CosmosTestStore.cs @@ -24,8 +24,14 @@ public class CosmosTestStore : TestStore public static CosmosTestStore Create(string name, Action? extensionConfiguration = null) => new(name, shared: false, extensionConfiguration: extensionConfiguration); - public static CosmosTestStore CreateInitialized(string name, Action? extensionConfiguration = null) - => (CosmosTestStore)Create(name, extensionConfiguration).Initialize(null, (Func?)null); + public static async Task CreateInitializedAsync( + string name, + Action? extensionConfiguration = null) + { + var testStore = Create(name, extensionConfiguration); + await testStore.InitializeAsync(null, (Func?)null); + return testStore; + } public static CosmosTestStore GetOrCreate(string name) => new(name); @@ -97,7 +103,7 @@ private static async Task TryConnectAsync() CosmosTestStore? testStore = null; try { - testStore = CreateInitialized("NonExistent"); + testStore = await CreateInitializedAsync("NonExistent"); return true; } @@ -138,7 +144,7 @@ private static bool IsNotConfigured(Exception exception) StringComparison.Ordinal), }; - protected override void Initialize(Func createContext, Action? seed, Action? clean) + protected override async Task InitializeAsync(Func createContext, Func? seed, Func? clean) { _initialized = true; @@ -149,12 +155,12 @@ protected override void Initialize(Func createContext, Action _storeContext), seed, clean); + await base.InitializeAsync(createContext ?? (() => _storeContext), seed, clean); } else { using var context = createContext(); - CreateFromFile(context).GetAwaiter().GetResult(); + await CreateFromFile(context); } } @@ -217,9 +223,6 @@ await cosmosClient.CreateItemAsync( } } - public override void Clean(DbContext context) - => CleanAsync(context).GetAwaiter().GetResult(); - public override async Task CleanAsync(DbContext context) { var cosmosClientWrapper = context.GetService(); diff --git a/test/EFCore.CrossStore.FunctionalTests/ConfigurationPatternsTest.cs b/test/EFCore.CrossStore.FunctionalTests/ConfigurationPatternsTest.cs index 831c03c59d4..a3737bf020d 100644 --- a/test/EFCore.CrossStore.FunctionalTests/ConfigurationPatternsTest.cs +++ b/test/EFCore.CrossStore.FunctionalTests/ConfigurationPatternsTest.cs @@ -8,12 +8,11 @@ namespace Microsoft.EntityFrameworkCore; [SqlServerConfiguredCondition] -public class ConfigurationPatternsTest : IClassFixture, IDisposable +public class ConfigurationPatternsTest : IClassFixture, IAsyncLifetime { public ConfigurationPatternsTest(CrossStoreFixture fixture) { Fixture = fixture; - ExistingTestStore = Fixture.CreateTestStore(SqlServerTestStoreFactory.Instance, StoreName, Seed); } [ConditionalFact] @@ -184,28 +183,22 @@ private class SomeService(MultipleProvidersContext context) } private CrossStoreFixture Fixture { get; } - private TestStore ExistingTestStore { get; } + private TestStore ExistingTestStore { get; set; } private static readonly string StoreName = "CrossStoreConfigurationPatternsTest"; - private void Seed(CrossStoreContext context) + private Task SeedAsync(CrossStoreContext context) { context.SimpleEntities.Add(new SimpleEntity { StringProperty = "Entity 1" }); - context.SaveChanges(); + return context.SaveChangesAsync(); } -#pragma warning disable xUnit1013 // Public method should be marked as test - public void Dispose() - => ExistingTestStore.Dispose(); -#pragma warning restore xUnit1013 // Public method should be marked as test - [SqlServerConfiguredCondition] - public class NestedContextDifferentStores : IClassFixture, IDisposable + public class NestedContextDifferentStores : IClassFixture, IAsyncLifetime { public NestedContextDifferentStores(CrossStoreFixture fixture) { Fixture = fixture; - ExistingTestStore = Fixture.CreateTestStore(SqlServerTestStoreFactory.Instance, StoreName, Seed); } [ConditionalFact] @@ -249,21 +242,16 @@ private async Task NestedContextTest(Func createBlogContext, Func ExistingTestStore.Dispose(); -#pragma warning restore xUnit1013 // Public method should be marked as test - private class BlogContext : DbContext { private readonly IServiceProvider _serviceProvider; @@ -310,5 +298,25 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) .UseSqlServer(SqlServerTestStore.CreateConnectionString(StoreName), b => b.ApplyConfiguration()) .UseInternalServiceProvider(_serviceProvider); } + + public async Task InitializeAsync() + { + ExistingTestStore = await Fixture.CreateTestStoreAsync(SqlServerTestStoreFactory.Instance, StoreName, SeedAsync); + } + + public Task DisposeAsync() + { + ExistingTestStore.Dispose(); + return Task.CompletedTask; + } + } + + public async Task InitializeAsync() + => ExistingTestStore = await Fixture.CreateTestStoreAsync(SqlServerTestStoreFactory.Instance, StoreName, SeedAsync); + + public Task DisposeAsync() + { + ExistingTestStore.Dispose(); + return Task.CompletedTask; } } diff --git a/test/EFCore.CrossStore.FunctionalTests/CrossStoreFixture.cs b/test/EFCore.CrossStore.FunctionalTests/CrossStoreFixture.cs index 73c2cf4dbc1..86c5de7bb3e 100644 --- a/test/EFCore.CrossStore.FunctionalTests/CrossStoreFixture.cs +++ b/test/EFCore.CrossStore.FunctionalTests/CrossStoreFixture.cs @@ -15,9 +15,12 @@ public DbContextOptions CreateOptions(TestStore testStore) public CrossStoreContext CreateContext(TestStore testStore) => new(CreateOptions(testStore)); - public TestStore CreateTestStore(ITestStoreFactory testStoreFactory, string storeName, Action seed = null) + public Task CreateTestStoreAsync( + ITestStoreFactory testStoreFactory, + string storeName, + Func seed = null) => testStoreFactory.GetOrCreate(storeName) - .Initialize( + .InitializeAsync( AddServices(testStoreFactory.AddProviderServices(new ServiceCollection())).BuildServiceProvider(validateScopes: true), CreateContext, seed); diff --git a/test/EFCore.CrossStore.FunctionalTests/EndToEndTest.cs b/test/EFCore.CrossStore.FunctionalTests/EndToEndTest.cs index 509118713d7..595dd04ef8a 100644 --- a/test/EFCore.CrossStore.FunctionalTests/EndToEndTest.cs +++ b/test/EFCore.CrossStore.FunctionalTests/EndToEndTest.cs @@ -6,20 +6,16 @@ // ReSharper disable InconsistentNaming namespace Microsoft.EntityFrameworkCore; -public abstract class EndToEndTest : IDisposable +public abstract class EndToEndTest : IAsyncLifetime { protected EndToEndTest(CrossStoreFixture fixture) { Fixture = fixture; - TestStore = Fixture.CreateTestStore(TestStoreFactory, "CrossStoreTest"); } protected CrossStoreFixture Fixture { get; } protected abstract ITestStoreFactory TestStoreFactory { get; } - protected TestStore TestStore { get; } - - public void Dispose() - => TestStore.Dispose(); + protected TestStore TestStore { get; private set; } [ConditionalFact] public virtual void Can_save_changes_and_query() @@ -69,6 +65,15 @@ public virtual void Can_save_changes_and_query() protected CrossStoreContext CreateContext() => Fixture.CreateContext(TestStore); + + public async Task InitializeAsync() + => TestStore = await Fixture.CreateTestStoreAsync(TestStoreFactory, "CrossStoreTest"); + + public Task DisposeAsync() + { + TestStore.Dispose(); + return Task.CompletedTask; + } } public class InMemoryEndToEndTest(CrossStoreFixture fixture) : EndToEndTest(fixture), IClassFixture diff --git a/test/EFCore.InMemory.FunctionalTests/BuiltInDataTypesInMemoryTest.cs b/test/EFCore.InMemory.FunctionalTests/BuiltInDataTypesInMemoryTest.cs index 557d4dead9f..4a3abb3ceeb 100644 --- a/test/EFCore.InMemory.FunctionalTests/BuiltInDataTypesInMemoryTest.cs +++ b/test/EFCore.InMemory.FunctionalTests/BuiltInDataTypesInMemoryTest.cs @@ -5,11 +5,11 @@ namespace Microsoft.EntityFrameworkCore; -public class BuiltInDataTypesInMemoryTest(BuiltInDataTypesInMemoryTest.BuiltInDataTypesInMemoryFixture fixture) : BuiltInDataTypesTestBase(fixture) +public class BuiltInDataTypesInMemoryTest(BuiltInDataTypesInMemoryTest.BuiltInDataTypesInMemoryFixture fixture) + : BuiltInDataTypesTestBase(fixture) { - public override void Optional_datetime_reading_null_from_database() - { - } + public override Task Optional_datetime_reading_null_from_database() + => Task.CompletedTask; public class BuiltInDataTypesInMemoryFixture : BuiltInDataTypesFixtureBase { diff --git a/test/EFCore.InMemory.FunctionalTests/ComplexTypesTrackingInMemoryTest.cs b/test/EFCore.InMemory.FunctionalTests/ComplexTypesTrackingInMemoryTest.cs index 7ea487ccc86..bcac60ffa8e 100644 --- a/test/EFCore.InMemory.FunctionalTests/ComplexTypesTrackingInMemoryTest.cs +++ b/test/EFCore.InMemory.FunctionalTests/ComplexTypesTrackingInMemoryTest.cs @@ -3,23 +3,9 @@ namespace Microsoft.EntityFrameworkCore; -public class ComplexTypesTrackingInMemoryTest(ComplexTypesTrackingInMemoryTest.InMemoryFixture fixture) : ComplexTypesTrackingTestBase(fixture) +public class ComplexTypesTrackingInMemoryTest(ComplexTypesTrackingInMemoryTest.InMemoryFixture fixture) + : ComplexTypesTrackingTestBase(fixture) { - protected override void ExecuteWithStrategyInTransaction( - Action testOperation, - Action nestedTestOperation1 = null, - Action nestedTestOperation2 = null) - { - try - { - base.ExecuteWithStrategyInTransaction(testOperation, nestedTestOperation1, nestedTestOperation2); - } - finally - { - Fixture.Reseed(); - } - } - protected override async Task ExecuteWithStrategyInTransactionAsync( Func testOperation, Func nestedTestOperation1 = null, @@ -31,7 +17,7 @@ protected override async Task ExecuteWithStrategyInTransactionAsync( } finally { - Fixture.Reseed(); + await Fixture.ReseedAsync(); } } diff --git a/test/EFCore.InMemory.FunctionalTests/ConvertToProviderTypesInMemoryTest.cs b/test/EFCore.InMemory.FunctionalTests/ConvertToProviderTypesInMemoryTest.cs index 938f5530393..8d4fc91e1af 100644 --- a/test/EFCore.InMemory.FunctionalTests/ConvertToProviderTypesInMemoryTest.cs +++ b/test/EFCore.InMemory.FunctionalTests/ConvertToProviderTypesInMemoryTest.cs @@ -3,12 +3,12 @@ namespace Microsoft.EntityFrameworkCore; -public class ConvertToProviderTypesInMemoryTest(ConvertToProviderTypesInMemoryTest.ConvertToProviderTypesInMemoryFixture fixture) : ConvertToProviderTypesTestBase< - ConvertToProviderTypesInMemoryTest.ConvertToProviderTypesInMemoryFixture>(fixture) +public class ConvertToProviderTypesInMemoryTest(ConvertToProviderTypesInMemoryTest.ConvertToProviderTypesInMemoryFixture fixture) + : ConvertToProviderTypesTestBase< + ConvertToProviderTypesInMemoryTest.ConvertToProviderTypesInMemoryFixture>(fixture) { - public override void Optional_datetime_reading_null_from_database() - { - } + public override Task Optional_datetime_reading_null_from_database() + => Task.CompletedTask; public class ConvertToProviderTypesInMemoryFixture : ConvertToProviderTypesFixtureBase { diff --git a/test/EFCore.InMemory.FunctionalTests/CustomConvertersInMemoryTest.cs b/test/EFCore.InMemory.FunctionalTests/CustomConvertersInMemoryTest.cs index 13aba285e35..23e7f592dc9 100644 --- a/test/EFCore.InMemory.FunctionalTests/CustomConvertersInMemoryTest.cs +++ b/test/EFCore.InMemory.FunctionalTests/CustomConvertersInMemoryTest.cs @@ -5,16 +5,15 @@ namespace Microsoft.EntityFrameworkCore; -public class CustomConvertersInMemoryTest(CustomConvertersInMemoryTest.CustomConvertersInMemoryFixture fixture) : CustomConvertersTestBase(fixture) +public class CustomConvertersInMemoryTest(CustomConvertersInMemoryTest.CustomConvertersInMemoryFixture fixture) + : CustomConvertersTestBase(fixture) { - public override void Optional_datetime_reading_null_from_database() - { - } + public override Task Optional_datetime_reading_null_from_database() + => Task.CompletedTask; // Disabled: In-memory database is case-sensitive - public override void Can_insert_and_read_back_with_case_insensitive_string_key() - { - } + public override Task Can_insert_and_read_back_with_case_insensitive_string_key() + => Task.CompletedTask; [ConditionalFact(Skip = "Issue#17050")] public override void Value_conversion_with_property_named_value() diff --git a/test/EFCore.InMemory.FunctionalTests/DataAnnotationInMemoryTest.cs b/test/EFCore.InMemory.FunctionalTests/DataAnnotationInMemoryTest.cs index 67f4b3625af..4e1e5e50f90 100644 --- a/test/EFCore.InMemory.FunctionalTests/DataAnnotationInMemoryTest.cs +++ b/test/EFCore.InMemory.FunctionalTests/DataAnnotationInMemoryTest.cs @@ -3,47 +3,53 @@ namespace Microsoft.EntityFrameworkCore; -public class DataAnnotationInMemoryTest(DataAnnotationInMemoryTest.DataAnnotationInMemoryFixture fixture) : DataAnnotationTestBase(fixture) +public class DataAnnotationInMemoryTest(DataAnnotationInMemoryTest.DataAnnotationInMemoryFixture fixture) + : DataAnnotationTestBase(fixture) { protected override TestHelpers TestHelpers => InMemoryTestHelpers.Instance; - public override void ConcurrencyCheckAttribute_throws_if_value_in_database_changed() + public override Task ConcurrencyCheckAttribute_throws_if_value_in_database_changed() { using var context = CreateContext(); Assert.True(context.Model.FindEntityType(typeof(One)).FindProperty("RowVersion").IsConcurrencyToken); + return Task.CompletedTask; } - public override void MaxLengthAttribute_throws_while_inserting_value_longer_than_max_length() + public override Task MaxLengthAttribute_throws_while_inserting_value_longer_than_max_length() { using var context = CreateContext(); Assert.Equal(10, context.Model.FindEntityType(typeof(One)).FindProperty("MaxLengthProperty").GetMaxLength()); + return Task.CompletedTask; } - public override void RequiredAttribute_for_navigation_throws_while_inserting_null_value() + public override Task RequiredAttribute_for_navigation_throws_while_inserting_null_value() { using var context = CreateContext(); Assert.True( - context.Model.FindEntityType(typeof(BookDetails)).FindNavigation(nameof(BookDetails.AnotherBook)).ForeignKey - .IsRequired); + context.Model.FindEntityType(typeof(BookDetails)).FindNavigation(nameof(BookDetails.AnotherBook)).ForeignKey.IsRequired); + return Task.CompletedTask; } - public override void RequiredAttribute_for_property_throws_while_inserting_null_value() + public override Task RequiredAttribute_for_property_throws_while_inserting_null_value() { using var context = CreateContext(); Assert.False(context.Model.FindEntityType(typeof(One)).FindProperty("RequiredColumn").IsNullable); + return Task.CompletedTask; } - public override void StringLengthAttribute_throws_while_inserting_value_longer_than_max_length() + public override Task StringLengthAttribute_throws_while_inserting_value_longer_than_max_length() { using var context = CreateContext(); Assert.Equal(16, context.Model.FindEntityType(typeof(Two)).FindProperty("Data").GetMaxLength()); + return Task.CompletedTask; } - public override void TimestampAttribute_throws_if_value_in_database_changed() + public override Task TimestampAttribute_throws_if_value_in_database_changed() { using var context = CreateContext(); Assert.True(context.Model.FindEntityType(typeof(Two)).FindProperty("Timestamp").IsConcurrencyToken); + return Task.CompletedTask; } public class DataAnnotationInMemoryFixture : DataAnnotationFixtureBase diff --git a/test/EFCore.InMemory.FunctionalTests/FieldMappingInMemoryTest.cs b/test/EFCore.InMemory.FunctionalTests/FieldMappingInMemoryTest.cs index 54c7e3af94e..670411bf30d 100644 --- a/test/EFCore.InMemory.FunctionalTests/FieldMappingInMemoryTest.cs +++ b/test/EFCore.InMemory.FunctionalTests/FieldMappingInMemoryTest.cs @@ -3,13 +3,13 @@ namespace Microsoft.EntityFrameworkCore; -public class FieldMappingInMemoryTest(FieldMappingInMemoryTest.FieldMappingInMemoryFixture fixture) : FieldMappingTestBase(fixture) +public class FieldMappingInMemoryTest(FieldMappingInMemoryTest.FieldMappingInMemoryFixture fixture) + : FieldMappingTestBase(fixture) { - protected override void Update(string navigation) + protected override async Task UpdateAsync(string navigation) { - base.Update(navigation); - - Fixture.Reseed(); + await base.UpdateAsync(navigation); + await Fixture.ReseedAsync(); } public class FieldMappingInMemoryFixture : FieldMappingFixtureBase diff --git a/test/EFCore.InMemory.FunctionalTests/GraphUpdates/GraphUpdatesIdentityResolutionInMemoryTest.cs b/test/EFCore.InMemory.FunctionalTests/GraphUpdates/GraphUpdatesIdentityResolutionInMemoryTest.cs index 47e045fca31..8de8cc86c8b 100644 --- a/test/EFCore.InMemory.FunctionalTests/GraphUpdates/GraphUpdatesIdentityResolutionInMemoryTest.cs +++ b/test/EFCore.InMemory.FunctionalTests/GraphUpdates/GraphUpdatesIdentityResolutionInMemoryTest.cs @@ -3,135 +3,136 @@ namespace Microsoft.EntityFrameworkCore; -public class GraphUpdatesIdentityResolutionInMemoryTest(GraphUpdatesIdentityResolutionInMemoryTest.InMemoryIdentityResolutionFixture fixture) +public class GraphUpdatesIdentityResolutionInMemoryTest( + GraphUpdatesIdentityResolutionInMemoryTest.InMemoryIdentityResolutionFixture fixture) : GraphUpdatesInMemoryTestBase(fixture) { [ConditionalFact] - public void Can_attach_full_required_graph_of_duplicates() - => ExecuteWithStrategyInTransaction( - context => + public Task Can_attach_full_required_graph_of_duplicates() + => ExecuteWithStrategyInTransactionAsync( + async context => { - var trackedRoot = LoadRequiredGraph(context); + var trackedRoot = await LoadRequiredGraphAsync(context); var entries = context.ChangeTracker.Entries().ToList(); - context.Attach(QueryRequiredGraph(context).AsNoTracking().Single(IsTheRoot)); + context.Attach(await QueryRequiredGraph(context).AsNoTracking().SingleAsync(IsTheRoot)); AssertEntries(entries, context.ChangeTracker.Entries().ToList()); AssertNavigations(trackedRoot); - Assert.Equal(0, context.SaveChanges()); + Assert.Equal(0, await context.SaveChangesAsync()); }); [ConditionalFact] - public void Can_attach_full_optional_graph_of_duplicates() - => ExecuteWithStrategyInTransaction( - context => + public Task Can_attach_full_optional_graph_of_duplicates() + => ExecuteWithStrategyInTransactionAsync( + async context => { - var trackedRoot = LoadOptionalGraph(context); + var trackedRoot = await LoadOptionalGraphAsync(context); var entries = context.ChangeTracker.Entries().ToList(); - context.Attach(QueryOptionalGraph(context).AsNoTracking().Single(IsTheRoot)); + context.Attach(await QueryOptionalGraph(context).AsNoTracking().SingleAsync(IsTheRoot)); AssertEntries(entries, context.ChangeTracker.Entries().ToList()); AssertNavigations(trackedRoot); - Assert.Equal(0, context.SaveChanges()); + Assert.Equal(0, await context.SaveChangesAsync()); }); [ConditionalFact] - public void Can_attach_full_required_non_PK_graph_of_duplicates() - => ExecuteWithStrategyInTransaction( - context => + public Task Can_attach_full_required_non_PK_graph_of_duplicates() + => ExecuteWithStrategyInTransactionAsync( + async context => { - var trackedRoot = LoadRequiredNonPkGraph(context); + var trackedRoot = await LoadRequiredNonPkGraphAsync(context); var entries = context.ChangeTracker.Entries().ToList(); - context.Attach(QueryRequiredNonPkGraph(context).AsNoTracking().Single(IsTheRoot)); + context.Attach(await QueryRequiredNonPkGraph(context).AsNoTracking().SingleAsync(IsTheRoot)); AssertEntries(entries, context.ChangeTracker.Entries().ToList()); AssertNavigations(trackedRoot); - Assert.Equal(0, context.SaveChanges()); + Assert.Equal(0, await context.SaveChangesAsync()); }); [ConditionalFact] - public void Can_attach_full_required_AK_graph_of_duplicates() - => ExecuteWithStrategyInTransaction( - context => + public Task Can_attach_full_required_AK_graph_of_duplicates() + => ExecuteWithStrategyInTransactionAsync( + async context => { - var trackedRoot = LoadRequiredAkGraph(context); + var trackedRoot = await LoadRequiredAkGraphAsync(context); var entries = context.ChangeTracker.Entries().ToList(); - context.Attach(QueryRequiredAkGraph(context).AsNoTracking().Single(IsTheRoot)); + context.Attach(await QueryRequiredAkGraph(context).AsNoTracking().SingleAsync(IsTheRoot)); AssertEntries(entries, context.ChangeTracker.Entries().ToList()); AssertNavigations(trackedRoot); - Assert.Equal(0, context.SaveChanges()); + Assert.Equal(0, await context.SaveChangesAsync()); }); [ConditionalFact] - public void Can_attach_full_optional_AK_graph_of_duplicates() - => ExecuteWithStrategyInTransaction( - context => + public Task Can_attach_full_optional_AK_graph_of_duplicates() + => ExecuteWithStrategyInTransactionAsync( + async context => { - var trackedRoot = LoadOptionalAkGraph(context); + var trackedRoot = await LoadOptionalAkGraphAsync(context); var entries = context.ChangeTracker.Entries().ToList(); - context.Attach(QueryOptionalAkGraph(context).AsNoTracking().Single(IsTheRoot)); + context.Attach(await QueryOptionalAkGraph(context).AsNoTracking().SingleAsync(IsTheRoot)); AssertEntries(entries, context.ChangeTracker.Entries().ToList()); AssertNavigations(trackedRoot); - Assert.Equal(0, context.SaveChanges()); + Assert.Equal(0, await context.SaveChangesAsync()); }); [ConditionalFact] - public void Can_attach_full_required_non_PK_AK_graph_of_duplicates() - => ExecuteWithStrategyInTransaction( - context => + public Task Can_attach_full_required_non_PK_AK_graph_of_duplicates() + => ExecuteWithStrategyInTransactionAsync( + async context => { - var trackedRoot = LoadRequiredNonPkAkGraph(context); + var trackedRoot = await LoadRequiredNonPkAkGraphAsync(context); var entries = context.ChangeTracker.Entries().ToList(); - context.Attach(QueryRequiredNonPkAkGraph(context).AsNoTracking().Single(IsTheRoot)); + context.Attach(await QueryRequiredNonPkAkGraph(context).AsNoTracking().SingleAsync(IsTheRoot)); AssertEntries(entries, context.ChangeTracker.Entries().ToList()); AssertNavigations(trackedRoot); - Assert.Equal(0, context.SaveChanges()); + Assert.Equal(0, await context.SaveChangesAsync()); }); [ConditionalFact] - public void Can_attach_full_required_one_to_many_graph_of_duplicates() - => ExecuteWithStrategyInTransaction( - context => + public Task Can_attach_full_required_one_to_many_graph_of_duplicates() + => ExecuteWithStrategyInTransactionAsync( + async context => { - var trackedRoot = LoadOptionalOneToManyGraph(context); + var trackedRoot = await LoadOptionalOneToManyGraphAsync(context); var entries = context.ChangeTracker.Entries().ToList(); - context.Attach(QueryOptionalOneToManyGraph(context).AsNoTracking().Single(IsTheRoot)); + context.Attach(await QueryOptionalOneToManyGraph(context).AsNoTracking().SingleAsync(IsTheRoot)); AssertEntries(entries, context.ChangeTracker.Entries().ToList()); AssertNavigations(trackedRoot); - Assert.Equal(0, context.SaveChanges()); + Assert.Equal(0, await context.SaveChangesAsync()); }); [ConditionalFact] - public void Can_attach_full_required_composite_graph_of_duplicates() - => ExecuteWithStrategyInTransaction( - context => + public Task Can_attach_full_required_composite_graph_of_duplicates() + => ExecuteWithStrategyInTransactionAsync( + async context => { - var trackedRoot = LoadRequiredCompositeGraph(context); + var trackedRoot = await LoadRequiredCompositeGraphAsync(context); var entries = context.ChangeTracker.Entries().ToList(); - context.Attach(QueryRequiredCompositeGraph(context).AsNoTracking().Single(IsTheRoot)); + context.Attach(await QueryRequiredCompositeGraph(context).AsNoTracking().SingleAsync(IsTheRoot)); AssertEntries(entries, context.ChangeTracker.Entries().ToList()); AssertNavigations(trackedRoot); - Assert.Equal(0, context.SaveChanges()); + Assert.Equal(0, await context.SaveChangesAsync()); }); public class InMemoryIdentityResolutionFixture : GraphUpdatesInMemoryFixtureBase diff --git a/test/EFCore.InMemory.FunctionalTests/GraphUpdates/GraphUpdatesInMemoryTestBase.cs b/test/EFCore.InMemory.FunctionalTests/GraphUpdates/GraphUpdatesInMemoryTestBase.cs index 2baf251bc6f..2c05c9308d0 100644 --- a/test/EFCore.InMemory.FunctionalTests/GraphUpdates/GraphUpdatesInMemoryTestBase.cs +++ b/test/EFCore.InMemory.FunctionalTests/GraphUpdates/GraphUpdatesInMemoryTestBase.cs @@ -43,151 +43,121 @@ public override Task Can_insert_when_FK_has_default_value(bool async) public override Task Can_insert_when_FK_has_sentinel_value(bool async) => Task.CompletedTask; - public override void Required_many_to_one_dependents_are_cascade_deleted_in_store( - CascadeTiming? cascadeDeleteTiming, - CascadeTiming? deleteOrphansTiming) - { + public override Task Required_many_to_one_dependents_are_cascade_deleted_in_store( + CascadeTiming? cascadeDeleteTiming, + CascadeTiming? deleteOrphansTiming) // FK uniqueness not enforced in in-memory database - } + => Task.CompletedTask; - public override void Optional_many_to_one_dependents_are_orphaned_in_store( - CascadeTiming? cascadeDeleteTiming, - CascadeTiming? deleteOrphansTiming) - { + public override Task Optional_many_to_one_dependents_are_orphaned_in_store( + CascadeTiming? cascadeDeleteTiming, + CascadeTiming? deleteOrphansTiming) // FK uniqueness not enforced in in-memory database - } + => Task.CompletedTask; - public override void Required_many_to_one_dependents_with_alternate_key_are_cascade_deleted_in_store( - CascadeTiming? cascadeDeleteTiming, - CascadeTiming? deleteOrphansTiming) - { + public override Task Required_many_to_one_dependents_with_alternate_key_are_cascade_deleted_in_store( + CascadeTiming? cascadeDeleteTiming, + CascadeTiming? deleteOrphansTiming) // FK uniqueness not enforced in in-memory database - } + => Task.CompletedTask; - public override void Optional_many_to_one_dependents_with_alternate_key_are_orphaned_in_store( - CascadeTiming? cascadeDeleteTiming, - CascadeTiming? deleteOrphansTiming) - { + public override Task Optional_many_to_one_dependents_with_alternate_key_are_orphaned_in_store( + CascadeTiming? cascadeDeleteTiming, + CascadeTiming? deleteOrphansTiming) // FK uniqueness not enforced in in-memory database - } + => Task.CompletedTask; - public override void Optional_one_to_one_relationships_are_one_to_one( - CascadeTiming? deleteOrphansTiming) - { + public override Task Optional_one_to_one_relationships_are_one_to_one( + CascadeTiming? deleteOrphansTiming) // FK uniqueness not enforced in in-memory database - } + => Task.CompletedTask; - public override void Required_one_to_one_relationships_are_one_to_one( - CascadeTiming? deleteOrphansTiming) - { + public override Task Required_one_to_one_relationships_are_one_to_one( + CascadeTiming? deleteOrphansTiming) // FK uniqueness not enforced in in-memory database - } + => Task.CompletedTask; - public override void Save_required_one_to_one_changed_by_reference( - ChangeMechanism changeMechanism, - CascadeTiming? deleteOrphansTiming) - { + public override Task Save_required_one_to_one_changed_by_reference( + ChangeMechanism changeMechanism, + CascadeTiming? deleteOrphansTiming) // FK uniqueness not enforced in in-memory database - } + => Task.CompletedTask; - public override void Sever_required_one_to_one( - ChangeMechanism changeMechanism, - CascadeTiming? deleteOrphansTiming) - { + public override Task Sever_required_one_to_one( + ChangeMechanism changeMechanism, + CascadeTiming? deleteOrphansTiming) // FK uniqueness not enforced in in-memory database - } + => Task.CompletedTask; - public override void Required_one_to_one_are_cascade_deleted_in_store( - CascadeTiming? cascadeDeleteTiming, - CascadeTiming? deleteOrphansTiming) - { + public override Task Required_one_to_one_are_cascade_deleted_in_store( + CascadeTiming? cascadeDeleteTiming, + CascadeTiming? deleteOrphansTiming) // FK uniqueness not enforced in in-memory database - } + => Task.CompletedTask; - public override void Required_non_PK_one_to_one_are_cascade_deleted_in_store( - CascadeTiming? cascadeDeleteTiming, - CascadeTiming? deleteOrphansTiming) - { + public override Task Required_non_PK_one_to_one_are_cascade_deleted_in_store( + CascadeTiming? cascadeDeleteTiming, + CascadeTiming? deleteOrphansTiming) // FK uniqueness not enforced in in-memory database - } + => Task.CompletedTask; - public override void Optional_one_to_one_are_orphaned_in_store( - CascadeTiming? cascadeDeleteTiming, - CascadeTiming? deleteOrphansTiming) - { + public override Task Optional_one_to_one_are_orphaned_in_store( + CascadeTiming? cascadeDeleteTiming, + CascadeTiming? deleteOrphansTiming) // FK uniqueness not enforced in in-memory database - } + => Task.CompletedTask; - public override void Required_one_to_one_are_cascade_detached_when_Added( - CascadeTiming? cascadeDeleteTiming, - CascadeTiming? deleteOrphansTiming) - { + public override Task Required_one_to_one_are_cascade_detached_when_Added( + CascadeTiming? cascadeDeleteTiming, + CascadeTiming? deleteOrphansTiming) // FK uniqueness not enforced in in-memory database - } + => Task.CompletedTask; - public override void Required_non_PK_one_to_one_are_cascade_detached_when_Added( - CascadeTiming? cascadeDeleteTiming, - CascadeTiming? deleteOrphansTiming) - { + public override Task Required_non_PK_one_to_one_are_cascade_detached_when_Added( + CascadeTiming? cascadeDeleteTiming, + CascadeTiming? deleteOrphansTiming) // FK uniqueness not enforced in in-memory database - } + => Task.CompletedTask; - public override void Optional_one_to_one_with_AK_relationships_are_one_to_one( - CascadeTiming? deleteOrphansTiming) - { + public override Task Optional_one_to_one_with_AK_relationships_are_one_to_one( + CascadeTiming? deleteOrphansTiming) // FK uniqueness not enforced in in-memory database - } + => Task.CompletedTask; - public override void Required_one_to_one_with_AK_relationships_are_one_to_one( - CascadeTiming? deleteOrphansTiming) - { + public override Task Required_one_to_one_with_AK_relationships_are_one_to_one( + CascadeTiming? deleteOrphansTiming) // FK uniqueness not enforced in in-memory database - } + => Task.CompletedTask; - public override void Required_one_to_one_with_alternate_key_are_cascade_deleted_in_store( - CascadeTiming? cascadeDeleteTiming, - CascadeTiming? deleteOrphansTiming) - { + public override Task Required_one_to_one_with_alternate_key_are_cascade_deleted_in_store( + CascadeTiming? cascadeDeleteTiming, + CascadeTiming? deleteOrphansTiming) // FK uniqueness not enforced in in-memory database - } + => Task.CompletedTask; - public override void Required_non_PK_one_to_one_with_alternate_key_are_cascade_deleted_in_store( - CascadeTiming? cascadeDeleteTiming, - CascadeTiming? deleteOrphansTiming) - { + public override Task Required_non_PK_one_to_one_with_alternate_key_are_cascade_deleted_in_store( + CascadeTiming? cascadeDeleteTiming, + CascadeTiming? deleteOrphansTiming) // FK uniqueness not enforced in in-memory database - } + => Task.CompletedTask; - public override void Optional_one_to_one_with_alternate_key_are_orphaned_in_store( - CascadeTiming? cascadeDeleteTiming, - CascadeTiming? deleteOrphansTiming) - { + public override Task Optional_one_to_one_with_alternate_key_are_orphaned_in_store( + CascadeTiming? cascadeDeleteTiming, + CascadeTiming? deleteOrphansTiming) // FK uniqueness not enforced in in-memory database - } + => Task.CompletedTask; - public override void Required_non_PK_one_to_one_with_alternate_key_are_cascade_detached_when_Added( - CascadeTiming? cascadeDeleteTiming, - CascadeTiming? deleteOrphansTiming) - { + public override Task Required_non_PK_one_to_one_with_alternate_key_are_cascade_detached_when_Added( + CascadeTiming? cascadeDeleteTiming, + CascadeTiming? deleteOrphansTiming) // FK uniqueness not enforced in in-memory database - } + => Task.CompletedTask; - public override void Required_one_to_one_with_alternate_key_are_cascade_detached_when_Added( - CascadeTiming? cascadeDeleteTiming, - CascadeTiming? deleteOrphansTiming) - { + public override Task Required_one_to_one_with_alternate_key_are_cascade_detached_when_Added( + CascadeTiming? cascadeDeleteTiming, + CascadeTiming? deleteOrphansTiming) // FK uniqueness not enforced in in-memory database - } - - protected override void ExecuteWithStrategyInTransaction( - Action testOperation, - Action nestedTestOperation1 = null, - Action nestedTestOperation2 = null, - Action nestedTestOperation3 = null) - { - base.ExecuteWithStrategyInTransaction(testOperation, nestedTestOperation1, nestedTestOperation2, nestedTestOperation3); - Fixture.Reseed(); - } + => Task.CompletedTask; protected override async Task ExecuteWithStrategyInTransactionAsync( Func testOperation, @@ -198,7 +168,7 @@ protected override async Task ExecuteWithStrategyInTransactionAsync( await base.ExecuteWithStrategyInTransactionAsync( testOperation, nestedTestOperation1, nestedTestOperation2, nestedTestOperation3); - Fixture.Reseed(); + await Fixture.ReseedAsync(); } public abstract class GraphUpdatesInMemoryFixtureBase : GraphUpdatesFixtureBase diff --git a/test/EFCore.InMemory.FunctionalTests/GraphUpdates/ProxyGraphUpdatesInMemoryTest.cs b/test/EFCore.InMemory.FunctionalTests/GraphUpdates/ProxyGraphUpdatesInMemoryTest.cs index bfbf9e072a5..f130dcf9562 100644 --- a/test/EFCore.InMemory.FunctionalTests/GraphUpdates/ProxyGraphUpdatesInMemoryTest.cs +++ b/test/EFCore.InMemory.FunctionalTests/GraphUpdates/ProxyGraphUpdatesInMemoryTest.cs @@ -15,85 +15,87 @@ protected ProxyGraphUpdatesInMemoryTestBase(TFixture fixture) } [ConditionalFact(Skip = "FK constraint checking. Issue #2166")] - public override void Optional_one_to_one_relationships_are_one_to_one() + public override Task Optional_one_to_one_relationships_are_one_to_one() => base.Optional_one_to_one_relationships_are_one_to_one(); [ConditionalFact(Skip = "FK constraint checking. Issue #2166")] - public override void Optional_one_to_one_with_AK_relationships_are_one_to_one() + public override Task Optional_one_to_one_with_AK_relationships_are_one_to_one() => base.Optional_one_to_one_with_AK_relationships_are_one_to_one(); [ConditionalTheory(Skip = "Cascade delete. Issue #3924")] - public override void Optional_many_to_one_dependents_with_alternate_key_are_orphaned_in_store( + public override Task Optional_many_to_one_dependents_with_alternate_key_are_orphaned_in_store( CascadeTiming cascadeDeleteTiming, CascadeTiming deleteOrphansTiming) => base.Optional_many_to_one_dependents_with_alternate_key_are_orphaned_in_store(cascadeDeleteTiming, deleteOrphansTiming); [ConditionalTheory(Skip = "Cascade delete. Issue #3924")] - public override void Optional_many_to_one_dependents_are_orphaned_in_store( + public override Task Optional_many_to_one_dependents_are_orphaned_in_store( CascadeTiming cascadeDeleteTiming, CascadeTiming deleteOrphansTiming) => base.Optional_many_to_one_dependents_are_orphaned_in_store(cascadeDeleteTiming, deleteOrphansTiming); [ConditionalTheory(Skip = "Cascade delete. Issue #3924")] - public override void Required_one_to_one_are_cascade_detached_when_Added( + public override Task Required_one_to_one_are_cascade_detached_when_Added( CascadeTiming cascadeDeleteTiming, CascadeTiming deleteOrphansTiming) => base.Required_one_to_one_are_cascade_detached_when_Added(cascadeDeleteTiming, deleteOrphansTiming); [ConditionalFact(Skip = "FK constraint checking. Issue #2166")] - public override void Required_one_to_one_relationships_are_one_to_one() + public override Task Required_one_to_one_relationships_are_one_to_one() => base.Required_one_to_one_relationships_are_one_to_one(); [ConditionalFact(Skip = "FK constraint checking. Issue #2166")] - public override void Required_one_to_one_with_AK_relationships_are_one_to_one() + public override Task Required_one_to_one_with_AK_relationships_are_one_to_one() => base.Required_one_to_one_with_AK_relationships_are_one_to_one(); [ConditionalTheory(Skip = "Cascade delete. Issue #3924")] - public override void Required_one_to_one_with_alternate_key_are_cascade_detached_when_Added( + public override Task Required_one_to_one_with_alternate_key_are_cascade_detached_when_Added( CascadeTiming cascadeDeleteTiming, CascadeTiming deleteOrphansTiming) => base.Required_one_to_one_with_alternate_key_are_cascade_detached_when_Added(cascadeDeleteTiming, deleteOrphansTiming); [ConditionalTheory(Skip = "Cascade delete. Issue #3924")] - public override void Required_one_to_one_with_alternate_key_are_cascade_deleted_in_store( + public override Task Required_one_to_one_with_alternate_key_are_cascade_deleted_in_store( CascadeTiming cascadeDeleteTiming, CascadeTiming deleteOrphansTiming) => base.Required_one_to_one_with_alternate_key_are_cascade_deleted_in_store(cascadeDeleteTiming, deleteOrphansTiming); [ConditionalTheory(Skip = "Cascade delete. Issue #3924")] - public override void Required_many_to_one_dependents_are_cascade_deleted_in_store( + public override Task Required_many_to_one_dependents_are_cascade_deleted_in_store( CascadeTiming cascadeDeleteTiming, CascadeTiming deleteOrphansTiming) => base.Required_many_to_one_dependents_are_cascade_deleted_in_store(cascadeDeleteTiming, deleteOrphansTiming); [ConditionalTheory(Skip = "Cascade delete. Issue #3924")] - public override void Required_many_to_one_dependents_with_alternate_key_are_cascade_deleted_in_store( + public override Task Required_many_to_one_dependents_with_alternate_key_are_cascade_deleted_in_store( CascadeTiming cascadeDeleteTiming, CascadeTiming deleteOrphansTiming) => base.Required_many_to_one_dependents_with_alternate_key_are_cascade_deleted_in_store( cascadeDeleteTiming, deleteOrphansTiming); [ConditionalTheory(Skip = "Cascade delete. Issue #3924")] - public override void Required_non_PK_one_to_one_are_cascade_detached_when_Added( + public override Task Required_non_PK_one_to_one_are_cascade_detached_when_Added( CascadeTiming cascadeDeleteTiming, CascadeTiming deleteOrphansTiming) => base.Required_non_PK_one_to_one_are_cascade_detached_when_Added(cascadeDeleteTiming, deleteOrphansTiming); [ConditionalTheory(Skip = "Cascade delete. Issue #3924")] - public override void Required_non_PK_one_to_one_with_alternate_key_are_cascade_detached_when_Added( + public override Task Required_non_PK_one_to_one_with_alternate_key_are_cascade_detached_when_Added( CascadeTiming cascadeDeleteTiming, CascadeTiming deleteOrphansTiming) => base.Required_non_PK_one_to_one_with_alternate_key_are_cascade_detached_when_Added( cascadeDeleteTiming, deleteOrphansTiming); - protected override void ExecuteWithStrategyInTransaction( - Action testOperation, - Action nestedTestOperation1 = null, - Action nestedTestOperation2 = null, - Action nestedTestOperation3 = null) + protected override async Task ExecuteWithStrategyInTransactionAsync( + Func testOperation, + Func nestedTestOperation1 = null, + Func nestedTestOperation2 = null, + Func nestedTestOperation3 = null) { - base.ExecuteWithStrategyInTransaction(testOperation, nestedTestOperation1, nestedTestOperation2, nestedTestOperation3); - Fixture.Reseed(); + await base.ExecuteWithStrategyInTransactionAsync( + testOperation, nestedTestOperation1, nestedTestOperation2, nestedTestOperation3); + + await Fixture.ReseedAsync(); } public abstract class ProxyGraphUpdatesInMemoryFixtureBase : ProxyGraphUpdatesFixtureBase @@ -106,7 +108,8 @@ public override DbContextOptionsBuilder AddOptions(DbContextOptionsBuilder build } } - public class LazyLoading(LazyLoading.ProxyGraphUpdatesWithLazyLoadingInMemoryFixture fixture) : ProxyGraphUpdatesInMemoryTestBase(fixture) + public class LazyLoading(LazyLoading.ProxyGraphUpdatesWithLazyLoadingInMemoryFixture fixture) + : ProxyGraphUpdatesInMemoryTestBase(fixture) { protected override bool DoesLazyLoading => true; @@ -127,13 +130,12 @@ protected override IServiceCollection AddServices(IServiceCollection serviceColl } } - public class ChangeTracking(ChangeTracking.ProxyGraphUpdatesWithChangeTrackingInMemoryFixture fixture) : ProxyGraphUpdatesInMemoryTestBase(fixture) + public class ChangeTracking(ChangeTracking.ProxyGraphUpdatesWithChangeTrackingInMemoryFixture fixture) + : ProxyGraphUpdatesInMemoryTestBase(fixture) { - // Needs lazy loading - public override void Save_two_entity_cycle_with_lazy_loading() - { - } + public override Task Save_two_entity_cycle_with_lazy_loading() + => Task.CompletedTask; protected override bool DoesLazyLoading => false; @@ -154,8 +156,9 @@ protected override IServiceCollection AddServices(IServiceCollection serviceColl } } - public class LazyLoadingAndChangeTracking(LazyLoadingAndChangeTracking.ProxyGraphUpdatesWithChangeTrackingInMemoryFixture fixture) : ProxyGraphUpdatesInMemoryTestBase< - LazyLoadingAndChangeTracking.ProxyGraphUpdatesWithChangeTrackingInMemoryFixture>(fixture) + public class LazyLoadingAndChangeTracking(LazyLoadingAndChangeTracking.ProxyGraphUpdatesWithChangeTrackingInMemoryFixture fixture) + : ProxyGraphUpdatesInMemoryTestBase< + LazyLoadingAndChangeTracking.ProxyGraphUpdatesWithChangeTrackingInMemoryFixture>(fixture) { protected override bool DoesLazyLoading => true; diff --git a/test/EFCore.InMemory.FunctionalTests/JsonTypesInMemoryTest.cs b/test/EFCore.InMemory.FunctionalTests/JsonTypesInMemoryTest.cs index 998a87bce0b..269f5d4fe47 100644 --- a/test/EFCore.InMemory.FunctionalTests/JsonTypesInMemoryTest.cs +++ b/test/EFCore.InMemory.FunctionalTests/JsonTypesInMemoryTest.cs @@ -7,37 +7,38 @@ namespace Microsoft.EntityFrameworkCore; public class JsonTypesInMemoryTest : JsonTypesTestBase { - public override void Can_read_write_point() + public override Task Can_read_write_point() // No built-in JSON support for spatial types in the in-memory provider - => Assert.Throws(() => base.Can_read_write_point()); + => Assert.ThrowsAsync(() => base.Can_read_write_point()); - public override void Can_read_write_point_with_M() + public override Task Can_read_write_point_with_M() // No built-in JSON support for spatial types in the in-memory provider - => Assert.Throws(() => base.Can_read_write_point_with_M()); + => Assert.ThrowsAsync(() => base.Can_read_write_point_with_M()); - public override void Can_read_write_point_with_Z() + public override Task Can_read_write_point_with_Z() // No built-in JSON support for spatial types in the in-memory provider - => Assert.Throws(() => base.Can_read_write_point_with_Z()); + => Assert.ThrowsAsync(() => base.Can_read_write_point_with_Z()); - public override void Can_read_write_point_with_Z_and_M() + public override Task Can_read_write_point_with_Z_and_M() // No built-in JSON support for spatial types in the in-memory provider - => Assert.Throws(() => base.Can_read_write_point_with_Z_and_M()); + => Assert.ThrowsAsync(() => base.Can_read_write_point_with_Z_and_M()); - public override void Can_read_write_line_string() + public override Task Can_read_write_line_string() // No built-in JSON support for spatial types in the in-memory provider - => Assert.Throws(() => base.Can_read_write_line_string()); + => Assert.ThrowsAsync(() => base.Can_read_write_line_string()); - public override void Can_read_write_multi_line_string() + public override Task Can_read_write_multi_line_string() // No built-in JSON support for spatial types in the in-memory provider - => Assert.Throws(() => base.Can_read_write_multi_line_string()); + => Assert.ThrowsAsync(() => base.Can_read_write_multi_line_string()); - public override void Can_read_write_polygon() + public override Task Can_read_write_polygon() // No built-in JSON support for spatial types in the in-memory provider - => Assert.Throws(() => base.Can_read_write_polygon()); + => Assert.ThrowsAsync(() => base.Can_read_write_polygon()); - public override void Can_read_write_polygon_typed_as_geometry() + public override Task Can_read_write_polygon_typed_as_geometry() // No built-in JSON support for spatial types in the in-memory provider - => Assert.Throws(base.Can_read_write_polygon_typed_as_geometry); + => Assert.ThrowsAsync(base.Can_read_write_polygon_typed_as_geometry); - protected override ITestStoreFactory TestStoreFactory => InMemoryTestStoreFactory.Instance; + protected override ITestStoreFactory TestStoreFactory + => InMemoryTestStoreFactory.Instance; } diff --git a/test/EFCore.InMemory.FunctionalTests/KeysWithConvertersInMemoryTest.cs b/test/EFCore.InMemory.FunctionalTests/KeysWithConvertersInMemoryTest.cs index cbf85b1dc16..5d0e4e1c7e8 100644 --- a/test/EFCore.InMemory.FunctionalTests/KeysWithConvertersInMemoryTest.cs +++ b/test/EFCore.InMemory.FunctionalTests/KeysWithConvertersInMemoryTest.cs @@ -3,35 +3,36 @@ namespace Microsoft.EntityFrameworkCore; -public class KeysWithConvertersInMemoryTest(KeysWithConvertersInMemoryTest.KeysWithConvertersInMemoryFixture fixture) : KeysWithConvertersTestBase< - KeysWithConvertersInMemoryTest.KeysWithConvertersInMemoryFixture>(fixture) +public class KeysWithConvertersInMemoryTest(KeysWithConvertersInMemoryTest.KeysWithConvertersInMemoryFixture fixture) + : KeysWithConvertersTestBase< + KeysWithConvertersInMemoryTest.KeysWithConvertersInMemoryFixture>(fixture) { [ConditionalFact(Skip = "Issue #26238")] - public override void Can_insert_and_read_back_with_bare_class_key_and_optional_dependents() + public override Task Can_insert_and_read_back_with_bare_class_key_and_optional_dependents() => base.Can_insert_and_read_back_with_bare_class_key_and_optional_dependents(); [ConditionalFact(Skip = "Issue #26238")] - public override void Can_insert_and_read_back_with_bare_class_key_and_optional_dependents_with_shadow_FK() + public override Task Can_insert_and_read_back_with_bare_class_key_and_optional_dependents_with_shadow_FK() => base.Can_insert_and_read_back_with_bare_class_key_and_optional_dependents_with_shadow_FK(); [ConditionalFact(Skip = "Issue #26238")] - public override void Can_insert_and_read_back_with_struct_binary_key_and_optional_dependents() + public override Task Can_insert_and_read_back_with_struct_binary_key_and_optional_dependents() => base.Can_insert_and_read_back_with_struct_binary_key_and_optional_dependents(); [ConditionalFact(Skip = "Issue #26238")] - public override void Can_insert_and_read_back_with_struct_binary_key_and_required_dependents() + public override Task Can_insert_and_read_back_with_struct_binary_key_and_required_dependents() => base.Can_insert_and_read_back_with_struct_binary_key_and_required_dependents(); [ConditionalFact(Skip = "Issue #26238")] - public override void Can_query_and_update_owned_entity_with_value_converter() + public override Task Can_query_and_update_owned_entity_with_value_converter() => base.Can_query_and_update_owned_entity_with_value_converter(); [ConditionalFact(Skip = "Issue #26238")] - public override void Can_query_and_update_owned_entity_with_int_bare_class_key() + public override Task Can_query_and_update_owned_entity_with_int_bare_class_key() => base.Can_query_and_update_owned_entity_with_int_bare_class_key(); [ConditionalFact(Skip = "Issue #26238")] - public override void Can_insert_and_read_back_with_enumerable_class_key_and_optional_dependents() + public override Task Can_insert_and_read_back_with_enumerable_class_key_and_optional_dependents() => base.Can_insert_and_read_back_with_enumerable_class_key_and_optional_dependents(); public class KeysWithConvertersInMemoryFixture : KeysWithConvertersFixtureBase diff --git a/test/EFCore.InMemory.FunctionalTests/ManyToManyTrackingInMemoryTest.cs b/test/EFCore.InMemory.FunctionalTests/ManyToManyTrackingInMemoryTest.cs index 1a67e452e33..309a8af440e 100644 --- a/test/EFCore.InMemory.FunctionalTests/ManyToManyTrackingInMemoryTest.cs +++ b/test/EFCore.InMemory.FunctionalTests/ManyToManyTrackingInMemoryTest.cs @@ -8,18 +8,6 @@ namespace Microsoft.EntityFrameworkCore; public class ManyToManyTrackingInMemoryTest(ManyToManyTrackingInMemoryTest.ManyToManyTrackingInMemoryFixture fixture) : ManyToManyTrackingTestBase(fixture) { - protected override void ExecuteWithStrategyInTransaction( - Action testOperation, - Action nestedTestOperation1 = null, - Action nestedTestOperation2 = null, - Action nestedTestOperation3 = null) - { - base.ExecuteWithStrategyInTransaction( - testOperation, nestedTestOperation1, nestedTestOperation2, nestedTestOperation3); - - Fixture.Reseed(); - } - protected override async Task ExecuteWithStrategyInTransactionAsync( Func testOperation, Func nestedTestOperation1 = null, diff --git a/test/EFCore.InMemory.FunctionalTests/Query/OwnedEntityQueryInMemoryTest.cs b/test/EFCore.InMemory.FunctionalTests/Query/OwnedEntityQueryInMemoryTest.cs index 1c324ffe437..44bdf7bf0e5 100644 --- a/test/EFCore.InMemory.FunctionalTests/Query/OwnedEntityQueryInMemoryTest.cs +++ b/test/EFCore.InMemory.FunctionalTests/Query/OwnedEntityQueryInMemoryTest.cs @@ -12,7 +12,7 @@ protected override ITestStoreFactory TestStoreFactory [MemberData(nameof(IsAsyncData))] public virtual async Task Expand_owned_navigation_as_optional_always(bool async) { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var query = context.Set().Include(c => c.Bar); @@ -25,11 +25,11 @@ public virtual async Task Expand_owned_navigation_as_optional_always(bool async) protected class MyContext(DbContextOptions options) : DbContext(options) { - public void Seed() + public Task SeedAsync() { Add(new Foo()); - SaveChanges(); + return SaveChangesAsync(); } protected override void OnModelCreating(ModelBuilder modelBuilder) @@ -65,7 +65,7 @@ protected class Foo [MemberData(nameof(IsAsyncData))] public virtual async Task Owned_references_on_same_level_expanded_at_different_times_around_take(bool async) { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); await base.Owned_references_on_same_level_expanded_at_different_times_around_take_helper(context, async); @@ -75,7 +75,7 @@ public virtual async Task Owned_references_on_same_level_expanded_at_different_t [MemberData(nameof(IsAsyncData))] public virtual async Task Owned_references_on_same_level_nested_expanded_at_different_times_around_take(bool async) { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); await base.Owned_references_on_same_level_nested_expanded_at_different_times_around_take_helper(context, async); diff --git a/test/EFCore.InMemory.FunctionalTests/Query/QueryBugsInMemoryTest.cs b/test/EFCore.InMemory.FunctionalTests/Query/QueryBugsInMemoryTest.cs index 65dc10fdaa3..6e4dc50c5ad 100644 --- a/test/EFCore.InMemory.FunctionalTests/Query/QueryBugsInMemoryTest.cs +++ b/test/EFCore.InMemory.FunctionalTests/Query/QueryBugsInMemoryTest.cs @@ -14,9 +14,9 @@ public class QueryBugsInMemoryTest : IClassFixture #region Bug9849 [ConditionalFact] - public virtual void Include_throw_when_empty_9849() + public virtual async Task Include_throw_when_empty_9849() { - using (CreateScratch(_ => { }, "9849")) + using (await CreateScratchAsync(_ => Task.CompletedTask, "9849")) { using var context = new DatabaseContext(); var results = context.VehicleInspections.Include(_ => _.Motors).ToList(); @@ -26,9 +26,9 @@ public virtual void Include_throw_when_empty_9849() } [ConditionalFact] - public virtual void Include_throw_when_empty_9849_2() + public virtual async Task Include_throw_when_empty_9849_2() { - using (CreateScratch(_ => { }, "9849")) + using (await CreateScratchAsync(_ => Task.CompletedTask, "9849")) { using var context = new DatabaseContext(); #pragma warning disable IDE1006 // Naming Styles @@ -40,9 +40,9 @@ public virtual void Include_throw_when_empty_9849_2() } [ConditionalFact] - public virtual void Include_throw_when_empty_9849_3() + public virtual async Task Include_throw_when_empty_9849_3() { - using (CreateScratch(_ => { }, "9849")) + using (await CreateScratchAsync(_ => Task.CompletedTask, "9849")) { using var context = new DatabaseContext(); #pragma warning disable IDE1006 // Naming Styles @@ -54,9 +54,9 @@ public virtual void Include_throw_when_empty_9849_3() } [ConditionalFact] - public virtual void Include_throw_when_empty_9849_4() + public virtual async Task Include_throw_when_empty_9849_4() { - using (CreateScratch(_ => { }, "9849")) + using (await CreateScratchAsync(_ => Task.CompletedTask, "9849")) { using var context = new DatabaseContext(); #pragma warning disable IDE1006 // Naming Styles @@ -68,9 +68,9 @@ public virtual void Include_throw_when_empty_9849_4() } [ConditionalFact] - public virtual void Include_throw_when_empty_9849_5() + public virtual async Task Include_throw_when_empty_9849_5() { - using (CreateScratch(_ => { }, "9849")) + using (await CreateScratchAsync(_ => Task.CompletedTask, "9849")) { using var context = new DatabaseContext(); var results @@ -84,9 +84,9 @@ join __ in context.VehicleInspections on _f.Id equals __.Id } [ConditionalFact] - public virtual void Include_throw_when_empty_9849_6() + public virtual async Task Include_throw_when_empty_9849_6() { - using (CreateScratch(_ => { }, "9849")) + using (await CreateScratchAsync(_ => Task.CompletedTask, "9849")) { using var context = new DatabaseContext(); #pragma warning disable IDE1006 // Naming Styles @@ -121,6 +121,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) // ReSharper disable once UnusedAutoPropertyAccessor.Local public DbSet VehicleInspections { get; set; } + // ReSharper disable once UnusedAutoPropertyAccessor.Local public DbSet Motors { get; set; } } @@ -143,9 +144,9 @@ private class Motor #region Bug3595 [ConditionalFact] - public virtual void GroupBy_with_uninitialized_datetime_projection_3595() + public virtual async Task GroupBy_with_uninitialized_datetime_projection_3595() { - using (CreateScratch(Seed3595, "3595")) + using (await CreateScratchAsync(Seed3595, "3595")) { using var context = new Context3595(); var q0 = from instance in context.Exams @@ -162,7 +163,7 @@ into gQuestions } } - private static void Seed3595(Context3595 context) + private static Task Seed3595(Context3595 context) { var question = new Question3595(); var examInstance = new Exam3595(); @@ -171,7 +172,7 @@ private static void Seed3595(Context3595 context) context.Add(question); context.Add(examInstance); context.Add(examInstanceQuestion); - context.SaveChanges(); + return context.SaveChangesAsync(); } private abstract class Base3595 @@ -206,6 +207,7 @@ private class Context3595 : DbContext // ReSharper disable once UnusedAutoPropertyAccessor.Local public DbSet Exams { get; set; } public DbSet Questions { get; set; } + // ReSharper disable once UnusedAutoPropertyAccessor.Local public DbSet ExamQuestions { get; set; } @@ -220,9 +222,9 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) #region Bug3101 [ConditionalFact] - public virtual void Repro3101_simple_coalesce1() + public virtual async Task Repro3101_simple_coalesce1() { - using (CreateScratch(Seed3101, "3101")) + using (await CreateScratchAsync(Seed3101, "3101")) { using var ctx = new MyContext3101(); var query = from eVersion in ctx.Entities @@ -237,9 +239,9 @@ from eRootJoined in RootEntities.DefaultIfEmpty() } [ConditionalFact] - public virtual void Repro3101_simple_coalesce2() + public virtual async Task Repro3101_simple_coalesce2() { - using (CreateScratch(Seed3101, "3101")) + using (await CreateScratchAsync(Seed3101, "3101")) { using var ctx = new MyContext3101(); var query = from eVersion in ctx.Entities @@ -255,9 +257,9 @@ from eRootJoined in RootEntities.DefaultIfEmpty() } [ConditionalFact] - public virtual void Repro3101_simple_coalesce3() + public virtual async Task Repro3101_simple_coalesce3() { - using (CreateScratch(Seed3101, "3101")) + using (await CreateScratchAsync(Seed3101, "3101")) { using var ctx = new MyContext3101(); var query = from eVersion in ctx.Entities.Include(e => e.Children) @@ -274,9 +276,9 @@ from eRootJoined in RootEntities.DefaultIfEmpty() } [ConditionalFact] - public virtual void Repro3101_complex_coalesce1() + public virtual async Task Repro3101_complex_coalesce1() { - using (CreateScratch(Seed3101, "3101")) + using (await CreateScratchAsync(Seed3101, "3101")) { using var ctx = new MyContext3101(); var query = from eVersion in ctx.Entities.Include(e => e.Children) @@ -292,9 +294,9 @@ from eRootJoined in RootEntities.DefaultIfEmpty() } [ConditionalFact] - public virtual void Repro3101_complex_coalesce2() + public virtual async Task Repro3101_complex_coalesce2() { - using (CreateScratch(Seed3101, "3101")) + using (await CreateScratchAsync(Seed3101, "3101")) { using var ctx = new MyContext3101(); var query = from eVersion in ctx.Entities @@ -310,9 +312,9 @@ from eRootJoined in RootEntities.DefaultIfEmpty() } [ConditionalFact] - public virtual void Repro3101_nested_coalesce1() + public virtual async Task Repro3101_nested_coalesce1() { - using (CreateScratch(Seed3101, "3101")) + using (await CreateScratchAsync(Seed3101, "3101")) { using var ctx = new MyContext3101(); var query = from eVersion in ctx.Entities @@ -328,9 +330,9 @@ from eRootJoined in RootEntities.DefaultIfEmpty() } [ConditionalFact] - public virtual void Repro3101_nested_coalesce2() + public virtual async Task Repro3101_nested_coalesce2() { - using (CreateScratch(Seed3101, "3101")) + using (await CreateScratchAsync(Seed3101, "3101")) { using var ctx = new MyContext3101(); var query = from eVersion in ctx.Entities.Include(e => e.Children) @@ -351,9 +353,9 @@ from eRootJoined in RootEntities.DefaultIfEmpty() } [ConditionalFact] - public virtual void Repro3101_conditional() + public virtual async Task Repro3101_conditional() { - using (CreateScratch(Seed3101, "3101")) + using (await CreateScratchAsync(Seed3101, "3101")) { using var ctx = new MyContext3101(); var query = from eVersion in ctx.Entities.Include(e => e.Children) @@ -371,9 +373,9 @@ from eRootJoined in RootEntities.DefaultIfEmpty() } [ConditionalFact] - public virtual void Repro3101_coalesce_tracking() + public virtual async Task Repro3101_coalesce_tracking() { - using (CreateScratch(Seed3101, "3101")) + using (await CreateScratchAsync(Seed3101, "3101")) { using var ctx = new MyContext3101(); var query = from eVersion in ctx.Entities @@ -394,7 +396,7 @@ from eRootJoined in RootEntities.DefaultIfEmpty() } } - private static void Seed3101(MyContext3101 context) + private static Task Seed3101(MyContext3101 context) { var c11 = new Child3101 { Name = "c11" }; var c12 = new Child3101 { Name = "c12" }; @@ -413,7 +415,7 @@ private static void Seed3101(MyContext3101 context) e2.RootEntity = e1; context.Entities.AddRange(e1, e2, e3); - context.SaveChanges(); + return context.SaveChangesAsync(); } private class MyContext3101 : DbContext @@ -460,9 +462,9 @@ private class Child3101 #region Bug5456 [ConditionalFact] - public virtual void Repro5456_include_group_join_is_per_query_context() + public virtual async Task Repro5456_include_group_join_is_per_query_context() { - using (CreateScratch(Seed5456, "5456")) + using (await CreateScratchAsync(Seed5456, "5456")) { Parallel.For( 0, 10, i => @@ -476,25 +478,32 @@ public virtual void Repro5456_include_group_join_is_per_query_context() } [ConditionalFact] - public virtual void Repro5456_include_group_join_is_per_query_context_async() + public virtual async Task Repro5456_include_group_join_is_per_query_context_async() { - using (CreateScratch(Seed5456, "5456")) + using (await CreateScratchAsync(Seed5456, "5456")) { - Parallel.For( - 0, 10, async i => - { - using var ctx = new MyContext5456(); - var result = await ctx.Posts.Where(x => x.Blog.Id > 1).Include(x => x.Blog).ToListAsync(); + var tasks = new List(); + for (var i = 0; i < 10; i++) + { + tasks.Add(Action()); + } - Assert.Equal(198, result.Count); - }); + Task.WaitAll(tasks.ToArray()); + } + + async Task Action() + { + using var ctx = new MyContext5456(); + var result = await ctx.Posts.Where(x => x.Blog.Id > 1).Include(x => x.Blog).ToListAsync(); + + Assert.Equal(198, result.Count); } } [ConditionalFact] - public virtual void Repro5456_multiple_include_group_join_is_per_query_context() + public virtual async Task Repro5456_multiple_include_group_join_is_per_query_context() { - using (CreateScratch(Seed5456, "5456")) + using (await CreateScratchAsync(Seed5456, "5456")) { Parallel.For( 0, 10, i => @@ -508,26 +517,33 @@ public virtual void Repro5456_multiple_include_group_join_is_per_query_context() } [ConditionalFact] - public virtual void Repro5456_multiple_include_group_join_is_per_query_context_async() + public virtual async Task Repro5456_multiple_include_group_join_is_per_query_context_async() { - using (CreateScratch(Seed5456, "5456")) + using (await CreateScratchAsync(Seed5456, "5456")) { - Parallel.For( - 0, 10, async i => - { - using var ctx = new MyContext5456(); - var result = await ctx.Posts.Where(x => x.Blog.Id > 1).Include(x => x.Blog).Include(x => x.Comments) - .ToListAsync(); + var tasks = new List(); + for (var i = 0; i < 10; i++) + { + tasks.Add(Action()); + } - Assert.Equal(198, result.Count); - }); + Task.WaitAll(tasks.ToArray()); + } + + async Task Action() + { + using var ctx = new MyContext5456(); + var result = await ctx.Posts.Where(x => x.Blog.Id > 1).Include(x => x.Blog).Include(x => x.Comments) + .ToListAsync(); + + Assert.Equal(198, result.Count); } } [ConditionalFact] - public virtual void Repro5456_multi_level_include_group_join_is_per_query_context() + public virtual async Task Repro5456_multi_level_include_group_join_is_per_query_context() { - using (CreateScratch(Seed5456, "5456")) + using (await CreateScratchAsync(Seed5456, "5456")) { Parallel.For( 0, 10, i => @@ -541,23 +557,30 @@ public virtual void Repro5456_multi_level_include_group_join_is_per_query_contex } [ConditionalFact] - public virtual void Repro5456_multi_level_include_group_join_is_per_query_context_async() + public virtual async Task Repro5456_multi_level_include_group_join_is_per_query_context_async() { - using (CreateScratch(Seed5456, "5456")) + using (await CreateScratchAsync(Seed5456, "5456")) { - Parallel.For( - 0, 10, async i => - { - using var ctx = new MyContext5456(); - var result = await ctx.Posts.Where(x => x.Blog.Id > 1).Include(x => x.Blog).ThenInclude(b => b.Author) - .ToListAsync(); + var tasks = new List(); + for (var i = 0; i < 10; i++) + { + tasks.Add(Action()); + } - Assert.Equal(198, result.Count); - }); + Task.WaitAll(tasks.ToArray()); + } + + async Task Action() + { + using var ctx = new MyContext5456(); + var result = await ctx.Posts.Where(x => x.Blog.Id > 1).Include(x => x.Blog).ThenInclude(b => b.Author) + .ToListAsync(); + + Assert.Equal(198, result.Count); } } - private void Seed5456(MyContext5456 context) + private Task Seed5456(MyContext5456 context) { for (var i = 0; i < 100; i++) { @@ -570,12 +593,13 @@ private void Seed5456(MyContext5456 context) }); } - context.SaveChanges(); + return context.SaveChangesAsync(); } private class MyContext5456 : DbContext { public DbSet Blogs { get; set; } + // ReSharper disable once UnusedAutoPropertyAccessor.Local public DbSet Posts { get; set; } public DbSet Comments { get; set; } @@ -621,9 +645,9 @@ private class Comment5456 #region Bug8282 [ConditionalFact] - public virtual void Entity_passed_to_DTO_constructor_works() + public virtual async Task Entity_passed_to_DTO_constructor_works() { - using (CreateScratch(e => { }, "8282")) + using (await CreateScratchAsync(_ => Task.CompletedTask, "8282")) { using var context = new MyContext8282(); var query = context.Entity.Select(e => new EntityDto8282(e)).ToList(); @@ -658,9 +682,9 @@ private class EntityDto8282(Entity8282 entity) #region Issue21803 [ConditionalFact] - public virtual void Select_enumerable_navigation_backed_by_collection() + public virtual async Task Select_enumerable_navigation_backed_by_collection() { - using (CreateScratch(Seed21803, "21803")) + using (await CreateScratchAsync(Seed21803, "21803")) { using var context = new MyContext21803(); @@ -670,7 +694,7 @@ public virtual void Select_enumerable_navigation_backed_by_collection() } } - private static void Seed21803(MyContext21803 context) + private static Task Seed21803(MyContext21803 context) { var appEntity = new AppEntity21803(); context.AddRange( @@ -679,7 +703,7 @@ private static void Seed21803(MyContext21803 context) new OtherEntity21803 { AppEntity = appEntity }, new OtherEntity21803 { AppEntity = appEntity }); - context.SaveChanges(); + return context.SaveChangesAsync(); } private class AppEntity21803 @@ -713,9 +737,9 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) #region Issue20729 [ConditionalFact] - public virtual void Multiple_owned_references_at_same_level_maintains_valueBuffer_positions() + public virtual async Task Multiple_owned_references_at_same_level_maintains_valueBuffer_positions() { - using (CreateScratch(Seed20729, "20729")) + using (await CreateScratchAsync(Seed20729, "20729")) { using var context = new MyContext20729(); @@ -737,7 +761,7 @@ public virtual void Multiple_owned_references_at_same_level_maintains_valueBuffe } } - private static void Seed20729(MyContext20729 context) + private static Task Seed20729(MyContext20729 context) { context.Owners.Add( new Owner20729 @@ -745,7 +769,7 @@ private static void Seed20729(MyContext20729 context) Owned1 = new Owned120729(), Owned2 = new Owned220729(), }); - context.SaveChanges(); + return context.SaveChangesAsync(); } private class Owner20729 @@ -791,9 +815,9 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) #region Issue23285 [ConditionalFact] - public virtual void Owned_reference_on_base_with_hierarchy() + public virtual async Task Owned_reference_on_base_with_hierarchy() { - using (CreateScratch(Seed23285, "23285")) + using (await CreateScratchAsync(Seed23285, "23285")) { using var context = new MyContext23285(); @@ -804,11 +828,11 @@ public virtual void Owned_reference_on_base_with_hierarchy() } } - private static void Seed23285(MyContext23285 context) + private static Task Seed23285(MyContext23285 context) { context.Table.Add(new ChildA23285()); - context.SaveChanges(); + return context.SaveChangesAsync(); } [Owned] @@ -856,9 +880,9 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) #region Issue23687 [ConditionalFact] - public virtual void Owned_reference_with_composite_key() + public virtual async Task Owned_reference_with_composite_key() { - using (CreateScratch(Seed23687, "23687")) + using (await CreateScratchAsync(Seed23687, "23687")) { using var context = new MyContext23687(); @@ -870,7 +894,7 @@ public virtual void Owned_reference_with_composite_key() } } - private static void Seed23687(MyContext23687 context) + private static Task Seed23687(MyContext23687 context) { context.Table.Add( new Root23687 @@ -880,7 +904,7 @@ private static void Seed23687(MyContext23687 context) OwnedProp = new OwnedClass23687 { A = "A", B = "B" } }); - context.SaveChanges(); + return context.SaveChangesAsync(); } [Owned] @@ -917,9 +941,9 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) #region Issue23593 [ConditionalFact] - public virtual void Join_with_enum_as_key_selector() + public virtual async Task Join_with_enum_as_key_selector() { - using (CreateScratch(Seed23593, "23593")) + using (await CreateScratchAsync(Seed23593, "23593")) { using var context = new MyContext23593(); @@ -933,9 +957,9 @@ join sme in context.StatusMapEvents on sm.Id equals sme.Id } [ConditionalFact] - public virtual void Join_with_enum_inside_anonymous_type_as_key_selector() + public virtual async Task Join_with_enum_inside_anonymous_type_as_key_selector() { - using (CreateScratch(Seed23593, "23593")) + using (await CreateScratchAsync(Seed23593, "23593")) { using var context = new MyContext23593(); @@ -949,9 +973,9 @@ public virtual void Join_with_enum_inside_anonymous_type_as_key_selector() } [ConditionalFact] - public virtual void Join_with_enum_inside_anonymous_type_with_other_property_as_key_selector() + public virtual async Task Join_with_enum_inside_anonymous_type_with_other_property_as_key_selector() { - using (CreateScratch(Seed23593, "23593")) + using (await CreateScratchAsync(Seed23593, "23593")) { using var context = new MyContext23593(); @@ -964,13 +988,13 @@ public virtual void Join_with_enum_inside_anonymous_type_with_other_property_as_ } } - private static void Seed23593(MyContext23593 context) + private static Task Seed23593(MyContext23593 context) { context.Add(new StatusMap23593 { Id = StatusMapCode23593.One }); context.Add(new StatusMap23593 { Id = StatusMapCode23593.Two }); context.Add(new StatusMapEvent23593 { Id = StatusMapCode23593.Two }); - context.SaveChanges(); + return context.SaveChangesAsync(); } private enum StatusMapCode23593 @@ -995,6 +1019,7 @@ private class MyContext23593 : DbContext { // ReSharper disable once UnusedAutoPropertyAccessor.Local public DbSet StatusMaps { get; set; } + // ReSharper disable once UnusedAutoPropertyAccessor.Local public DbSet StatusMapEvents { get; set; } @@ -1009,9 +1034,9 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) #region Issue23926 [ConditionalFact] - public virtual void Left_join_with_entity_with_enum_discriminator() + public virtual async Task Left_join_with_entity_with_enum_discriminator() { - using (CreateScratch(Seed23926, "23926")) + using (await CreateScratchAsync(Seed23926, "23926")) { using var context = new MyContext23926(); @@ -1021,13 +1046,13 @@ public virtual void Left_join_with_entity_with_enum_discriminator() } } - private static void Seed23926(MyContext23926 context) + private static Task Seed23926(MyContext23926 context) { context.Add(new History23926 { User = new User23926 { Name = "UserA" } }); context.Add(new History23926 { User = new DerivedUser23926 { Name = "DerivedUserB" } }); context.Add(new History23926 { User = null }); - context.SaveChanges(); + return context.SaveChangesAsync(); } private class History23926 @@ -1076,9 +1101,9 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) #region Issue18435 [ConditionalFact] - public virtual void Shared_owned_property_on_multiple_level_in_Select() + public virtual async Task Shared_owned_property_on_multiple_level_in_Select() { - using (CreateScratch(Seed18435, "18435")) + using (await CreateScratchAsync(Seed18435, "18435")) { using var context = new MyContext18435(); @@ -1101,7 +1126,7 @@ public virtual void Shared_owned_property_on_multiple_level_in_Select() } } - private static void Seed18435(MyContext18435 context) + private static Task Seed18435(MyContext18435 context) { context.Add( new RootEntity18435 @@ -1124,7 +1149,7 @@ private static void Seed18435(MyContext18435 context) } }); - context.SaveChanges(); + return context.SaveChangesAsync(); } private class RootEntity18435 @@ -1166,9 +1191,9 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) #region Issue19425 [ConditionalFact(Skip = "Issue#19425")] - public virtual void Non_nullable_cast_in_null_check() + public virtual async Task Non_nullable_cast_in_null_check() { - using (CreateScratch(Seed19425, "19425")) + using (await CreateScratchAsync(Seed19425, "19425")) { using var context = new MyContext19425(); @@ -1179,11 +1204,11 @@ public virtual void Non_nullable_cast_in_null_check() } } - private static void Seed19425(MyContext19425 context) + private static Task Seed19425(MyContext19425 context) { context.FooTable.Add(new FooTable19425 { Id = 1, Bar = null }); - context.SaveChanges(); + return context.SaveChangesAsync(); } private enum Bar19425 @@ -1214,9 +1239,9 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) #region Issue19667 [ConditionalFact] - public virtual void Property_access_on_nullable_converted_scalar_type() + public virtual async Task Property_access_on_nullable_converted_scalar_type() { - using (CreateScratch(Seed19667, "19667")) + using (await CreateScratchAsync(Seed19667, "19667")) { using var context = new MyContext19667(); @@ -1226,12 +1251,12 @@ public virtual void Property_access_on_nullable_converted_scalar_type() } } - private static void Seed19667(MyContext19667 context) + private static Task Seed19667(MyContext19667 context) { context.Entities.Add(new MyEntity19667 { Id = 1, Type = new MyType19667 { Date = new DateTime(2020, 1, 1) } }); context.Entities.Add(new MyEntity19667 { Id = 2, Type = new MyType19667 { Date = new DateTime(2020, 1, 1).AddDays(1) } }); - context.SaveChanges(); + return context.SaveChangesAsync(); } private class MyEntity19667 @@ -1263,9 +1288,9 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) #region Issue20359 [ConditionalFact] - public virtual void Changing_order_of_projection_in_anonymous_type_works() + public virtual async Task Changing_order_of_projection_in_anonymous_type_works() { - using (CreateScratch(Seed20359, "20359")) + using (await CreateScratchAsync(Seed20359, "20359")) { using var context = new MyContext20359(); @@ -1282,7 +1307,7 @@ public virtual void Changing_order_of_projection_in_anonymous_type_works() } } - private static void Seed20359(MyContext20359 context) + private static Task Seed20359(MyContext20359 context) { var root = new Root20359 { @@ -1291,7 +1316,7 @@ private static void Seed20359(MyContext20359 context) context.Add(root); - context.SaveChanges(); + return context.SaveChangesAsync(); } private class A20359 @@ -1350,9 +1375,9 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) #region Issue23360 [ConditionalFact] - public virtual void Union_with_different_property_name_using_same_anonymous_type() + public virtual async Task Union_with_different_property_name_using_same_anonymous_type() { - using (CreateScratch(Seed23360, "23360")) + using (await CreateScratchAsync(Seed23360, "23360")) { using var context = new MyContext23360(); @@ -1381,7 +1406,7 @@ public virtual void Union_with_different_property_name_using_same_anonymous_type } } - private static void Seed23360(MyContext23360 context) + private static Task Seed23360(MyContext23360 context) { context.User.Add( new User23360 @@ -1395,7 +1420,7 @@ private static void Seed23360(MyContext23360 context) GivenName = "John", FamilyName = "Doe", }); - context.SaveChanges(); + return context.SaveChangesAsync(); } private class User23360 @@ -1438,9 +1463,9 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) #region Issue18394 [ConditionalFact] - public virtual void Ordering_of_collection_result_is_correct() + public virtual async Task Ordering_of_collection_result_is_correct() { - using (CreateScratch(Seed18394, "18394")) + using (await CreateScratchAsync(Seed18394, "18394")) { using var context = new MyContext18394(); @@ -1465,12 +1490,12 @@ public virtual void Ordering_of_collection_result_is_correct() } } - private static void Seed18394(MyContext18394 context) + private static Task Seed18394(MyContext18394 context) { var a = new A18394 { PropertyB = new B18394 { PropertyCList = [new() { SomeText = "TestText" }] } }; context.As.Add(a); - context.SaveChanges(); + return context.SaveChangesAsync(); } private class ADto18394 @@ -1543,9 +1568,9 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) #region Issue23934 [ConditionalFact] - public virtual void Owned_entity_indexes_are_maintained_properly() + public virtual async Task Owned_entity_indexes_are_maintained_properly() { - using (CreateScratch(Seed23934, "23934")) + using (await CreateScratchAsync(Seed23934, "23934")) { using var context = new MyContext23934(); @@ -1557,7 +1582,7 @@ public virtual void Owned_entity_indexes_are_maintained_properly() } } - private static void Seed23934(MyContext23934 context) + private static Task Seed23934(MyContext23934 context) { var inner = new Inner23934 { Id = Guid.NewGuid(), OwnedProp = new OwnedClass23934 { At = new DateTime(2020, 1, 1) } }; @@ -1571,7 +1596,7 @@ private static void Seed23934(MyContext23934 context) context.Inners.Add(inner); context.Outers.Add(outer); - context.SaveChanges(); + return context.SaveChangesAsync(); } private class Outer23934 @@ -1612,10 +1637,10 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) #region SharedHelper - private static InMemoryTestStore CreateScratch(Action seed, string databaseName) + private static Task CreateScratchAsync(Func seed, string databaseName) where TContext : DbContext, new() => InMemoryTestStore.GetOrCreate(databaseName) - .InitializeInMemory(null, () => new TContext(), c => seed((TContext)c)); + .InitializeInMemoryAsync(null, () => new TContext(), c => seed((TContext)c)); #endregion } diff --git a/test/EFCore.InMemory.FunctionalTests/Query/SharedTypeQueryInMemoryTest.cs b/test/EFCore.InMemory.FunctionalTests/Query/SharedTypeQueryInMemoryTest.cs index ffa77d9a717..00af8f46592 100644 --- a/test/EFCore.InMemory.FunctionalTests/Query/SharedTypeQueryInMemoryTest.cs +++ b/test/EFCore.InMemory.FunctionalTests/Query/SharedTypeQueryInMemoryTest.cs @@ -13,7 +13,7 @@ protected override ITestStoreFactory TestStoreFactory public virtual async Task Can_use_shared_type_entity_type_in_ToInMemoryQuery(bool async) { var contextFactory = await InitializeAsync( - seed: c => c.Seed()); + seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); diff --git a/test/EFCore.InMemory.FunctionalTests/QueryExpressionInterceptionInMemoryTestBase.cs b/test/EFCore.InMemory.FunctionalTests/QueryExpressionInterceptionInMemoryTestBase.cs index 432f15ba2c1..28972312909 100644 --- a/test/EFCore.InMemory.FunctionalTests/QueryExpressionInterceptionInMemoryTestBase.cs +++ b/test/EFCore.InMemory.FunctionalTests/QueryExpressionInterceptionInMemoryTestBase.cs @@ -10,9 +10,9 @@ protected QueryExpressionInterceptionInMemoryTestBase(InterceptionInMemoryFixtur { } - public override UniverseContext Seed(UniverseContext context) + public override async Task SeedAsync(UniverseContext context) { - base.Seed(context); + await base.SeedAsync(context); context.AddRange( new Singularity { Id = 77, Type = "Black Hole" }, @@ -20,7 +20,7 @@ public override UniverseContext Seed(UniverseContext context) new Brane { Id = 77, Type = "Black Hole?" }, new Brane { Id = 88, Type = "Bing Bang?" }); - context.SaveChanges(); + await context.SaveChangesAsync(); context.ChangeTracker.Clear(); return context; @@ -44,7 +44,8 @@ public override DbContextOptionsBuilder AddOptions(DbContextOptionsBuilder build } public class QueryExpressionInterceptionInMemoryTest(QueryExpressionInterceptionInMemoryTest.InterceptionInMemoryFixture fixture) - : QueryExpressionInterceptionInMemoryTestBase(fixture), IClassFixture + : QueryExpressionInterceptionInMemoryTestBase(fixture), + IClassFixture { public class InterceptionInMemoryFixture : InterceptionInMemoryFixtureBase { @@ -53,7 +54,8 @@ protected override bool ShouldSubscribeToDiagnosticListener } } - public class QueryExpressionInterceptionWithDiagnosticsInMemoryTest(QueryExpressionInterceptionWithDiagnosticsInMemoryTest.InterceptionInMemoryFixture fixture) + public class QueryExpressionInterceptionWithDiagnosticsInMemoryTest( + QueryExpressionInterceptionWithDiagnosticsInMemoryTest.InterceptionInMemoryFixture fixture) : QueryExpressionInterceptionInMemoryTestBase(fixture), IClassFixture { diff --git a/test/EFCore.InMemory.FunctionalTests/Scaffolding/CompiledModelInMemoryTest.cs b/test/EFCore.InMemory.FunctionalTests/Scaffolding/CompiledModelInMemoryTest.cs index 1e82a842374..86bfd2b0e6d 100644 --- a/test/EFCore.InMemory.FunctionalTests/Scaffolding/CompiledModelInMemoryTest.cs +++ b/test/EFCore.InMemory.FunctionalTests/Scaffolding/CompiledModelInMemoryTest.cs @@ -29,7 +29,7 @@ public virtual void Empty_model() }); [ConditionalFact] - public virtual void Global_namespace() + public virtual Task Global_namespace() => Test( modelBuilder => modelBuilder.Entity("1", e => { @@ -43,7 +43,7 @@ public virtual void Global_namespace() options: new CompiledModelCodeGenerationOptions { ModelNamespace = string.Empty }); [ConditionalFact] - public virtual void Self_referential_property() + public virtual Task Self_referential_property() => Test( modelBuilder => modelBuilder.Entity( @@ -318,7 +318,7 @@ public virtual void Custom_type_mapping() }); [ConditionalFact] - public virtual void Fully_qualified_model() + public virtual Task Fully_qualified_model() => Test( modelBuilder => { modelBuilder.Entity(); diff --git a/test/EFCore.InMemory.FunctionalTests/StoreGeneratedFixupInMemoryTest.cs b/test/EFCore.InMemory.FunctionalTests/StoreGeneratedFixupInMemoryTest.cs index 44fc20c43a3..589eeaaf615 100644 --- a/test/EFCore.InMemory.FunctionalTests/StoreGeneratedFixupInMemoryTest.cs +++ b/test/EFCore.InMemory.FunctionalTests/StoreGeneratedFixupInMemoryTest.cs @@ -30,10 +30,10 @@ public void InMemory_database_does_not_use_temp_values() Assert.Equal(tempValue, entry.Property(e => e.Id).CurrentValue); } - protected override void ExecuteWithStrategyInTransaction(Action testOperation) + protected override async Task ExecuteWithStrategyInTransactionAsync(Func testOperation) { - base.ExecuteWithStrategyInTransaction(testOperation); - Fixture.Reseed(); + await base.ExecuteWithStrategyInTransactionAsync(testOperation); + await Fixture.ReseedAsync(); } protected override bool EnforcesFKs diff --git a/test/EFCore.InMemory.FunctionalTests/TestUtilities/InMemoryTestStore.cs b/test/EFCore.InMemory.FunctionalTests/TestUtilities/InMemoryTestStore.cs index f04de97d790..f94fd504c84 100644 --- a/test/EFCore.InMemory.FunctionalTests/TestUtilities/InMemoryTestStore.cs +++ b/test/EFCore.InMemory.FunctionalTests/TestUtilities/InMemoryTestStore.cs @@ -10,26 +10,26 @@ public class InMemoryTestStore(string name = null, bool shared = true) : TestSto public static InMemoryTestStore GetOrCreate(string name) => new(name); - public static InMemoryTestStore GetOrCreateInitialized(string name) - => new InMemoryTestStore(name).InitializeInMemory(null, (Func)null, null); + public static Task GetOrCreateInitializedAsync(string name) + => new InMemoryTestStore(name).InitializeInMemoryAsync(null, (Func)null, null); public static InMemoryTestStore Create(string name) => new(name, shared: false); - public static InMemoryTestStore CreateInitialized(string name) - => new InMemoryTestStore(name, shared: false).InitializeInMemory(null, (Func)null, null); + public static Task CreateInitializedAsync(string name) + => new InMemoryTestStore(name, shared: false).InitializeInMemoryAsync(null, (Func)null, null); - public InMemoryTestStore InitializeInMemory( + public async Task InitializeInMemoryAsync( IServiceProvider serviceProvider, Func createContext, - Action seed) - => (InMemoryTestStore)Initialize(serviceProvider, createContext, seed); + Func seed) + => (InMemoryTestStore)await InitializeAsync(serviceProvider, createContext, seed); - public InMemoryTestStore InitializeInMemory( + public async Task InitializeInMemoryAsync( IServiceProvider serviceProvider, Func createContext, - Action seed) - => (InMemoryTestStore)Initialize(serviceProvider, () => createContext(this), seed); + Func seed) + => (InMemoryTestStore)await InitializeAsync(serviceProvider, () => createContext(this), seed); protected override TestStoreIndex GetTestStoreIndex(IServiceProvider serviceProvider) => serviceProvider == null @@ -39,9 +39,9 @@ protected override TestStoreIndex GetTestStoreIndex(IServiceProvider serviceProv public override DbContextOptionsBuilder AddProviderOptions(DbContextOptionsBuilder builder) => builder.UseInMemoryDatabase(Name); - public override void Clean(DbContext context) + public override Task CleanAsync(DbContext context) { context.GetService().GetStore(Name).Clear(); - context.Database.EnsureCreated(); + return context.Database.EnsureCreatedAsync(); } } diff --git a/test/EFCore.InMemory.FunctionalTests/UpdatesInMemoryTestBase.cs b/test/EFCore.InMemory.FunctionalTests/UpdatesInMemoryTestBase.cs index 86959006207..6867899eab7 100644 --- a/test/EFCore.InMemory.FunctionalTests/UpdatesInMemoryTestBase.cs +++ b/test/EFCore.InMemory.FunctionalTests/UpdatesInMemoryTestBase.cs @@ -17,21 +17,6 @@ protected UpdatesInMemoryTestBase(TFixture fixture) protected override string UpdateConcurrencyMessage => InMemoryStrings.UpdateConcurrencyException; - protected override void ExecuteWithStrategyInTransaction( - Action testOperation, - Action nestedTestOperation1 = null, - Action nestedTestOperation2 = null) - { - try - { - base.ExecuteWithStrategyInTransaction(testOperation, nestedTestOperation1, nestedTestOperation2); - } - finally - { - Fixture.Reseed(); - } - } - protected override async Task ExecuteWithStrategyInTransactionAsync( Func testOperation, Func nestedTestOperation1 = null, @@ -43,7 +28,7 @@ protected override async Task ExecuteWithStrategyInTransactionAsync( } finally { - Fixture.Reseed(); + await Fixture.ReseedAsync(); } } diff --git a/test/EFCore.InMemory.FunctionalTests/WithConstructorsInMemoryTest.cs b/test/EFCore.InMemory.FunctionalTests/WithConstructorsInMemoryTest.cs index 00ce477e1e0..2348328ca8c 100644 --- a/test/EFCore.InMemory.FunctionalTests/WithConstructorsInMemoryTest.cs +++ b/test/EFCore.InMemory.FunctionalTests/WithConstructorsInMemoryTest.cs @@ -3,13 +3,14 @@ namespace Microsoft.EntityFrameworkCore; -public class WithConstructorsInMemoryTest(WithConstructorsInMemoryTest.WithConstructorsInMemoryFixture fixture) : WithConstructorsTestBase(fixture) +public class WithConstructorsInMemoryTest(WithConstructorsInMemoryTest.WithConstructorsInMemoryFixture fixture) + : WithConstructorsTestBase(fixture) { - public override void Query_and_update_using_constructors_with_property_parameters() + public override async Task Query_and_update_using_constructors_with_property_parameters() { - base.Query_and_update_using_constructors_with_property_parameters(); + await base.Query_and_update_using_constructors_with_property_parameters(); - Fixture.Reseed(); + await Fixture.ReseedAsync(); } public class WithConstructorsInMemoryFixture : WithConstructorsFixtureBase diff --git a/test/EFCore.Relational.Specification.Tests/BulkUpdates/NonSharedModelBulkUpdatesTestBase.cs b/test/EFCore.Relational.Specification.Tests/BulkUpdates/NonSharedModelBulkUpdatesTestBase.cs index 8cbbfe624b9..1ff4f844351 100644 --- a/test/EFCore.Relational.Specification.Tests/BulkUpdates/NonSharedModelBulkUpdatesTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/BulkUpdates/NonSharedModelBulkUpdatesTestBase.cs @@ -147,7 +147,7 @@ public virtual async Task Update_non_owned_property_on_entity_with_owned_in_join await AssertUpdate( async, contextFactory.CreateContext, - ss => ss.Set().Join(ss.Set(), o => o.Id, i => i.Id, (o, i) => new { Outer = o, Inner = i}), + ss => ss.Set().Join(ss.Set(), o => o.Id, i => i.Id, (o, i) => new { Outer = o, Inner = i }), s => s.SetProperty(t => t.Outer.Title, "NewValue"), rowsAffectedCount: 0); } @@ -185,10 +185,10 @@ public virtual async Task Update_main_table_in_entity_with_entity_splitting(bool tb.Property(b => b.Title); tb.Property(b => b.Rating); }), - seed: context => + seed: async context => { context.Set().Add(new Blog { Title = "SomeBlog" }); - context.SaveChanges(); + await context.SaveChangesAsync(); }); await AssertUpdate( @@ -212,10 +212,10 @@ public virtual async Task Update_non_main_table_in_entity_with_entity_splitting( tb.Property(b => b.Title); tb.Property(b => b.Rating); }), - seed: context => + seed: async context => { context.Set().Add(new Blog { Title = "SomeBlog" }); - context.SaveChanges(); + await context.SaveChangesAsync(); }); await AssertUpdate( @@ -360,42 +360,26 @@ public class Post #region HelperMethods - public async Task AssertDelete( + public Task AssertDelete( bool async, Func contextCreator, Func> query, int rowsAffectedCount) where TContext : DbContext - { - if (async) - { - await TestHelpers.ExecuteWithStrategyInTransactionAsync( - contextCreator, UseTransaction, - async context => - { - var processedQuery = query(context); - - var result = await processedQuery.ExecuteDeleteAsync(); - - Assert.Equal(rowsAffectedCount, result); - }); - } - else - { - TestHelpers.ExecuteWithStrategyInTransaction( - contextCreator, UseTransaction, - context => - { - var processedQuery = query(context); + => TestHelpers.ExecuteWithStrategyInTransactionAsync( + contextCreator, UseTransaction, + async context => + { + var processedQuery = query(context); - var result = processedQuery.ExecuteDelete(); + var result = async + ? await processedQuery.ExecuteDeleteAsync() + : processedQuery.ExecuteDelete(); - Assert.Equal(rowsAffectedCount, result); - }); - } - } + Assert.Equal(rowsAffectedCount, result); + }); - public async Task AssertUpdate( + public Task AssertUpdate( bool async, Func contextCreator, Func> query, @@ -403,34 +387,18 @@ public async Task AssertUpdate( int rowsAffectedCount) where TResult : class where TContext : DbContext - { - if (async) - { - await TestHelpers.ExecuteWithStrategyInTransactionAsync( - contextCreator, UseTransaction, - async context => - { - var processedQuery = query(context); - - var result = await processedQuery.ExecuteUpdateAsync(setPropertyCalls); - - Assert.Equal(rowsAffectedCount, result); - }); - } - else - { - TestHelpers.ExecuteWithStrategyInTransaction( - contextCreator, UseTransaction, - context => - { - var processedQuery = query(context); + => TestHelpers.ExecuteWithStrategyInTransactionAsync( + contextCreator, UseTransaction, + async context => + { + var processedQuery = query(context); - var result = processedQuery.ExecuteUpdate(setPropertyCalls); + var result = async + ? await processedQuery.ExecuteUpdateAsync(setPropertyCalls) + : processedQuery.ExecuteUpdate(setPropertyCalls); - Assert.Equal(rowsAffectedCount, result); - }); - } - } + Assert.Equal(rowsAffectedCount, result); + }); protected static async Task AssertTranslationFailedWithDetails(Func query, string details) => Assert.Contains( diff --git a/test/EFCore.Relational.Specification.Tests/BulkUpdates/NorthwindBulkUpdatesTestBase.cs b/test/EFCore.Relational.Specification.Tests/BulkUpdates/NorthwindBulkUpdatesTestBase.cs index b986e6fed05..7bf55a39bee 100644 --- a/test/EFCore.Relational.Specification.Tests/BulkUpdates/NorthwindBulkUpdatesTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/BulkUpdates/NorthwindBulkUpdatesTestBase.cs @@ -276,33 +276,27 @@ public virtual Task Delete_non_entity_projection_3(bool async) [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual async Task Delete_FromSql_converted_to_subquery(bool async) - { - if (async) - { - await TestHelpers.ExecuteWithStrategyInTransactionAsync( - () => Fixture.CreateContext(), - (facade, transaction) => Fixture.UseTransaction(facade, transaction), - async context => await context.Set().FromSqlRaw( - NormalizeDelimitersInRawString( - @"SELECT [OrderID], [ProductID], [UnitPrice], [Quantity], [Discount] -FROM [Order Details] -WHERE [OrderID] < 10300")) - .ExecuteDeleteAsync()); - } - else - { - TestHelpers.ExecuteWithStrategyInTransaction( - () => Fixture.CreateContext(), - (facade, transaction) => Fixture.UseTransaction(facade, transaction), - context => context.Set().FromSqlRaw( - NormalizeDelimitersInRawString( - @"SELECT [OrderID], [ProductID], [UnitPrice], [Quantity], [Discount] + public virtual Task Delete_FromSql_converted_to_subquery(bool async) + => TestHelpers.ExecuteWithStrategyInTransactionAsync( + () => Fixture.CreateContext(), + (facade, transaction) => Fixture.UseTransaction(facade, transaction), + async context => + { + var queryable = context.Set().FromSqlRaw( + NormalizeDelimitersInRawString( + @"SELECT [OrderID], [ProductID], [UnitPrice], [Quantity], [Discount] FROM [Order Details] -WHERE [OrderID] < 10300")) - .ExecuteDelete()); - } - } +WHERE [OrderID] < 10300")); + + if (async) + { + await queryable.ExecuteDeleteAsync(); + } + else + { + queryable.ExecuteDelete(); + } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] @@ -981,33 +975,27 @@ from o in ss.Set().Where(o => o.OrderID < 10300 && o.OrderDate.Value.Year [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual async Task Update_FromSql_set_constant(bool async) - { - if (async) - { - await TestHelpers.ExecuteWithStrategyInTransactionAsync( - () => Fixture.CreateContext(), - (facade, transaction) => Fixture.UseTransaction(facade, transaction), - async context => await context.Set().FromSqlRaw( - NormalizeDelimitersInRawString( - @"SELECT [Region], [PostalCode], [Phone], [Fax], [CustomerID], [Country], [ContactTitle], [ContactName], [CompanyName], [City], [Address] -FROM [Customers] -WHERE [CustomerID] LIKE 'A%'")) - .ExecuteUpdateAsync(s => s.SetProperty(c => c.ContactName, "Updated"))); - } - else - { - TestHelpers.ExecuteWithStrategyInTransaction( - () => Fixture.CreateContext(), - (facade, transaction) => Fixture.UseTransaction(facade, transaction), - context => context.Set().FromSqlRaw( - NormalizeDelimitersInRawString( - @"SELECT [Region], [PostalCode], [Phone], [Fax], [CustomerID], [Country], [ContactTitle], [ContactName], [CompanyName], [City], [Address] + public virtual Task Update_FromSql_set_constant(bool async) + => TestHelpers.ExecuteWithStrategyInTransactionAsync( + () => Fixture.CreateContext(), + (facade, transaction) => Fixture.UseTransaction(facade, transaction), + async context => + { + var queryable = context.Set().FromSqlRaw( + NormalizeDelimitersInRawString( + @"SELECT [Region], [PostalCode], [Phone], [Fax], [CustomerID], [Country], [ContactTitle], [ContactName], [CompanyName], [City], [Address] FROM [Customers] -WHERE [CustomerID] LIKE 'A%'")) - .ExecuteUpdate(s => s.SetProperty(c => c.ContactName, "Updated"))); - } - } +WHERE [CustomerID] LIKE 'A%'")); + + if (async) + { + await queryable.ExecuteUpdateAsync(s => s.SetProperty(c => c.ContactName, "Updated")); + } + else + { + queryable.ExecuteUpdate(s => s.SetProperty(c => c.ContactName, "Updated")); + } + }); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] diff --git a/test/EFCore.Relational.Specification.Tests/CommandInterceptionTestBase.cs b/test/EFCore.Relational.Specification.Tests/CommandInterceptionTestBase.cs index dab8001b9a6..3aae8eca49f 100644 --- a/test/EFCore.Relational.Specification.Tests/CommandInterceptionTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/CommandInterceptionTestBase.cs @@ -23,7 +23,7 @@ protected CommandInterceptionTestBase(InterceptionFixtureBase fixture) [InlineData(true, true)] public virtual async Task Intercept_query_passively(bool async, bool inject) { - var (context, interceptor) = CreateContext(inject); + var (context, interceptor) = await CreateContextAsync(inject); using (context) { using var listener = Fixture.SubscribeToDiagnosticListener(context.ContextId); @@ -63,7 +63,7 @@ public PassiveReaderCommandInterceptor() [InlineData(true, true)] public virtual async Task Intercept_scalar_passively(bool async, bool inject) { - var (context, interceptor) = CreateContext(inject); + var (context, interceptor) = await CreateContextAsync(inject); using (context) { const string sql = "SELECT 1"; @@ -104,7 +104,7 @@ public PassiveScalarCommandInterceptor() [InlineData(true, true)] public virtual async Task Intercept_non_query_passively(bool async, bool inject) { - var (context, interceptor) = CreateContext(inject); + var (context, interceptor) = await CreateContextAsync(inject); using (context) { using (context.Database.BeginTransaction()) @@ -143,7 +143,7 @@ public PassiveNonQueryCommandInterceptor() [InlineData(true, true)] public virtual async Task Intercept_query_to_suppress_execution(bool async, bool inject) { - var (context, interceptor) = CreateContext(inject); + var (context, interceptor) = await CreateContextAsync(inject); using (context) { using var listener = Fixture.SubscribeToDiagnosticListener(context.ContextId); @@ -206,7 +206,7 @@ public override async ValueTask> ReaderExecutin [InlineData(true, true)] public virtual async Task Intercept_query_to_suppress_command_creation(bool async, bool inject) { - var (context, interceptor) = CreateContext(inject); + var (context, interceptor) = await CreateContextAsync(inject); using (context) { using var listener = Fixture.SubscribeToDiagnosticListener(context.ContextId); @@ -276,7 +276,7 @@ public override ValueTask> ReaderExecutingAsync [InlineData(true, true)] public virtual async Task Intercept_scalar_to_suppress_execution(bool async, bool inject) { - var (context, interceptor) = CreateContext(inject); + var (context, interceptor) = await CreateContextAsync(inject); using (context) { const string sql = "SELECT 1"; @@ -340,7 +340,7 @@ public override async ValueTask> ScalarExecutingAsync [InlineData(true, true)] public virtual async Task Intercept_non_query_to_suppress_execution(bool async, bool inject) { - var (context, interceptor) = CreateContext(inject); + var (context, interceptor) = await CreateContextAsync(inject); using (context) { using (context.Database.BeginTransaction()) @@ -412,7 +412,7 @@ public virtual Task Intercept_CommandInitialized_to_mutate_query_command protected virtual async Task QueryMutationTest(bool async, bool inject) where TInterceptor : CommandInterceptorBase, new() { - var (context, interceptor) = CreateContext(inject); + var (context, interceptor) = await CreateContextAsync(inject); using (context) { using var listener = Fixture.SubscribeToDiagnosticListener(context.ContextId); @@ -503,7 +503,7 @@ public virtual Task Intercept_CommandInitialized_to_mutate_scalar_command(bool a protected async Task ScalarMutationTest(bool async, bool inject) where TInterceptor : CommandInterceptorBase, new() { - var (context, interceptor) = CreateContext(inject); + var (context, interceptor) = await CreateContextAsync(inject); using (context) { const string sql = "SELECT 1"; @@ -583,7 +583,7 @@ public override DbCommand CommandInitialized(CommandEndEventData eventData, DbCo public virtual async Task Intercept_non_query_to_mutate_command(bool async, bool inject) { var interceptor = new MutatingNonQueryCommandInterceptor(this); - var context = inject ? CreateContext(null, interceptor) : CreateContext(interceptor); + var context = inject ? await CreateContextAsync(null, interceptor) : await CreateContextAsync(interceptor); using (context) { using (context.Database.BeginTransaction()) @@ -607,10 +607,11 @@ public virtual async Task Intercept_non_query_to_mutate_command(bool async, bool } } - protected class MutatingNonQueryCommandInterceptor(CommandInterceptionTestBase testBase) : CommandInterceptorBase(DbCommandMethod.ExecuteNonQuery) + protected class MutatingNonQueryCommandInterceptor(CommandInterceptionTestBase testBase) + : CommandInterceptorBase(DbCommandMethod.ExecuteNonQuery) { public readonly string MutatedSql = - testBase.NormalizeDelimitersInRawString("DELETE FROM [Singularity] WHERE [Id] = 78"); + testBase.NormalizeDelimitersInRawString("DELETE FROM [Singularity] WHERE [Id] = 78"); public override InterceptionResult NonQueryExecuting( DbCommand command, @@ -641,7 +642,7 @@ public override ValueTask> NonQueryExecutingAsync( [InlineData(true, true)] public virtual async Task Intercept_query_to_replace_execution(bool async, bool inject) { - var (context, interceptor) = CreateContext(inject); + var (context, interceptor) = await CreateContextAsync(inject); using (context) { using var listener = Fixture.SubscribeToDiagnosticListener(context.ContextId); @@ -713,7 +714,7 @@ private static DbCommand CreateNewCommand(DbCommand command) [InlineData(true, true)] public virtual async Task Intercept_scalar_to_replace_execution(bool async, bool inject) { - var (context, interceptor) = CreateContext(inject); + var (context, interceptor) = await CreateContextAsync(inject); using (context) { const string sql = "SELECT 1"; @@ -786,7 +787,7 @@ private static DbCommand CreateNewCommand(DbCommand command) public virtual async Task Intercept_non_query_to_replace_execution(bool async, bool inject) { var interceptor = new QueryReplacingNonQueryCommandInterceptor(this); - var context = inject ? CreateContext(null, interceptor) : CreateContext(interceptor); + var context = inject ? await CreateContextAsync(null, interceptor) : await CreateContextAsync(interceptor); using (context) { using (context.Database.BeginTransaction()) @@ -810,7 +811,8 @@ public virtual async Task Intercept_non_query_to_replace_execution(bool async, b } } - protected class QueryReplacingNonQueryCommandInterceptor(CommandInterceptionTestBase testBase) : CommandInterceptorBase(DbCommandMethod.ExecuteNonQuery) + protected class QueryReplacingNonQueryCommandInterceptor(CommandInterceptionTestBase testBase) + : CommandInterceptorBase(DbCommandMethod.ExecuteNonQuery) { private readonly string commandText = testBase.NormalizeDelimitersInRawString("DELETE FROM [Singularity] WHERE [Id] = 77"); @@ -854,7 +856,7 @@ private DbCommand CreateNewCommand(DbCommand command) [InlineData(true, true)] public virtual async Task Intercept_query_to_replace_result(bool async, bool inject) { - var (context, interceptor) = CreateContext(inject); + var (context, interceptor) = await CreateContextAsync(inject); using (context) { using var listener = Fixture.SubscribeToDiagnosticListener(context.ContextId); @@ -998,7 +1000,7 @@ public override string GetString(int ordinal) [InlineData(true, true)] public virtual async Task Intercept_scalar_to_replace_result(bool async, bool inject) { - var (context, interceptor) = CreateContext(inject); + var (context, interceptor) = await CreateContextAsync(inject); using (context) { const string sql = "SELECT 1"; @@ -1062,7 +1064,7 @@ public override async ValueTask ScalarExecutedAsync( [InlineData(true, true)] public virtual async Task Intercept_non_query_to_replace_result(bool async, bool inject) { - var (context, interceptor) = CreateContext(inject); + var (context, interceptor) = await CreateContextAsync(inject); using (context) { using (context.Database.BeginTransaction()) @@ -1124,7 +1126,7 @@ public virtual async Task Intercept_query_that_throws(bool async, bool inject) { var badSql = NormalizeDelimitersInRawString("SELECT * FROM [TheVoid]"); - var (context, interceptor) = CreateContext(inject); + var (context, interceptor) = await CreateContextAsync(inject); using (context) { try @@ -1151,7 +1153,7 @@ public virtual async Task Intercept_query_that_throws(bool async, bool inject) [InlineData(true, true)] public virtual async Task Intercept_scalar_that_throws(bool async, bool inject) { - var (context, interceptor) = CreateContext(inject); + var (context, interceptor) = await CreateContextAsync(inject); using (context) { const string sql = "SELECT Won"; @@ -1188,7 +1190,7 @@ public virtual async Task Intercept_scalar_that_throws(bool async, bool inject) [InlineData(true, true)] public virtual async Task Intercept_non_query_that_throws(bool async, bool inject) { - var (context, interceptor) = CreateContext(inject); + var (context, interceptor) = await CreateContextAsync(inject); using (context) { var nonQuery = NormalizeDelimitersInRawString("DELETE FROM [TheVoid] WHERE [Id] = 555"); @@ -1219,7 +1221,7 @@ public virtual async Task Intercept_non_query_that_throws(bool async, bool injec [InlineData(true, true)] public virtual async Task Intercept_query_to_throw(bool async, bool inject) { - var (context, interceptor) = CreateContext(inject); + var (context, interceptor) = await CreateContextAsync(inject); using (context) { var exception = async @@ -1237,7 +1239,7 @@ public virtual async Task Intercept_query_to_throw(bool async, bool inject) [InlineData(true, true)] public virtual async Task Intercept_scalar_to_throw(bool async, bool inject) { - var (context, interceptor) = CreateContext(inject); + var (context, interceptor) = await CreateContextAsync(inject); using (context) { var command = context.GetService().Create().Append("SELECT 1").Build(); @@ -1261,7 +1263,7 @@ public virtual async Task Intercept_scalar_to_throw(bool async, bool inject) [InlineData(true, true)] public virtual async Task Intercept_non_query_to_throw(bool async, bool inject) { - var (context, interceptor) = CreateContext(inject); + var (context, interceptor) = await CreateContextAsync(inject); using (context) { using (context.Database.BeginTransaction()) @@ -1327,7 +1329,7 @@ public virtual async Task Intercept_query_with_one_app_and_one_injected_intercep { var appInterceptor = new ResultReplacingReaderCommandInterceptor(); var injectedInterceptor = new MutatingReaderCommandInterceptor(); - using var context = CreateContext(appInterceptor, injectedInterceptor); + using var context = await CreateContextAsync(appInterceptor, injectedInterceptor); await TestCompoisteQueryInterceptors(context, appInterceptor, injectedInterceptor, async); } @@ -1352,7 +1354,7 @@ private static async Task TestCompoisteQueryInterceptors( [InlineData(true)] public virtual async Task Intercept_scalar_with_one_app_and_one_injected_interceptor(bool async) { - using var context = CreateContext( + using var context = await CreateContextAsync( new ResultReplacingScalarCommandInterceptor(), new MutatingScalarCommandInterceptor()); await TestCompositeScalarInterceptors(context, async); @@ -1378,7 +1380,7 @@ private static async Task TestCompositeScalarInterceptors(UniverseContext contex [InlineData(true)] public virtual async Task Intercept_non_query_one_app_and_one_injected_interceptor(bool async) { - using var context = CreateContext( + using var context = await CreateContextAsync( new ResultReplacingNonQueryCommandInterceptor(), new MutatingNonQueryCommandInterceptor(this)); await TestCompositeNonQueryInterceptors(context, async); @@ -1407,7 +1409,7 @@ public virtual async Task Intercept_query_with_two_injected_interceptors(bool as var injectedInterceptor1 = new MutatingReaderCommandInterceptor(); var injectedInterceptor2 = new ResultReplacingReaderCommandInterceptor(); - using var context = CreateContext(null, injectedInterceptor1, injectedInterceptor2); + using var context = await CreateContextAsync(null, injectedInterceptor1, injectedInterceptor2); await TestCompoisteQueryInterceptors(context, injectedInterceptor2, injectedInterceptor1, async); } @@ -1416,7 +1418,7 @@ public virtual async Task Intercept_query_with_two_injected_interceptors(bool as [InlineData(true)] public virtual async Task Intercept_scalar_with_two_injected_interceptors(bool async) { - using var context = CreateContext( + using var context = await CreateContextAsync( null, new MutatingScalarCommandInterceptor(), new ResultReplacingScalarCommandInterceptor()); await TestCompositeScalarInterceptors(context, async); @@ -1427,7 +1429,7 @@ public virtual async Task Intercept_scalar_with_two_injected_interceptors(bool a [InlineData(true)] public virtual async Task Intercept_non_query_with_two_injected_interceptors(bool async) { - using var context = CreateContext( + using var context = await CreateContextAsync( null, new MutatingNonQueryCommandInterceptor(this), new ResultReplacingNonQueryCommandInterceptor()); await TestCompositeNonQueryInterceptors(context, async); @@ -1438,7 +1440,7 @@ public virtual async Task Intercept_non_query_with_two_injected_interceptors(boo [InlineData(true)] public virtual async Task Intercept_query_with_explicitly_composed_app_interceptor(bool async) { - using var context = CreateContext( + using var context = await CreateContextAsync( new IInterceptor[] { new MutatingReaderCommandInterceptor(), new ResultReplacingReaderCommandInterceptor() }); var results = async ? await context.Set().ToListAsync() @@ -1467,7 +1469,7 @@ private static void AssertCompositeResults(List results) [InlineData(true)] public virtual async Task Intercept_scalar_with_explicitly_composed_app_interceptor(bool async) { - using var context = CreateContext( + using var context = await CreateContextAsync( new IInterceptor[] { new MutatingScalarCommandInterceptor(), new ResultReplacingScalarCommandInterceptor() }); await TestCompositeScalarInterceptors(context, async); } @@ -1477,7 +1479,7 @@ public virtual async Task Intercept_scalar_with_explicitly_composed_app_intercep [InlineData(true)] public virtual async Task Intercept_non_query_with_explicitly_composed_app_interceptor(bool async) { - using var context = CreateContext( + using var context = await CreateContextAsync( new IInterceptor[] { new MutatingNonQueryCommandInterceptor(this), new ResultReplacingNonQueryCommandInterceptor() }); await TestCompositeNonQueryInterceptors(context, async); } @@ -1489,7 +1491,7 @@ public virtual async Task Intercept_non_query_with_explicitly_composed_app_inter [InlineData(true, true)] public virtual async Task Intercept_query_to_call_DataReader_NextResult(bool async, bool inject) { - var (context, interceptor) = CreateContext(inject); + var (context, interceptor) = await CreateContextAsync(inject); using (context) { using var listener = Fixture.SubscribeToDiagnosticListener(context.ContextId); @@ -1543,7 +1545,7 @@ public override async ValueTask DataReaderClosingAsync( [InlineData(true, true)] public virtual async Task Intercept_query_to_suppress_close_of_reader(bool async, bool inject) { - var (context, interceptor) = CreateContext(inject); + var (context, interceptor) = await CreateContextAsync(inject); using (context) { using var listener = Fixture.SubscribeToDiagnosticListener(context.ContextId); diff --git a/test/EFCore.Relational.Specification.Tests/ConnectionInterceptionTestBase.cs b/test/EFCore.Relational.Specification.Tests/ConnectionInterceptionTestBase.cs index 898812eeb38..c395cb132d6 100644 --- a/test/EFCore.Relational.Specification.Tests/ConnectionInterceptionTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/ConnectionInterceptionTestBase.cs @@ -17,7 +17,7 @@ protected ConnectionInterceptionTestBase(InterceptionFixtureBase fixture) [InlineData(true)] public virtual async Task Intercept_connection_passively(bool async) { - var (context, interceptor) = CreateContext(); + var (context, interceptor) = await CreateContextAsync(); using (context) { // Test infrastructure uses an open connection, so close it first. @@ -69,7 +69,7 @@ public virtual async Task Intercept_connection_passively(bool async) [InlineData(true)] public virtual async Task Intercept_connection_to_override_opening(bool async) { - var (context, interceptor) = CreateContext(); + var (context, interceptor) = await CreateContextAsync(); using (context) { // Test infrastructure uses an open connection, so close it first. @@ -125,7 +125,7 @@ public virtual async Task Intercept_connection_with_multiple_interceptors(bool a var interceptor2 = new ConnectionOverridingInterceptor(); var interceptor3 = new ConnectionInterceptor(); var interceptor4 = new ConnectionOverridingInterceptor(); - using var context = CreateContext( + using var context = await CreateContextAsync( new IInterceptor[] { new NoOpConnectionInterceptor(), interceptor1, interceptor2 }, new IInterceptor[] { interceptor3, interceptor4, new NoOpConnectionInterceptor() }); // Test infrastructure uses an open connection, so close it first. diff --git a/test/EFCore.Relational.Specification.Tests/DataAnnotationRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/DataAnnotationRelationalTestBase.cs index f1f9019d1b7..c9151cf4a11 100644 --- a/test/EFCore.Relational.Specification.Tests/DataAnnotationRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/DataAnnotationRelationalTestBase.cs @@ -65,33 +65,33 @@ public class Profile16 } [ConditionalFact] - public virtual void Table_can_configure_TPT_with_Owned() - => ExecuteWithStrategyInTransaction( + public virtual Task Table_can_configure_TPT_with_Owned() + => ExecuteWithStrategyInTransactionAsync( context => { var model = context.Model; - var animalType = model.FindEntityType(typeof(Animal)); + var animalType = model.FindEntityType(typeof(Animal))!; Assert.Equal("Animals", animalType.GetTableMappings().Single().Table.Name); - var petType = model.FindEntityType(typeof(Pet)); + var petType = model.FindEntityType(typeof(Pet))!; Assert.Equal("Pets", petType.GetTableMappings().Last().Table.Name); - var tagNavigation = petType.FindNavigation(nameof(Pet.Tag)); + var tagNavigation = petType.FindNavigation(nameof(Pet.Tag))!; var ownership = tagNavigation.ForeignKey; Assert.True(ownership.IsRequiredDependent); var petTagType = ownership.DeclaringEntityType; Assert.Equal("Pets", petTagType.GetTableMappings().Single().Table.Name); - var tagIdProperty = petTagType.FindProperty(nameof(PetTag.TagId)); + var tagIdProperty = petTagType.FindProperty(nameof(PetTag.TagId))!; Assert.False(tagIdProperty.IsNullable); Assert.All(tagIdProperty.GetTableColumnMappings(), m => Assert.False(m.Column.IsNullable)); - var catType = model.FindEntityType(typeof(Cat)); + var catType = model.FindEntityType(typeof(Cat))!; Assert.Equal("Cats", catType.GetTableMappings().Last().Table.Name); - var dogType = model.FindEntityType(typeof(Dog)); + var dogType = model.FindEntityType(typeof(Dog))!; Assert.Equal("Dogs", dogType.GetTableMappings().Last().Table.Name); var petFood = new PetFood { FoodName = "Fish" }; @@ -105,11 +105,10 @@ public virtual void Table_can_configure_TPT_with_Owned() FavoritePetFood = petFood }); - context.SaveChanges(); - }, - context => + return context.SaveChangesAsync(); + }, async context => { - var cat = context.Set().Single(); + var cat = await context.Set().SingleAsync(); Assert.Equal("Felis catus", cat.Species); Assert.Equal(2u, cat.Tag.TagId); }); diff --git a/test/EFCore.Relational.Specification.Tests/EntitySplittingTestBase.cs b/test/EFCore.Relational.Specification.Tests/EntitySplittingTestBase.cs index 310c793dbf4..2303856c50e 100644 --- a/test/EFCore.Relational.Specification.Tests/EntitySplittingTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/EntitySplittingTestBase.cs @@ -47,26 +47,24 @@ public virtual async Task ExecuteDelete_throws_for_entity_splitting(bool async) { await InitializeAsync(OnModelCreating, sensitiveLogEnabled: true); - if (async) - { - await TestHelpers.ExecuteWithStrategyInTransactionAsync( - CreateContext, - UseTransaction, - async context => Assert.Contains( - RelationalStrings.NonQueryTranslationFailedWithDetails( - "", RelationalStrings.ExecuteOperationOnEntitySplitting("ExecuteDelete", "MeterReading"))[21..], - (await Assert.ThrowsAsync(() => context.MeterReadings.ExecuteDeleteAsync())).Message)); - } - else - { - TestHelpers.ExecuteWithStrategyInTransaction( - CreateContext, - UseTransaction, - context => Assert.Contains( - RelationalStrings.NonQueryTranslationFailedWithDetails( - "", RelationalStrings.ExecuteOperationOnEntitySplitting("ExecuteDelete", "MeterReading"))[21..], - Assert.Throws(() => context.MeterReadings.ExecuteDelete()).Message)); - } + await TestHelpers.ExecuteWithStrategyInTransactionAsync( + CreateContext, + UseTransaction, + async context => Assert.Contains( + RelationalStrings.NonQueryTranslationFailedWithDetails( + "", RelationalStrings.ExecuteOperationOnEntitySplitting("ExecuteDelete", "MeterReading"))[21..], + (await Assert.ThrowsAsync( + async () => + { + if (async) + { + await context.MeterReadings.ExecuteDeleteAsync(); + } + else + { + context.MeterReadings.ExecuteDelete(); + } + })).Message)); } // See additional tests bulk update tests in NonSharedModelBulkUpdatesTestBase @@ -100,8 +98,8 @@ protected virtual void OnModelCreating(ModelBuilder modelBuilder) protected async Task InitializeAsync( Action onModelCreating, - Action onConfiguring = null, - Action seed = null, + Func onConfiguring = null, + Func seed = null, bool sensitiveLogEnabled = true) => ContextFactory = await InitializeAsync( onModelCreating, @@ -119,9 +117,9 @@ protected async Task InitializeAsync( protected virtual EntitySplittingContext CreateContext() => ContextFactory.CreateContext(); - public override void Dispose() + public override async Task DisposeAsync() { - base.Dispose(); + await base.DisposeAsync(); ContextFactory = null; } diff --git a/test/EFCore.Relational.Specification.Tests/JsonTypesRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/JsonTypesRelationalTestBase.cs index 26fe7efcf50..d3b76f5c073 100644 --- a/test/EFCore.Relational.Specification.Tests/JsonTypesRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/JsonTypesRelationalTestBase.cs @@ -9,7 +9,7 @@ public abstract class JsonTypesRelationalTestBase : JsonTypesTestBase { [ConditionalTheory] [InlineData(null)] - public virtual void Can_read_write_collection_of_fixed_length_string_JSON_values(object? storeType) + public virtual Task Can_read_write_collection_of_fixed_length_string_JSON_values(object? storeType) => Can_read_and_write_JSON_collection_value>( b => b.ElementType().IsFixedLength().HasMaxLength(32), nameof(StringCollectionType.String), @@ -28,7 +28,7 @@ public virtual void Can_read_write_collection_of_fixed_length_string_JSON_values [ConditionalTheory] [InlineData(null)] - public virtual void Can_read_write_collection_of_ASCII_string_JSON_values(object? storeType) + public virtual Task Can_read_write_collection_of_ASCII_string_JSON_values(object? storeType) => Can_read_and_write_JSON_collection_value>( b => b.ElementType().IsUnicode(false), nameof(StringCollectionType.String), diff --git a/test/EFCore.Relational.Specification.Tests/Migrations/MigrationsTestBase.cs b/test/EFCore.Relational.Specification.Tests/Migrations/MigrationsTestBase.cs index bfffec65ac1..3989e70a61e 100644 --- a/test/EFCore.Relational.Specification.Tests/Migrations/MigrationsTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Migrations/MigrationsTestBase.cs @@ -2410,42 +2410,42 @@ public virtual Task Create_sequence_short() [ConditionalFact] public virtual Task Create_sequence_nocache() - => Test( - builder => { }, - builder => builder.HasSequence("Alpha").UseNoCache(), - model => - { - var sequence = Assert.Single(model.Sequences); - Assert.Equal("Alpha", sequence.Name); - Assert.False(sequence.IsCached); - }); + => Test( + builder => { }, + builder => builder.HasSequence("Alpha").UseNoCache(), + model => + { + var sequence = Assert.Single(model.Sequences); + Assert.Equal("Alpha", sequence.Name); + Assert.False(sequence.IsCached); + }); [ConditionalFact] public virtual Task Create_sequence_cache() - => Test( - builder => { }, - builder => builder.HasSequence("Beta").UseCache(20), - model => - { - var sequence = Assert.Single(model.Sequences); - Assert.Equal("Beta", sequence.Name); - Assert.True(sequence.IsCached); - Assert.Equal(20, sequence.CacheSize); - }); + => Test( + builder => { }, + builder => builder.HasSequence("Beta").UseCache(20), + model => + { + var sequence = Assert.Single(model.Sequences); + Assert.Equal("Beta", sequence.Name); + Assert.True(sequence.IsCached); + Assert.Equal(20, sequence.CacheSize); + }); [ConditionalFact] public virtual Task Create_sequence_default_cache() - => Test( - builder => { }, - builder => builder.HasSequence("Gamma").UseCache(), - model => - { - var sequence = Assert.Single(model.Sequences); - Assert.Equal("Gamma", sequence.Name); - Assert.True(sequence.IsCached); - Assert.Null(sequence.CacheSize); - }); + => Test( + builder => { }, + builder => builder.HasSequence("Gamma").UseCache(), + model => + { + var sequence = Assert.Single(model.Sequences); + Assert.Equal("Gamma", sequence.Name); + Assert.True(sequence.IsCached); + Assert.Null(sequence.CacheSize); + }); [ConditionalFact] public virtual Task Create_sequence_all_settings() @@ -2510,43 +2510,43 @@ public virtual Task Alter_sequence_increment_by() [ConditionalFact] public virtual Task Alter_sequence_default_cache_to_cache() - => Test( - builder => builder.HasSequence("Delta").UseCache(), - builder => { }, - builder => builder.HasSequence("Delta").UseCache(20), - model => - { - var sequence = Assert.Single(model.Sequences); - Assert.True(sequence.IsCached); - Assert.Equal(20, sequence.CacheSize); - }); + => Test( + builder => builder.HasSequence("Delta").UseCache(), + builder => { }, + builder => builder.HasSequence("Delta").UseCache(20), + model => + { + var sequence = Assert.Single(model.Sequences); + Assert.True(sequence.IsCached); + Assert.Equal(20, sequence.CacheSize); + }); [ConditionalFact] public virtual Task Alter_sequence_default_cache_to_nocache() - => Test( - builder => builder.HasSequence("Epsilon").UseCache(), - builder => { }, - builder => builder.HasSequence("Epsilon").UseNoCache(), - model => - { - var sequence = Assert.Single(model.Sequences); - Assert.False(sequence.IsCached); - Assert.Null(sequence.CacheSize); - }); + => Test( + builder => builder.HasSequence("Epsilon").UseCache(), + builder => { }, + builder => builder.HasSequence("Epsilon").UseNoCache(), + model => + { + var sequence = Assert.Single(model.Sequences); + Assert.False(sequence.IsCached); + Assert.Null(sequence.CacheSize); + }); [ConditionalFact] public virtual Task Alter_sequence_cache_to_nocache() - => Test( - builder => builder.HasSequence("Zeta").UseCache(20), - builder => { }, - builder => builder.HasSequence("Zeta").UseNoCache(), - model => - { - var sequence = Assert.Single(model.Sequences); - Assert.False(sequence.IsCached); - Assert.Null(sequence.CacheSize); - }); + => Test( + builder => builder.HasSequence("Zeta").UseCache(20), + builder => { }, + builder => builder.HasSequence("Zeta").UseNoCache(), + model => + { + var sequence = Assert.Single(model.Sequences); + Assert.False(sequence.IsCached); + Assert.Null(sequence.CacheSize); + }); [ConditionalFact] public virtual Task Alter_sequence_cache_to_default_cache() @@ -2813,10 +2813,11 @@ public virtual Task Create_table_with_complex_type_with_required_properties_on_d { e.HasBaseType("Contact"); e.Property("Number"); - e.ComplexProperty("MyComplex", ct => - { - ct.ComplexProperty("MyNestedComplex").IsRequired(); - }); + e.ComplexProperty( + "MyComplex", ct => + { + ct.ComplexProperty("MyNestedComplex").IsRequired(); + }); }); }, model => @@ -2862,36 +2863,36 @@ public class MyNestedComplex [ConditionalFact] public virtual Task Add_required_primitive_collection_to_existing_table() - => Test( - builder => builder.Entity( - "Customer", e => - { - e.Property("Id").ValueGeneratedOnAdd(); - e.HasKey("Id"); - e.Property("Name"); - e.ToTable("Customers"); - }), - builder => builder.Entity( - "Customer", e => - { - e.Property("Id").ValueGeneratedOnAdd(); - e.HasKey("Id"); - e.Property("Name"); - e.Property>("Numbers").IsRequired(); - e.ToTable("Customers"); - }), - model => - { - var customersTable = Assert.Single(model.Tables.Where(t => t.Name == "Customers")); - Assert.Collection( - customersTable.Columns, - c => Assert.Equal("Id", c.Name), - c => Assert.Equal("Name", c.Name), - c => Assert.Equal("Numbers", c.Name)); - Assert.Same( - customersTable.Columns.Single(c => c.Name == "Id"), - Assert.Single(customersTable.PrimaryKey!.Columns)); - }); + => Test( + builder => builder.Entity( + "Customer", e => + { + e.Property("Id").ValueGeneratedOnAdd(); + e.HasKey("Id"); + e.Property("Name"); + e.ToTable("Customers"); + }), + builder => builder.Entity( + "Customer", e => + { + e.Property("Id").ValueGeneratedOnAdd(); + e.HasKey("Id"); + e.Property("Name"); + e.Property>("Numbers").IsRequired(); + e.ToTable("Customers"); + }), + model => + { + var customersTable = Assert.Single(model.Tables.Where(t => t.Name == "Customers")); + Assert.Collection( + customersTable.Columns, + c => Assert.Equal("Id", c.Name), + c => Assert.Equal("Name", c.Name), + c => Assert.Equal("Numbers", c.Name)); + Assert.Same( + customersTable.Columns.Single(c => c.Name == "Id"), + Assert.Single(customersTable.PrimaryKey!.Columns)); + }); [ConditionalFact] public virtual Task Add_required_primitive_collection_with_custom_default_value_to_existing_table() @@ -2905,14 +2906,20 @@ public virtual Task Add_required_primitive_collection_with_custom_default_value_ e.ToTable("Customers"); }), builder => builder.Entity( - "Customer", e => - { - e.Property("Id").ValueGeneratedOnAdd(); - e.HasKey("Id"); - e.Property("Name"); - e.Property>("Numbers").IsRequired().HasDefaultValue(new List { 1, 2, 3 }); - e.ToTable("Customers"); - }), + "Customer", e => + { + e.Property("Id").ValueGeneratedOnAdd(); + e.HasKey("Id"); + e.Property("Name"); + e.Property>("Numbers").IsRequired().HasDefaultValue( + new List + { + 1, + 2, + 3 + }); + e.ToTable("Customers"); + }), model => { var customersTable = Assert.Single(model.Tables.Where(t => t.Name == "Customers")); @@ -2940,14 +2947,14 @@ protected virtual Task Add_required_primitive_collection_with_custom_default_val e.ToTable("Customers"); }), builder => builder.Entity( - "Customer", e => - { - e.Property("Id").ValueGeneratedOnAdd(); - e.HasKey("Id"); - e.Property("Name"); - e.Property>("Numbers").IsRequired().HasDefaultValueSql(defaultValueSql); - e.ToTable("Customers"); - }), + "Customer", e => + { + e.Property("Id").ValueGeneratedOnAdd(); + e.HasKey("Id"); + e.Property("Name"); + e.Property>("Numbers").IsRequired().HasDefaultValueSql(defaultValueSql); + e.ToTable("Customers"); + }), model => { var customersTable = Assert.Single(model.Tables.Where(t => t.Name == "Customers")); @@ -2973,17 +2980,25 @@ public virtual Task Add_required_primitive_collection_with_custom_converter_to_e e.ToTable("Customers"); }), builder => builder.Entity( - "Customer", e => - { - e.Property("Id").ValueGeneratedOnAdd(); - e.HasKey("Id"); - e.Property("Name"); - e.Property>("Numbers").HasConversion(new ValueConverter, string>( - convertToProviderExpression: x => x != null && x.Count > 0 ? "some numbers" : "nothing", - convertFromProviderExpression: x => x == "nothing" ? new List { } : new List { 7, 8, 9 })) + "Customer", e => + { + e.Property("Id").ValueGeneratedOnAdd(); + e.HasKey("Id"); + e.Property("Name"); + e.Property>("Numbers").HasConversion( + new ValueConverter, string>( + convertToProviderExpression: x => x != null && x.Count > 0 ? "some numbers" : "nothing", + convertFromProviderExpression: x => x == "nothing" + ? new List { } + : new List + { + 7, + 8, + 9 + })) .IsRequired(); - e.ToTable("Customers"); - }), + e.ToTable("Customers"); + }), model => { var customersTable = Assert.Single(model.Tables.Where(t => t.Name == "Customers")); @@ -3009,18 +3024,26 @@ public virtual Task Add_required_primitive_collection_with_custom_converter_and_ e.ToTable("Customers"); }), builder => builder.Entity( - "Customer", e => - { - e.Property("Id").ValueGeneratedOnAdd(); - e.HasKey("Id"); - e.Property("Name"); - e.Property>("Numbers").HasConversion(new ValueConverter, string>( - convertToProviderExpression: x => x != null && x.Count > 0 ? "some numbers" : "nothing", - convertFromProviderExpression: x => x == "nothing" ? new List { } : new List { 7, 8, 9 })) + "Customer", e => + { + e.Property("Id").ValueGeneratedOnAdd(); + e.HasKey("Id"); + e.Property("Name"); + e.Property>("Numbers").HasConversion( + new ValueConverter, string>( + convertToProviderExpression: x => x != null && x.Count > 0 ? "some numbers" : "nothing", + convertFromProviderExpression: x => x == "nothing" + ? new List { } + : new List + { + 7, + 8, + 9 + })) .HasDefaultValue(new List { 42 }) .IsRequired(); - e.ToTable("Customers"); - }), + e.ToTable("Customers"); + }), model => { var customersTable = Assert.Single(model.Tables.Where(t => t.Name == "Customers")); @@ -3046,14 +3069,14 @@ public virtual Task Add_optional_primitive_collection_to_existing_table() e.ToTable("Customers"); }), builder => builder.Entity( - "Customer", e => - { - e.Property("Id").ValueGeneratedOnAdd(); - e.HasKey("Id"); - e.Property("Name"); - e.Property>("Numbers"); - e.ToTable("Customers"); - }), + "Customer", e => + { + e.Property("Id").ValueGeneratedOnAdd(); + e.HasKey("Id"); + e.Property("Name"); + e.Property>("Numbers"); + e.ToTable("Customers"); + }), model => { var customersTable = Assert.Single(model.Tables.Where(t => t.Name == "Customers")); @@ -3072,14 +3095,14 @@ public virtual Task Create_table_with_required_primitive_collection() => Test( builder => { }, builder => builder.Entity( - "Customer", e => - { - e.Property("Id").ValueGeneratedOnAdd(); - e.HasKey("Id"); - e.Property("Name"); - e.Property>("Numbers").IsRequired(); - e.ToTable("Customers"); - }), + "Customer", e => + { + e.Property("Id").ValueGeneratedOnAdd(); + e.HasKey("Id"); + e.Property("Name"); + e.Property>("Numbers").IsRequired(); + e.ToTable("Customers"); + }), model => { var customersTable = Assert.Single(model.Tables.Where(t => t.Name == "Customers")); @@ -3098,14 +3121,14 @@ public virtual Task Create_table_with_optional_primitive_collection() => Test( builder => { }, builder => builder.Entity( - "Customer", e => - { - e.Property("Id").ValueGeneratedOnAdd(); - e.HasKey("Id"); - e.Property("Name"); - e.Property>("Numbers"); - e.ToTable("Customers"); - }), + "Customer", e => + { + e.Property("Id").ValueGeneratedOnAdd(); + e.HasKey("Id"); + e.Property("Name"); + e.Property>("Numbers"); + e.ToTable("Customers"); + }), model => { var customersTable = Assert.Single(model.Tables.Where(t => t.Name == "Customers")); @@ -3131,14 +3154,14 @@ public virtual Task Add_required_primitve_collection_to_existing_table() e.ToTable("Customers"); }), builder => builder.Entity( - "Customer", e => - { - e.Property("Id").ValueGeneratedOnAdd(); - e.HasKey("Id"); - e.Property("Name"); - e.Property>("Numbers").IsRequired(); - e.ToTable("Customers"); - }), + "Customer", e => + { + e.Property("Id").ValueGeneratedOnAdd(); + e.HasKey("Id"); + e.Property("Name"); + e.Property>("Numbers").IsRequired(); + e.ToTable("Customers"); + }), model => { var customersTable = Assert.Single(model.Tables.Where(t => t.Name == "Customers")); @@ -3164,14 +3187,20 @@ public virtual Task Add_required_primitve_collection_with_custom_default_value_t e.ToTable("Customers"); }), builder => builder.Entity( - "Customer", e => - { - e.Property("Id").ValueGeneratedOnAdd(); - e.HasKey("Id"); - e.Property("Name"); - e.Property>("Numbers").IsRequired().HasDefaultValue(new List { 1, 2, 3 }); - e.ToTable("Customers"); - }), + "Customer", e => + { + e.Property("Id").ValueGeneratedOnAdd(); + e.HasKey("Id"); + e.Property("Name"); + e.Property>("Numbers").IsRequired().HasDefaultValue( + new List + { + 1, + 2, + 3 + }); + e.ToTable("Customers"); + }), model => { var customersTable = Assert.Single(model.Tables.Where(t => t.Name == "Customers")); @@ -3199,14 +3228,14 @@ protected virtual Task Add_required_primitve_collection_with_custom_default_valu e.ToTable("Customers"); }), builder => builder.Entity( - "Customer", e => - { - e.Property("Id").ValueGeneratedOnAdd(); - e.HasKey("Id"); - e.Property("Name"); - e.Property>("Numbers").IsRequired().HasDefaultValueSql(defaultValueSql); - e.ToTable("Customers"); - }), + "Customer", e => + { + e.Property("Id").ValueGeneratedOnAdd(); + e.HasKey("Id"); + e.Property("Name"); + e.Property>("Numbers").IsRequired().HasDefaultValueSql(defaultValueSql); + e.ToTable("Customers"); + }), model => { var customersTable = Assert.Single(model.Tables.Where(t => t.Name == "Customers")); @@ -3232,17 +3261,25 @@ public virtual Task Add_required_primitve_collection_with_custom_converter_to_ex e.ToTable("Customers"); }), builder => builder.Entity( - "Customer", e => - { - e.Property("Id").ValueGeneratedOnAdd(); - e.HasKey("Id"); - e.Property("Name"); - e.Property>("Numbers").HasConversion(new ValueConverter, string>( - convertToProviderExpression: x => x != null && x.Count > 0 ? "some numbers" : "nothing", - convertFromProviderExpression: x => x == "nothing" ? new List { } : new List { 7, 8, 9 })) + "Customer", e => + { + e.Property("Id").ValueGeneratedOnAdd(); + e.HasKey("Id"); + e.Property("Name"); + e.Property>("Numbers").HasConversion( + new ValueConverter, string>( + convertToProviderExpression: x => x != null && x.Count > 0 ? "some numbers" : "nothing", + convertFromProviderExpression: x => x == "nothing" + ? new List { } + : new List + { + 7, + 8, + 9 + })) .IsRequired(); - e.ToTable("Customers"); - }), + e.ToTable("Customers"); + }), model => { var customersTable = Assert.Single(model.Tables.Where(t => t.Name == "Customers")); @@ -3268,18 +3305,26 @@ public virtual Task Add_required_primitve_collection_with_custom_converter_and_c e.ToTable("Customers"); }), builder => builder.Entity( - "Customer", e => - { - e.Property("Id").ValueGeneratedOnAdd(); - e.HasKey("Id"); - e.Property("Name"); - e.Property>("Numbers").HasConversion(new ValueConverter, string>( - convertToProviderExpression: x => x != null && x.Count > 0 ? "some numbers" : "nothing", - convertFromProviderExpression: x => x == "nothing" ? new List { } : new List { 7, 8, 9 })) + "Customer", e => + { + e.Property("Id").ValueGeneratedOnAdd(); + e.HasKey("Id"); + e.Property("Name"); + e.Property>("Numbers").HasConversion( + new ValueConverter, string>( + convertToProviderExpression: x => x != null && x.Count > 0 ? "some numbers" : "nothing", + convertFromProviderExpression: x => x == "nothing" + ? new List { } + : new List + { + 7, + 8, + 9 + })) .HasDefaultValue(new List { 42 }) .IsRequired(); - e.ToTable("Customers"); - }), + e.ToTable("Customers"); + }), model => { var customersTable = Assert.Single(model.Tables.Where(t => t.Name == "Customers")); @@ -3461,7 +3506,7 @@ await migrationsCommandExecutor.ExecuteNonQueryAsync( finally { using var _ = Fixture.TestSqlLoggerFactory.SuspendRecordingEvents(); - Fixture.TestStore.Clean(context); + await Fixture.TestStore.CleanAsync(context); } } diff --git a/test/EFCore.Relational.Specification.Tests/Query/AdHocAdvancedMappingsQueryRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/AdHocAdvancedMappingsQueryRelationalTestBase.cs index 039f3d2265e..79a4d7cf64c 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/AdHocAdvancedMappingsQueryRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/AdHocAdvancedMappingsQueryRelationalTestBase.cs @@ -21,7 +21,7 @@ protected void AssertSql(params string[] expected) [ConditionalFact] public virtual async Task Two_similar_complex_properties_projected_with_split_query1() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var query = context.Offers @@ -41,7 +41,7 @@ public virtual async Task Two_similar_complex_properties_projected_with_split_qu [ConditionalFact] public virtual async Task Two_similar_complex_properties_projected_with_split_query2() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var query = context.Offers @@ -60,7 +60,7 @@ public virtual async Task Two_similar_complex_properties_projected_with_split_qu [ConditionalFact] public virtual async Task Projecting_one_of_two_similar_complex_types_picks_the_correct_one() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); @@ -68,11 +68,11 @@ public virtual async Task Projecting_one_of_two_similar_complex_types_picks_the_ .Where(x => x.B.AId.Value == 1) .OrderBy(x => x.Id) .Take(10) - .Select(x => new - { - x.B.A.Id, - x.B.Info.Created, - }).ToList(); + .Select( + x => new + { + x.B.A.Id, x.B.Info.Created, + }).ToList(); Assert.Equal(new DateTime(2000, 1, 1), query[0].Created); } @@ -85,59 +85,59 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity().Property(x => x.Id).ValueGeneratedNever(); modelBuilder.Entity().Property(x => x.Id).ValueGeneratedNever(); - modelBuilder.Entity().ComplexProperty(x => x.Payment, cpb => - { - cpb.IsRequired(); - cpb.Property(p => p.Netto).HasColumnName("payment_netto"); - cpb.Property(p => p.Brutto).HasColumnName("payment_brutto"); - }); + modelBuilder.Entity().ComplexProperty( + x => x.Payment, cpb => + { + cpb.IsRequired(); + cpb.Property(p => p.Netto).HasColumnName("payment_netto"); + cpb.Property(p => p.Brutto).HasColumnName("payment_brutto"); + }); modelBuilder.Entity().Property(x => x.Id).ValueGeneratedNever(); - modelBuilder.Entity().ComplexProperty(x => x.Payment, cpb => - { - cpb.IsRequired(); - cpb.Property(p => p.Netto).HasColumnName("payment_netto"); - cpb.Property(p => p.Brutto).HasColumnName("payment_brutto"); - }); + modelBuilder.Entity().ComplexProperty( + x => x.Payment, cpb => + { + cpb.IsRequired(); + cpb.Property(p => p.Netto).HasColumnName("payment_netto"); + cpb.Property(p => p.Brutto).HasColumnName("payment_brutto"); + }); } - public void Seed() + public async Task SeedAsync() { var v1 = new Variation { Id = 1, Payment = new Payment(1, 10), - Nested = new NestedEntity - { - Id = 1, - Payment = new Payment(10, 100) - } + Nested = new NestedEntity { Id = 1, Payment = new Payment(10, 100) } }; var v2 = new Variation { Id = 2, Payment = new Payment(2, 20), - Nested = new NestedEntity - { - Id = 2, - Payment = new Payment(20, 200) - } + Nested = new NestedEntity { Id = 2, Payment = new Payment(20, 200) } }; var v3 = new Variation { Id = 3, Payment = new Payment(3, 30), - Nested = new NestedEntity - { - Id = 3, - Payment = new Payment(30, 300) - } + Nested = new NestedEntity { Id = 3, Payment = new Payment(30, 300) } }; - Offers.Add(new Offer { Id = 1, Variations = new List { v1, v2, v3 } }); - - SaveChanges(); + Offers.Add( + new Offer + { + Id = 1, + Variations = new List + { + v1, + v2, + v3 + } + }); + + await SaveChangesAsync(); } public abstract class EntityBase @@ -181,7 +181,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) modelBuilder.Entity(x => x.ComplexProperty(c => c.Info).IsRequired()); } - public void Seed() + public async Task SeedAsync() { var c = new C { @@ -196,7 +196,7 @@ public void Seed() }; Cs.Add(c); - SaveChanges(); + await SaveChangesAsync(); } public class Metadata diff --git a/test/EFCore.Relational.Specification.Tests/Query/AdHocJsonQueryTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/AdHocJsonQueryTestBase.cs index 3482997fe13..b51ac0f8a32 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/AdHocJsonQueryTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/AdHocJsonQueryTestBase.cs @@ -30,25 +30,18 @@ public virtual async Task Contains_on_nested_collection_with_init_only_navigatio Assert.Equal(new DateOnly(2023, 1, 1), result.Visits.DaysVisited.Single()); } - protected virtual void Seed32310(MyContext32310 context) + protected virtual async Task Seed32310(MyContext32310 context) { - var user = new Pub32310 - { - Name = "FBI", - Visits = new Visits32310 - { - LocationTag = "tag", - DaysVisited = [new(2023, 1, 1)] - } - }; + var user = new Pub32310 { Name = "FBI", Visits = new Visits32310 { LocationTag = "tag", DaysVisited = [new(2023, 1, 1)] } }; context.Add(user); - context.SaveChanges(); + await context.SaveChangesAsync(); } protected class MyContext32310(DbContextOptions options) : DbContext(options) { - public DbSet Pubs => Set(); + public DbSet Pubs + => Set(); protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity(b => { b.OwnsOne(e => e.Visits).ToJson(); }); @@ -114,7 +107,7 @@ public virtual async Task Can_project_nullable_json_property_when_the_element_in } } - protected abstract void Seed29219(MyContext29219 ctx); + protected abstract Task Seed29219(MyContext29219 ctx); protected class MyContext29219(DbContextOptions options) : DbContext(options) { @@ -145,7 +138,7 @@ public class MyJsonEntity29219 #region 30028 - protected abstract void Seed30028(MyContext30028 ctx); + protected abstract Task Seed30028(MyContext30028 ctx); protected class MyContext30028(DbContextOptions options) : DbContext(options) { @@ -278,16 +271,15 @@ public virtual async Task Project_json_with_no_properties() context.Entities.ToList(); } - protected void Seed30028(Context32939 ctx) + protected Task Seed30028(Context32939 ctx) { var entity = new Context32939.Entity32939 { - Empty = new Context32939.JsonEmpty32939(), - FieldOnly = new Context32939.JsonFieldOnly32939() + Empty = new Context32939.JsonEmpty32939(), FieldOnly = new Context32939.JsonFieldOnly32939() }; ctx.Entities.Add(entity); - ctx.SaveChanges(); + return ctx.SaveChangesAsync(); } protected class Context32939(DbContextOptions options) : DbContext(options) @@ -323,7 +315,7 @@ public class JsonFieldOnly32939 #region 33046 - protected abstract void Seed33046(Context33046 ctx); + protected abstract Task Seed33046(Context33046 ctx); [ConditionalFact] public virtual async Task Query_with_nested_json_collection_mapped_to_private_field_via_IReadOnlyList() @@ -341,11 +333,12 @@ protected class Context33046(DbContextOptions options) : DbContext(options) protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity().Property(x => x.Id).ValueGeneratedNever(); - modelBuilder.Entity().OwnsMany(x => x.Rounds, ownedBuilder => - { - ownedBuilder.ToJson(); - ownedBuilder.OwnsMany(r => r.SubRounds); - }); + modelBuilder.Entity().OwnsMany( + x => x.Rounds, ownedBuilder => + { + ownedBuilder.ToJson(); + ownedBuilder.OwnsMany(r => r.SubRounds); + }); } public class Review @@ -355,7 +348,8 @@ public class Review #pragma warning disable IDE0044 // Add readonly modifier private List _rounds = []; #pragma warning restore IDE0044 // Add readonly modifier - public IReadOnlyList Rounds => _rounds.AsReadOnly(); + public IReadOnlyList Rounds + => _rounds.AsReadOnly(); } public class ReviewRound @@ -365,7 +359,8 @@ public class ReviewRound #pragma warning disable IDE0044 // Add readonly modifier private List _subRounds = []; #pragma warning restore IDE0044 // Add readonly modifier - public IReadOnlyList SubRounds => _subRounds.AsReadOnly(); + public IReadOnlyList SubRounds + => _subRounds.AsReadOnly(); } public class SubRound @@ -506,7 +501,7 @@ public virtual async Task Predicate_based_on_element_of_json_array_of_primitives } } - protected abstract void SeedArrayOfPrimitives(MyContextArrayOfPrimitives ctx); + protected abstract Task SeedArrayOfPrimitives(MyContextArrayOfPrimitives ctx); protected class MyContextArrayOfPrimitives(DbContextOptions options) : DbContext(options) { @@ -590,7 +585,7 @@ public virtual async Task Junk_in_json_basic_no_tracking(bool async) } } - protected abstract void SeedJunkInJson(MyContextJunkInJson ctx); + protected abstract Task SeedJunkInJson(MyContextJunkInJson ctx); protected class MyContextJunkInJson(DbContextOptions options) : DbContext(options) { @@ -694,7 +689,7 @@ public virtual async Task Tricky_buffering_basic(bool async) } } - protected abstract void SeedTrickyBuffering(MyContextTrickyBuffering ctx); + protected abstract Task SeedTrickyBuffering(MyContextTrickyBuffering ctx); protected class MyContextTrickyBuffering(DbContextOptions options) : DbContext(options) { @@ -824,7 +819,7 @@ public virtual async Task Project_shadow_properties_from_json_entity(bool async) } } - protected abstract void SeedShadowProperties(MyContextShadowProperties ctx); + protected abstract Task SeedShadowProperties(MyContextShadowProperties ctx); protected class MyContextShadowProperties(DbContextOptions options) : DbContext(options) { @@ -912,7 +907,7 @@ protected void OnConfiguringLazyLoadingProxies(DbContextOptionsBuilder optionsBu protected IServiceCollection AddServicesLazyLoadingProxies(IServiceCollection addServices) => addServices.AddEntityFrameworkProxies(); - private void SeedLazyLoadingProxies(MyContextLazyLoadingProxies ctx) + private Task SeedLazyLoadingProxies(MyContextLazyLoadingProxies ctx) { var r1 = new MyJsonEntityLazyLoadingProxiesWithCtor("r1", 1); var c11 = new MyJsonEntityLazyLoadingProxies { Name = "c11", Number = 11 }; @@ -945,7 +940,7 @@ private void SeedLazyLoadingProxies(MyContextLazyLoadingProxies ctx) }; ctx.Entities.AddRange(e1, e2); - ctx.SaveChanges(); + return ctx.SaveChangesAsync(); } protected class MyContextLazyLoadingProxies(DbContextOptions options) : DbContext(options) @@ -1004,7 +999,7 @@ public virtual async Task Not_ICollection_basic_projection(bool async) } } - protected abstract void SeedNotICollection(MyContextNotICollection ctx); + protected abstract Task SeedNotICollection(MyContextNotICollection ctx); public class MyEntityNotICollection { @@ -1017,7 +1012,8 @@ public class MyJsonEntityNotICollection { private readonly List _collection = []; - public IEnumerable Collection => _collection.AsReadOnly(); + public IEnumerable Collection + => _collection.AsReadOnly(); } public class MyJsonNestedEntityNotICollection @@ -1033,11 +1029,12 @@ public class MyContextNotICollection(DbContextOptions options) : DbContext(optio protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity().Property(x => x.Id).ValueGeneratedNever(); - modelBuilder.Entity().OwnsOne(cr => cr.Json, nb => - { - nb.ToJson(); - nb.OwnsMany(x => x.Collection); - }); + modelBuilder.Entity().OwnsOne( + cr => cr.Json, nb => + { + nb.ToJson(); + nb.OwnsMany(x => x.Collection); + }); } } diff --git a/test/EFCore.Relational.Specification.Tests/Query/AdHocMiscellaneousQueryRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/AdHocMiscellaneousQueryRelationalTestBase.cs index 5e9a8f0530a..d27d4c9d37c 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/AdHocMiscellaneousQueryRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/AdHocMiscellaneousQueryRelationalTestBase.cs @@ -32,10 +32,10 @@ public async Task Query_when_null_key_in_database_should_throw() Assert.Equal( RelationalStrings.ErrorMaterializingPropertyNullReference(nameof(Context2951.ZeroKey2951), "Id", typeof(int)), - Assert.Throws(() => context.ZeroKeys.ToList()).Message); + (await Assert.ThrowsAsync(() => context.ZeroKeys.ToListAsync())).Message); } - protected abstract void Seed2951(Context2951 context); + protected abstract Task Seed2951(Context2951 context); protected class Context2951(DbContextOptions options) : DbContext(options) { diff --git a/test/EFCore.Relational.Specification.Tests/Query/AdHocNavigationsQueryRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/AdHocNavigationsQueryRelationalTestBase.cs index c0e9a812140..31fa22cdf6c 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/AdHocNavigationsQueryRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/AdHocNavigationsQueryRelationalTestBase.cs @@ -25,7 +25,7 @@ protected void AssertSql(params string[] expected) [InlineData(false, false)] public virtual async Task Select_enumerable_navigation_backed_by_collection(bool async, bool split) { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var query = context.Set().Select(appEntity => appEntity.OtherEntities); @@ -48,7 +48,7 @@ private class Context21803(DbContextOptions options) : DbContext(options) { public DbSet Entities { get; set; } - public void Seed() + public async Task SeedAsync() { var appEntity = new AppEntity(); AddRange( @@ -57,7 +57,7 @@ public void Seed() new OtherEntity { AppEntity = appEntity }, new OtherEntity { AppEntity = appEntity }); - SaveChanges(); + await SaveChangesAsync(); } public class AppEntity diff --git a/test/EFCore.Relational.Specification.Tests/Query/AdHocQuerySplittingQueryTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/AdHocQuerySplittingQueryTestBase.cs index e7312245b9c..06c6fa948b5 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/AdHocQuerySplittingQueryTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/AdHocQuerySplittingQueryTestBase.cs @@ -22,7 +22,9 @@ protected void ClearLog() protected void AssertSql(params string[] expected) => TestSqlLoggerFactory.AssertBaseline(expected); - protected abstract DbContextOptionsBuilder SetQuerySplittingBehavior(DbContextOptionsBuilder optionsBuilder, QuerySplittingBehavior splittingBehavior); + protected abstract DbContextOptionsBuilder SetQuerySplittingBehavior( + DbContextOptionsBuilder optionsBuilder, + QuerySplittingBehavior splittingBehavior); protected abstract DbContextOptionsBuilder ClearQuerySplittingBehavior(DbContextOptionsBuilder optionsBuilder); @@ -32,7 +34,7 @@ protected void AssertSql(params string[] expected) public virtual async Task Can_configure_SingleQuery_at_context_level() { var contextFactory = await InitializeAsync( - seed: c => c.Seed(), + seed: c => c.SeedAsync(), onConfiguring: o => SetQuerySplittingBehavior(o, QuerySplittingBehavior.SingleQuery)); using (var context = contextFactory.CreateContext()) @@ -55,7 +57,7 @@ public virtual async Task Can_configure_SingleQuery_at_context_level() public virtual async Task Can_configure_SplitQuery_at_context_level() { var contextFactory = await InitializeAsync( - seed: c => c.Seed(), + seed: c => c.SeedAsync(), onConfiguring: o => SetQuerySplittingBehavior(o, QuerySplittingBehavior.SplitQuery)); using (var context = contextFactory.CreateContext()) @@ -78,7 +80,7 @@ public virtual async Task Can_configure_SplitQuery_at_context_level() public virtual async Task Unconfigured_query_splitting_behavior_throws_a_warning() { var contextFactory = await InitializeAsync( - seed: c => c.Seed(), + seed: c => c.SeedAsync(), onConfiguring: o => ClearQuerySplittingBehavior(o)); using (var context = contextFactory.CreateContext()) @@ -99,7 +101,7 @@ public virtual async Task Unconfigured_query_splitting_behavior_throws_a_warning [ConditionalFact] public virtual async Task Using_AsSingleQuery_without_context_configuration_does_not_throw_warning() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); context.Parents.Include(p => p.Children1).Include(p => p.Children2).AsSingleQuery().ToList(); } @@ -107,7 +109,7 @@ public virtual async Task Using_AsSingleQuery_without_context_configuration_does [ConditionalFact] public virtual async Task SplitQuery_disposes_inner_data_readers() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); ((RelationalTestStore)contextFactory.TestStore).CloseConnection(); @@ -144,10 +146,10 @@ protected class Context21355(DbContextOptions options) : DbContext(options) { public DbSet Parents { get; set; } - public void Seed() + public async Task SeedAsync() { Add(new Parent { Id = "Parent1", Children1 = [new(), new()] }); - SaveChanges(); + await SaveChangesAsync(); } public class Parent @@ -225,14 +227,14 @@ void Query(Context25225 context, Guid parentId, Guid collectionId) return (context1, context2); } - private Task> CreateContext25225Async() - => InitializeAsync( - seed: c => c.Seed(), + private async Task> CreateContext25225Async() + => await InitializeAsync( + seed: c => c.SeedAsync(), onConfiguring: o => SetQuerySplittingBehavior(o, QuerySplittingBehavior.SplitQuery), - createTestStore: CreateTestStore25225); + createTestStore: () => CreateTestStore25225()); - protected virtual TestStore CreateTestStore25225() - => base.CreateTestStore(); + protected virtual Task CreateTestStore25225() + => Task.FromResult(base.CreateTestStore()); private static IQueryable SelectParent25225(Context25225 context, Guid parentId) => context @@ -247,8 +249,7 @@ protected virtual TestStore CreateTestStore25225() .Select( c => new Context25225.CollectionViewModel { - Id = c.Id, - ParentId = c.ParentId, + Id = c.Id, ParentId = c.ParentId, }) .ToArray() }); @@ -270,12 +271,12 @@ protected class Context25225(DbContextOptions options) : DbContext(options) public static readonly Guid Collection2Id = new("d347bbd5-003a-441f-a148-df8ab8ac4a29"); public DbSet Parents { get; set; } - public void Seed() + public async Task SeedAsync() { var parent1 = new Parent { Id = Parent1Id, Collection = new List { new() { Id = Collection1Id, } } }; var parent2 = new Parent { Id = Parent2Id, Collection = new List { new() { Id = Collection2Id, } } }; AddRange(parent1, parent2); - SaveChanges(); + await SaveChangesAsync(); } public class Parent @@ -314,7 +315,7 @@ public class CollectionViewModel public virtual async Task NoTracking_split_query_creates_only_required_instances(bool async) { var contextFactory = await InitializeAsync( - seed: c => c.Seed(), + seed: c => c.SeedAsync(), onConfiguring: o => SetQuerySplittingBehavior(o, QuerySplittingBehavior.SplitQuery)); using var context = contextFactory.CreateContext(); @@ -335,11 +336,11 @@ private class Context25400(DbContextOptions options) : DbContext(options) protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity().HasKey(e => e.Id); - public void Seed() + public async Task SeedAsync() { Tests.Add(new Test(15)); - SaveChanges(); + await SaveChangesAsync(); } public class Test diff --git a/test/EFCore.Relational.Specification.Tests/Query/EntitySplittingQueryTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/EntitySplittingQueryTestBase.cs index bab34036905..c30158fe590 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/EntitySplittingQueryTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/EntitySplittingQueryTestBase.cs @@ -2920,7 +2920,7 @@ protected async Task InitializeContextFactoryAsync(Action onModelC { wc.Log(RelationalEventId.ForeignKeyTpcPrincipalWarning); }), - shouldLogCategory: _ => true, seed: c => Seed(c)); + shouldLogCategory: _ => true, seed: c => SeedAsync(c)); protected virtual EntitySplittingContext CreateContext() => ContextFactory.CreateContext(); @@ -2947,12 +2947,12 @@ protected virtual void OnModelCreating(ModelBuilder modelBuilder) modelBuilder.Entity(); } - protected virtual void Seed(EntitySplittingContext context) + protected virtual Task SeedAsync(EntitySplittingContext context) => EntitySplittingData.Instance.Seed(context); - public override void Dispose() + public override async Task DisposeAsync() { - base.Dispose(); + await base.DisposeAsync(); ContextFactory = null; } diff --git a/test/EFCore.Relational.Specification.Tests/Query/JsonQueryFixtureBase.cs b/test/EFCore.Relational.Specification.Tests/Query/JsonQueryFixtureBase.cs index cc407d97505..16d35739592 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/JsonQueryFixtureBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/JsonQueryFixtureBase.cs @@ -470,8 +470,8 @@ public override JsonQueryContext CreateContext() return context; } - protected override void Seed(JsonQueryContext context) - => JsonQueryContext.Seed(context); + protected override async Task SeedAsync(JsonQueryContext context) + => await JsonQueryContext.SeedAsync(context); protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext context) { diff --git a/test/EFCore.Relational.Specification.Tests/Query/NonSharedPrimitiveCollectionsQueryRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/NonSharedPrimitiveCollectionsQueryRelationalTestBase.cs index 13d3a4387ba..3867e1e0338 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/NonSharedPrimitiveCollectionsQueryRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/NonSharedPrimitiveCollectionsQueryRelationalTestBase.cs @@ -22,7 +22,7 @@ public virtual async Task Column_collection_inside_json_owned_entity() context.AddRange( new TestOwner { Owned = new TestOwned { Strings = ["foo", "bar"] } }, new TestOwner { Owned = new TestOwned { Strings = ["baz"] } }); - context.SaveChanges(); + return context.SaveChangesAsync(); }); await using var context = contextFactory.CreateContext(); diff --git a/test/EFCore.Relational.Specification.Tests/Query/NullSemanticsQueryFixtureBase.cs b/test/EFCore.Relational.Specification.Tests/Query/NullSemanticsQueryFixtureBase.cs index 381cb70fee1..8b2e940e023 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/NullSemanticsQueryFixtureBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/NullSemanticsQueryFixtureBase.cs @@ -103,8 +103,8 @@ public override NullSemanticsContext CreateContext() return context; } - protected override void Seed(NullSemanticsContext context) - => NullSemanticsContext.Seed(context); + protected override Task SeedAsync(NullSemanticsContext context) + => NullSemanticsContext.SeedAsync(context); protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext context) { diff --git a/test/EFCore.Relational.Specification.Tests/Query/OperatorsProceduralQueryTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/OperatorsProceduralQueryTestBase.cs index 6e641011959..f35a2a8679a 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/OperatorsProceduralQueryTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/OperatorsProceduralQueryTestBase.cs @@ -127,7 +127,7 @@ protected OperatorsProceduralQueryTestBase() protected override string StoreName => "OperatorsProceduralTest"; - protected virtual void Seed(OperatorsContext ctx) + protected virtual async Task SeedAsync(OperatorsContext ctx) { ctx.Set().AddRange(ExpectedData.OperatorEntitiesString); ctx.Set().AddRange(ExpectedData.OperatorEntitiesInt); @@ -137,14 +137,14 @@ protected virtual void Seed(OperatorsContext ctx) ctx.Set().AddRange(ExpectedData.OperatorEntitiesNullableBool); ctx.Set().AddRange(ExpectedData.OperatorEntitiesDateTimeOffset); - ctx.SaveChanges(); + await ctx.SaveChangesAsync(); } //[ConditionalFact] public virtual async Task Procedural_predicate_test_six_sources_three_pairs() { var maxDepth = 7; - var contextFactory = await InitializeAsync(seed: Seed); + var contextFactory = await InitializeAsync(seed: ctx => SeedAsync(ctx)); using var context = contextFactory.CreateContext(); var actualSetSource = new ActualSetSource(context); @@ -191,7 +191,7 @@ public virtual async Task Procedural_predicate_test_six_sources_three_pairs() public virtual async Task Procedural_projection_test_six_sources_two_trios() { var maxDepth = 7; - var contextFactory = await InitializeAsync(seed: Seed); + var contextFactory = await InitializeAsync(seed: ctx => SeedAsync(ctx)); using var context = contextFactory.CreateContext(); var actualSetSource = new ActualSetSource(context); @@ -836,7 +836,12 @@ public class OperatorDto3(TEntity1 entity public TResult Result { get; set; } = result; } - public class OperatorDto4(TEntity1 entity1, TEntity2 entity2, TEntity3 entity3, TEntity4 entity4, TResult result) + public class OperatorDto4( + TEntity1 entity1, + TEntity2 entity2, + TEntity3 entity3, + TEntity4 entity4, + TResult result) where TEntity1 : OperatorEntityBase where TEntity2 : OperatorEntityBase where TEntity3 : OperatorEntityBase @@ -850,7 +855,13 @@ public class OperatorDto4(TEnti public TResult Result { get; set; } = result; } - public class OperatorDto5(TEntity1 entity1, TEntity2 entity2, TEntity3 entity3, TEntity4 entity4, TEntity5 entity5, TResult result) + public class OperatorDto5( + TEntity1 entity1, + TEntity2 entity2, + TEntity3 entity3, + TEntity4 entity4, + TEntity5 entity5, + TResult result) where TEntity1 : OperatorEntityBase where TEntity2 : OperatorEntityBase where TEntity3 : OperatorEntityBase diff --git a/test/EFCore.Relational.Specification.Tests/Query/OperatorsQueryTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/OperatorsQueryTestBase.cs index 921ab5b9f4a..818554d1d94 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/OperatorsQueryTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/OperatorsQueryTestBase.cs @@ -17,7 +17,7 @@ protected OperatorsQueryTestBase() protected override string StoreName => "OperatorsTest"; - protected virtual void Seed(OperatorsContext ctx) + protected virtual Task Seed(OperatorsContext ctx) { ctx.Set().AddRange(ExpectedData.OperatorEntitiesString); ctx.Set().AddRange(ExpectedData.OperatorEntitiesInt); @@ -27,7 +27,7 @@ protected virtual void Seed(OperatorsContext ctx) ctx.Set().AddRange(ExpectedData.OperatorEntitiesNullableBool); ctx.Set().AddRange(ExpectedData.OperatorEntitiesDateTimeOffset); - ctx.SaveChanges(); + return ctx.SaveChangesAsync(); } [ConditionalFact(Skip = "issue #30245")] @@ -326,7 +326,7 @@ public virtual async Task Concat_and_json_scalar(bool async) context.Set().AddRange( new Owner { Owned = new Owned { SomeProperty = "Bar" } }, new Owner { Owned = new Owned { SomeProperty = "Baz" } }); - context.SaveChanges(); + return context.SaveChangesAsync(); }); await using var context = contextFactory.CreateContext(); diff --git a/test/EFCore.Relational.Specification.Tests/Query/OptionalDependentQueryFixtureBase.cs b/test/EFCore.Relational.Specification.Tests/Query/OptionalDependentQueryFixtureBase.cs index 544a6a68dde..c4366a6ce5e 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/OptionalDependentQueryFixtureBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/OptionalDependentQueryFixtureBase.cs @@ -7,7 +7,9 @@ namespace Microsoft.EntityFrameworkCore.Query; #nullable disable -public abstract class OptionalDependentQueryFixtureBase : SharedStoreFixtureBase, IQueryFixtureBase, ITestSqlLoggerFactory +public abstract class OptionalDependentQueryFixtureBase : SharedStoreFixtureBase, + IQueryFixtureBase, + ITestSqlLoggerFactory { private OptionalDependentData _expectedData; @@ -132,8 +134,8 @@ public static void AssertOptionalDependentNestedJsonSomeRequired( public TestSqlLoggerFactory TestSqlLoggerFactory => (TestSqlLoggerFactory)ListLoggerFactory; - protected override void Seed(OptionalDependentContext context) - => OptionalDependentContext.Seed(context); + protected override Task SeedAsync(OptionalDependentContext context) + => OptionalDependentContext.SeedAsync(context); protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext context) { diff --git a/test/EFCore.Relational.Specification.Tests/Query/OwnedEntityQueryRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/OwnedEntityQueryRelationalTestBase.cs index e5e158982d3..55789c12376 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/OwnedEntityQueryRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/OwnedEntityQueryRelationalTestBase.cs @@ -234,7 +234,7 @@ protected class PublishTokenType25680 [MemberData(nameof(IsAsyncData))] public virtual async Task Owned_reference_mapped_to_different_table_updated_correctly_after_subquery_pushdown(bool async) { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); await base.Owned_references_on_same_level_expanded_at_different_times_around_take_helper(context, async); @@ -244,7 +244,7 @@ public virtual async Task Owned_reference_mapped_to_different_table_updated_corr [MemberData(nameof(IsAsyncData))] public virtual async Task Owned_reference_mapped_to_different_table_nested_updated_correctly_after_subquery_pushdown(bool async) { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); await base.Owned_references_on_same_level_nested_expanded_at_different_times_around_take_helper(context, async); @@ -283,7 +283,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) [MemberData(nameof(IsAsyncData))] public virtual async Task Owned_entity_with_all_null_properties_materializes_when_not_containing_another_owned_entity(bool async) { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var query = context.RotRutCases.OrderBy(e => e.Buyer); @@ -315,7 +315,7 @@ public virtual async Task Owned_entity_with_all_null_properties_materializes_whe [MemberData(nameof(IsAsyncData))] public virtual async Task Owned_entity_with_all_null_properties_entity_equality_when_not_containing_another_owned_entity(bool async) { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var query = context.RotRutCases.AsNoTracking().Select(e => e.Rot).Where(e => e != null); @@ -337,13 +337,16 @@ public virtual async Task Owned_entity_with_all_null_properties_entity_equality_ [MemberData(nameof(IsAsyncData))] public virtual async Task Owned_entity_with_all_null_properties_in_compared_to_null_in_conditional_projection(bool async) { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var query = context.RotRutCases .AsNoTracking() .OrderBy(e => e.Id) - .Select(e => e.Rot == null ? null : new Context28247.RotDto { MyApartmentNo = e.Rot.ApartmentNo, MyServiceType = e.Rot.ServiceType }); + .Select( + e => e.Rot == null + ? null + : new Context28247.RotDto { MyApartmentNo = e.Rot.ApartmentNo, MyServiceType = e.Rot.ServiceType }); var result = async ? await query.ToListAsync() @@ -366,13 +369,16 @@ public virtual async Task Owned_entity_with_all_null_properties_in_compared_to_n [MemberData(nameof(IsAsyncData))] public virtual async Task Owned_entity_with_all_null_properties_in_compared_to_non_null_in_conditional_projection(bool async) { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var query = context.RotRutCases .AsNoTracking() .OrderBy(e => e.Id) - .Select(e => e.Rot != null ? new Context28247.RotDto { MyApartmentNo = e.Rot.ApartmentNo, MyServiceType = e.Rot.ServiceType } : null); + .Select( + e => e.Rot != null + ? new Context28247.RotDto { MyApartmentNo = e.Rot.ApartmentNo, MyServiceType = e.Rot.ServiceType } + : null); var result = async ? await query.ToListAsync() @@ -395,7 +401,7 @@ public virtual async Task Owned_entity_with_all_null_properties_in_compared_to_n [MemberData(nameof(IsAsyncData))] public virtual async Task Owned_entity_with_all_null_properties_property_access_when_not_containing_another_owned_entity(bool async) { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var query = context.RotRutCases.AsNoTracking().Select(e => e.Rot.ApartmentNo); @@ -430,7 +436,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) b.OwnsOne(e => e.Rut); }); - public void Seed() + public Task SeedAsync() { Add( new RotRutCase @@ -448,7 +454,7 @@ public void Seed() Rut = new Rut { Value = null } }); - SaveChanges(); + return SaveChangesAsync(); } public class RotRutCase @@ -485,7 +491,7 @@ public class Rut [MemberData(nameof(IsAsyncData))] public virtual async Task Join_selects_with_duplicating_aliases_and_owned_expansion_uniquifies_correctly(bool async) { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var query = from monarch in context.Monarchs @@ -507,7 +513,7 @@ private class Context30358(DbContextOptions options) : DbContext(options) protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity().OwnsOne(x => x.ToolUsed, x => x.ToTable("MagicTools")); - public void Seed() + public Task SeedAsync() { Add( new Monarch @@ -537,7 +543,7 @@ public void Seed() ToolUsed = new MagicTool { Name = "The Hundred Words" } }); - SaveChanges(); + return SaveChangesAsync(); } public class Monarch @@ -568,7 +574,7 @@ public class MagicTool [ConditionalFact] public async Task Can_have_required_owned_type_on_derived_type() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); context.Set().ToList(); } @@ -578,23 +584,26 @@ private class Context31107(DbContextOptions options) : DbContext(options) protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity(); - modelBuilder.Entity(b => - { - b.OwnsOne(entity => entity.Data, builder => + modelBuilder.Entity( + b => { - builder.ToTable("Child1EntityData"); - builder.WithOwner().HasForeignKey("Child1EntityId"); + b.OwnsOne( + entity => entity.Data, builder => + { + builder.ToTable("Child1EntityData"); + builder.WithOwner().HasForeignKey("Child1EntityId"); + }); + b.Navigation(e => e.Data).IsRequired(); }); - b.Navigation(e => e.Data).IsRequired(); - }); modelBuilder.Entity(); } - public void Seed() + + public Task SeedAsync() { Add(new Child2Entity { Id = Guid.NewGuid() }); - SaveChanges(); + return SaveChangesAsync(); } public abstract class BaseEntity diff --git a/test/EFCore.Relational.Specification.Tests/Query/SharedTypeQueryRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/SharedTypeQueryRelationalTestBase.cs index 6972f15a921..0d2c0d4da7c 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/SharedTypeQueryRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/SharedTypeQueryRelationalTestBase.cs @@ -21,7 +21,7 @@ protected void AssertSql(params string[] expected) public virtual async Task Can_use_shared_type_entity_type_in_query_filter_with_from_sql(bool async) { var contextFactory = await InitializeAsync( - seed: c => c.Seed()); + seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var query = context.Set(); @@ -33,24 +33,24 @@ public virtual async Task Can_use_shared_type_entity_type_in_query_filter_with_f } [ConditionalFact] - public virtual void Ad_hoc_query_for_shared_type_entity_type_works() + public virtual async Task Ad_hoc_query_for_shared_type_entity_type_works() { - var contextFactory = Initialize( - seed: c => c.Seed()); + var contextFactory = await InitializeAsync( + seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var result = context.Database.SqlQueryRaw( ((RelationalTestStore)TestStore).NormalizeDelimitersInRawString(@"SELECT * FROM [ViewQuery24601]")); - Assert.Empty(result); + Assert.Empty(await result.ToListAsync()); } [ConditionalFact] - public virtual void Ad_hoc_query_for_default_shared_type_entity_type_throws() + public virtual async Task Ad_hoc_query_for_default_shared_type_entity_type_throws() { - var contextFactory = Initialize( - seed: c => c.Seed()); + var contextFactory = await InitializeAsync( + seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); diff --git a/test/EFCore.Relational.Specification.Tests/Query/ToSqlQueryTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/ToSqlQueryTestBase.cs index bdbeb97e88e..516f1b8511f 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/ToSqlQueryTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/ToSqlQueryTestBase.cs @@ -13,16 +13,16 @@ protected override string StoreName public virtual async Task Entity_type_with_navigation_mapped_to_SqlQuery(bool async) { var contextFactory = await InitializeAsync( - seed: c => + seed: async c => { var author = new Author { Name = "Toast", Posts = { new Post { Title = "Sausages of the world!" } } }; c.Add(author); - c.SaveChanges(); + await c.SaveChangesAsync(); var postStat = new PostStat { Count = 10, Author = author }; author.PostStat = postStat; c.Add(postStat); - c.SaveChanges(); + await c.SaveChangesAsync(); }); using var context = contextFactory.CreateContext(); diff --git a/test/EFCore.Relational.Specification.Tests/Query/UdfDbFunctionTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/UdfDbFunctionTestBase.cs index 38cfc869361..c43c07a2258 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/UdfDbFunctionTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/UdfDbFunctionTestBase.cs @@ -259,6 +259,7 @@ public IQueryable GetCustomerData(int customerId) => FromExpression(() => GetCustomerData(customerId)); #endregion + #endregion protected override void OnModelCreating(ModelBuilder modelBuilder) @@ -378,9 +379,9 @@ public TestSqlLoggerFactory TestSqlLoggerFactory protected override bool ShouldLogCategory(string logCategory) => logCategory == DbLoggerCategory.Query.Name; - protected override void Seed(DbContext context) + protected override async Task SeedAsync(DbContext context) { - context.Database.EnsureCreatedResiliently(); + await context.Database.EnsureCreatedResilientlyAsync(); var product1 = new Product { Name = "Product1" }; var product2 = new Product { Name = "Product2" }; diff --git a/test/EFCore.Relational.Specification.Tests/Scaffolding/CompiledModelRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Scaffolding/CompiledModelRelationalTestBase.cs index 2e8e68f9204..1652d5a5549 100644 --- a/test/EFCore.Relational.Specification.Tests/Scaffolding/CompiledModelRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Scaffolding/CompiledModelRelationalTestBase.cs @@ -97,11 +97,12 @@ protected override void BuildBigModel(ModelBuilder modelBuilder, bool jsonColumn .UsingEntity( jb => { - jb.ToTable(tb => - { - tb.HasComment("Join table"); - tb.ExcludeFromMigrations(); - }); + jb.ToTable( + tb => + { + tb.HasComment("Join table"); + tb.ExcludeFromMigrations(); + }); jb.Property("rowid") .IsRowVersion() .HasComment("RowVersion") @@ -283,15 +284,15 @@ protected override void AssertBigModel(IModel model, bool jsonColumns) if (jsonColumns) { Assert.Equal( - new[] - { - derivedSkipNavigation.ForeignKey, - referenceOwnership, - collectionOwnership, - dependentForeignKey, - derivedSkipNavigation.Inverse.ForeignKey - }, - principalKey.GetReferencingForeignKeys()); + new[] + { + derivedSkipNavigation.ForeignKey, + referenceOwnership, + collectionOwnership, + dependentForeignKey, + derivedSkipNavigation.Inverse.ForeignKey + }, + principalKey.GetReferencingForeignKeys()); Assert.Equal( new[] { dependentBaseForeignKey, referenceOwnership, derivedSkipNavigation.Inverse.ForeignKey }, @@ -300,16 +301,16 @@ protected override void AssertBigModel(IModel model, bool jsonColumns) else { Assert.Equal( - new[] - { - derivedSkipNavigation.ForeignKey, - tptForeignKey, - referenceOwnership, - collectionOwnership, - dependentForeignKey, - derivedSkipNavigation.Inverse.ForeignKey - }, - principalKey.GetReferencingForeignKeys()); + new[] + { + derivedSkipNavigation.ForeignKey, + tptForeignKey, + referenceOwnership, + collectionOwnership, + dependentForeignKey, + derivedSkipNavigation.Inverse.ForeignKey + }, + principalKey.GetReferencingForeignKeys()); Assert.Equal( new[] { dependentBaseForeignKey, tptForeignKey, referenceOwnership, derivedSkipNavigation.Inverse.ForeignKey }, @@ -374,7 +375,7 @@ protected override void BuildComplexTypesModel(ModelBuilder modelBuilder) .HasOriginalValueParameter(p => p.Id)); eb.DeleteUsingStoredProcedure( s => s.HasRowsAffectedParameter() - .HasOriginalValueParameter(p => p.Id)); + .HasOriginalValueParameter(p => p.Id)); }); modelBuilder.Entity>>( @@ -586,7 +587,8 @@ protected virtual void BuildTpcSprocsModel(ModelBuilder modelBuilder) }); } - protected virtual bool UseSprocReturnValue => false; + protected virtual bool UseSprocReturnValue + => false; protected virtual void AssertTpcSprocs(IModel model) { @@ -697,6 +699,7 @@ protected virtual void AssertTpcSprocs(IModel model) { Assert.Equal(["Id_Original", "RowsAffected"], deleteSproc.Parameters.Select(p => p.Name)); } + Assert.Empty(deleteSproc.ResultColumns); Assert.Equal(UseSprocReturnValue, deleteSproc.IsRowsAffectedReturned); Assert.Same(principalBase, deleteSproc.EntityType); @@ -911,7 +914,7 @@ public virtual void Triggers() }); [ConditionalFact] - public virtual void DbFunctions() + public virtual Task DbFunctions() => Test( assertModel: model => { @@ -995,7 +998,8 @@ public virtual void DbFunctions() Assert.Equal("date", isDateParameter.StoreFunctionParameter.Name); Assert.Equal(isDateParameter.StoreType, isDateParameter.StoreFunctionParameter.StoreType); - var getData = model.FindDbFunction(typeof(DbFunctionContext) + var getData = model.FindDbFunction( + typeof(DbFunctionContext) .GetMethod("GetData", [typeof(int)])!)!; Assert.Equal("GetData", getData.Name); //Assert.Equal("dbo", getData.Schema); @@ -1131,7 +1135,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) } [ConditionalFact] - public virtual void Custom_function_type_mapping() + public virtual Task Custom_function_type_mapping() => Test( assertModel: model => { @@ -1157,7 +1161,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) } [ConditionalFact] - public virtual void Custom_function_parameter_type_mapping() + public virtual Task Custom_function_parameter_type_mapping() => Test( assertModel: model => { @@ -1184,7 +1188,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) } [ConditionalFact] - public virtual void Throws_for_custom_function_translation() + public virtual Task Throws_for_custom_function_translation() => Test( expectedExceptionMessage: RelationalStrings.CompiledModelFunctionTranslation("GetSqlFragmentStatic")); diff --git a/test/EFCore.Relational.Specification.Tests/TableSplittingTestBase.cs b/test/EFCore.Relational.Specification.Tests/TableSplittingTestBase.cs index c37d1f39b77..293a1cec9ab 100644 --- a/test/EFCore.Relational.Specification.Tests/TableSplittingTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/TableSplittingTestBase.cs @@ -764,26 +764,24 @@ public virtual async Task ExecuteDelete_throws_for_table_sharing(bool async) { await InitializeAsync(OnModelCreating); - if (async) - { - await TestHelpers.ExecuteWithStrategyInTransactionAsync( - CreateContext, - UseTransaction, - async context => Assert.Contains( - RelationalStrings.NonQueryTranslationFailedWithDetails( - "", RelationalStrings.ExecuteDeleteOnTableSplitting("Vehicles"))[21..], - (await Assert.ThrowsAsync(() => context.Set().ExecuteDeleteAsync())).Message)); - } - else - { - TestHelpers.ExecuteWithStrategyInTransaction( - CreateContext, - UseTransaction, - context => Assert.Contains( - RelationalStrings.NonQueryTranslationFailedWithDetails( - "", RelationalStrings.ExecuteDeleteOnTableSplitting("Vehicles"))[21..], - Assert.Throws(() => context.Set().ExecuteDelete()).Message)); - } + await TestHelpers.ExecuteWithStrategyInTransactionAsync( + CreateContext, + UseTransaction, + async context => Assert.Contains( + RelationalStrings.NonQueryTranslationFailedWithDetails( + "", RelationalStrings.ExecuteDeleteOnTableSplitting("Vehicles"))[21..], + (await Assert.ThrowsAsync( + async () => + { + if (async) + { + await context.Set().ExecuteDeleteAsync(); + } + else + { + context.Set().ExecuteDelete(); + } + })).Message)); } [ConditionalTheory] @@ -792,27 +790,26 @@ public virtual async Task ExecuteUpdate_works_for_table_sharing(bool async) { await InitializeAsync(OnModelCreating); - if (async) - { - await TestHelpers.ExecuteWithStrategyInTransactionAsync( - CreateContext, - UseTransaction, - async context => await context.Set().ExecuteUpdateAsync(s => s.SetProperty(e => e.SeatingCapacity, 1)), - context => + await TestHelpers.ExecuteWithStrategyInTransactionAsync( + CreateContext, + UseTransaction, + async context => + { + if (async) { - Assert.True(context.Set().All(e => e.SeatingCapacity == 1)); - - return Task.CompletedTask; - }); - } - else - { - TestHelpers.ExecuteWithStrategyInTransaction( - CreateContext, - UseTransaction, - context => context.Set().ExecuteUpdate(s => s.SetProperty(e => e.SeatingCapacity, 1)), - context => Assert.True(context.Set().All(e => e.SeatingCapacity == 1))); - } + await context.Set().ExecuteUpdateAsync(s => s.SetProperty(e => e.SeatingCapacity, 1)); + } + else + { + context.Set().ExecuteUpdate(s => s.SetProperty(e => e.SeatingCapacity, 1)); + } + }, async context => + { + Assert.True( + async + ? await context.Set().AllAsync(e => e.SeatingCapacity == 1) + : context.Set().All(e => e.SeatingCapacity == 1)); + }); } [ConditionalTheory] @@ -862,7 +859,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) }); } - public void Seed() + public Task SeedAsync() { Add( new Order @@ -876,7 +873,7 @@ public void Seed() } }); - SaveChanges(); + return SaveChangesAsync(); } } @@ -994,7 +991,7 @@ protected virtual void OnSharedModelCreating(ModelBuilder modelBuilder) protected async Task InitializeAsync(Action onModelCreating, bool seed = true) => ContextFactory = await InitializeAsync( - onModelCreating, shouldLogCategory: _ => true, seed: seed ? c => c.Seed() : null); + onModelCreating, shouldLogCategory: _ => true, seed: seed ? c => c.SeedAsync() : null); protected async Task InitializeSharedAsync(Action onModelCreating, bool sensitiveLogEnabled = true) => SharedContextFactory = await InitializeAsync( @@ -1014,9 +1011,9 @@ protected virtual TransportationContext CreateContext() protected virtual SharedTableContext CreateSharedContext() => SharedContextFactory.CreateContext(); - public override void Dispose() + public override async Task DisposeAsync() { - base.Dispose(); + await base.DisposeAsync(); ContextFactory = null; SharedContextFactory = null; diff --git a/test/EFCore.Relational.Specification.Tests/TestModels/EntitySplitting/EntitySplittingData.cs b/test/EFCore.Relational.Specification.Tests/TestModels/EntitySplitting/EntitySplittingData.cs index a18eec0bb00..c92256cf0a3 100644 --- a/test/EFCore.Relational.Specification.Tests/TestModels/EntitySplitting/EntitySplittingData.cs +++ b/test/EFCore.Relational.Specification.Tests/TestModels/EntitySplitting/EntitySplittingData.cs @@ -276,7 +276,7 @@ private void WireUp() } } - public void Seed(EntitySplittingContext context) + public Task Seed(EntitySplittingContext context) { // Seed data cannot contain any store generated value, // or recreate instances when calling AddRange @@ -285,6 +285,6 @@ public void Seed(EntitySplittingContext context) context.AddRange(_entityThrees); context.AddRange(_baseEntities); - context.SaveChanges(); + return context.SaveChangesAsync(); } } diff --git a/test/EFCore.Relational.Specification.Tests/TestModels/JsonQuery/JsonQueryContext.cs b/test/EFCore.Relational.Specification.Tests/TestModels/JsonQuery/JsonQueryContext.cs index 39c2f36d1d7..b6010b6182f 100644 --- a/test/EFCore.Relational.Specification.Tests/TestModels/JsonQuery/JsonQueryContext.cs +++ b/test/EFCore.Relational.Specification.Tests/TestModels/JsonQuery/JsonQueryContext.cs @@ -17,7 +17,7 @@ public class JsonQueryContext(DbContextOptions options) : DbContext(options) public DbSet JsonEntitiesAllTypes { get; set; } public DbSet JsonEntitiesConverters { get; set; } - public static void Seed(JsonQueryContext context) + public static Task SeedAsync(JsonQueryContext context) { var jsonEntitiesBasic = JsonQueryData.CreateJsonEntitiesBasic(); var entitiesBasic = JsonQueryData.CreateEntitiesBasic(); @@ -40,6 +40,6 @@ public static void Seed(JsonQueryContext context) context.JsonEntitiesInheritance.AddRange(jsonEntitiesInheritance); context.JsonEntitiesAllTypes.AddRange(jsonEntitiesAllTypes); context.JsonEntitiesConverters.AddRange(jsonEntitiesConverters); - context.SaveChanges(); + return context.SaveChangesAsync(); } } diff --git a/test/EFCore.Relational.Specification.Tests/TestModels/OptionalDependent/OptionalDependentContext.cs b/test/EFCore.Relational.Specification.Tests/TestModels/OptionalDependent/OptionalDependentContext.cs index 0379454f3b2..0894d3ef780 100644 --- a/test/EFCore.Relational.Specification.Tests/TestModels/OptionalDependent/OptionalDependentContext.cs +++ b/test/EFCore.Relational.Specification.Tests/TestModels/OptionalDependent/OptionalDependentContext.cs @@ -10,13 +10,13 @@ public class OptionalDependentContext(DbContextOptions options) : DbContext(opti public DbSet EntitiesAllOptional { get; set; } public DbSet EntitiesSomeRequired { get; set; } - public static void Seed(OptionalDependentContext context) + public static async Task SeedAsync(OptionalDependentContext context) { var entitiesAllOptional = OptionalDependentData.CreateEntitiesAllOptional(); var entitiesSomeRequired = OptionalDependentData.CreateEntitiesSomeRequired(); context.EntitiesAllOptional.AddRange(entitiesAllOptional); context.EntitiesSomeRequired.AddRange(entitiesSomeRequired); - context.SaveChanges(); + await context.SaveChangesAsync(); } } diff --git a/test/EFCore.Relational.Specification.Tests/TestUtilities/BulkUpdatesAsserter.cs b/test/EFCore.Relational.Specification.Tests/TestUtilities/BulkUpdatesAsserter.cs index 252e557ff6c..98da8ff8bcf 100644 --- a/test/EFCore.Relational.Specification.Tests/TestUtilities/BulkUpdatesAsserter.cs +++ b/test/EFCore.Relational.Specification.Tests/TestUtilities/BulkUpdatesAsserter.cs @@ -13,40 +13,24 @@ public class BulkUpdatesAsserter(IBulkUpdatesFixtureBase queryFixture, Func _rewriteServerQueryExpression = rewriteServerQueryExpression; private readonly IReadOnlyDictionary _entitySorters = queryFixture.EntitySorters ?? new Dictionary(); - public async Task AssertDelete( + public Task AssertDelete( bool async, Func> query, int rowsAffectedCount) - { - if (async) - { - await TestHelpers.ExecuteWithStrategyInTransactionAsync( - _contextCreator, _useTransaction, - async context => - { - var processedQuery = RewriteServerQuery(query(_setSourceCreator(context))); + => TestHelpers.ExecuteWithStrategyInTransactionAsync( + _contextCreator, _useTransaction, + async context => + { + var processedQuery = RewriteServerQuery(query(_setSourceCreator(context))); - var result = await processedQuery.ExecuteDeleteAsync(); + var result = async + ? await processedQuery.ExecuteDeleteAsync() + : processedQuery.ExecuteDelete(); - Assert.Equal(rowsAffectedCount, result); - }); - } - else - { - TestHelpers.ExecuteWithStrategyInTransaction( - _contextCreator, _useTransaction, - context => - { - var processedQuery = RewriteServerQuery(query(_setSourceCreator(context))); + Assert.Equal(rowsAffectedCount, result); + }); - var result = processedQuery.ExecuteDelete(); - - Assert.Equal(rowsAffectedCount, result); - }); - } - } - - public async Task AssertUpdate( + public Task AssertUpdate( bool async, Func> query, Expression> entitySelector, @@ -54,47 +38,26 @@ public async Task AssertUpdate( int rowsAffectedCount, Action, IReadOnlyList> asserter) where TResult : class - { - var elementSorter = (Func)_entitySorters[typeof(TEntity)]; - if (async) - { - await TestHelpers.ExecuteWithStrategyInTransactionAsync( - _contextCreator, _useTransaction, - async context => - { - var processedQuery = RewriteServerQuery(query(_setSourceCreator(context))); - - var before = processedQuery.AsNoTracking().Select(entitySelector).OrderBy(elementSorter).ToList(); - - var result = await processedQuery.ExecuteUpdateAsync(setPropertyCalls); - - Assert.Equal(rowsAffectedCount, result); - - var after = processedQuery.AsNoTracking().Select(entitySelector).OrderBy(elementSorter).ToList(); + => TestHelpers.ExecuteWithStrategyInTransactionAsync( + _contextCreator, _useTransaction, + async context => + { + var elementSorter = (Func)_entitySorters[typeof(TEntity)]; - asserter?.Invoke(before, after); - }); - } - else - { - TestHelpers.ExecuteWithStrategyInTransaction( - _contextCreator, _useTransaction, - context => - { - var processedQuery = RewriteServerQuery(query(_setSourceCreator(context))); + var processedQuery = RewriteServerQuery(query(_setSourceCreator(context))); - var before = processedQuery.AsNoTracking().Select(entitySelector).OrderBy(elementSorter).ToList(); + var before = processedQuery.AsNoTracking().Select(entitySelector).OrderBy(elementSorter).ToList(); - var result = processedQuery.ExecuteUpdate(setPropertyCalls); + var result = async + ? await processedQuery.ExecuteUpdateAsync(setPropertyCalls) + : processedQuery.ExecuteUpdate(setPropertyCalls); - Assert.Equal(rowsAffectedCount, result); + Assert.Equal(rowsAffectedCount, result); - var after = processedQuery.AsNoTracking().Select(entitySelector).OrderBy(elementSorter).ToList(); + var after = processedQuery.AsNoTracking().Select(entitySelector).OrderBy(elementSorter).ToList(); - asserter?.Invoke(before, after); - }); - } - } + asserter?.Invoke(before, after); + }); private IQueryable RewriteServerQuery(IQueryable query) => query.Provider.CreateQuery(_rewriteServerQueryExpression(query.Expression)); diff --git a/test/EFCore.Relational.Specification.Tests/TestUtilities/RelationalTestStore.cs b/test/EFCore.Relational.Specification.Tests/TestUtilities/RelationalTestStore.cs index 8a8e2aff30d..54404949421 100644 --- a/test/EFCore.Relational.Specification.Tests/TestUtilities/RelationalTestStore.cs +++ b/test/EFCore.Relational.Specification.Tests/TestUtilities/RelationalTestStore.cs @@ -26,17 +26,17 @@ public DbTransaction BeginTransaction() protected virtual DbConnection Connection { get; } = connection; - public override TestStore Initialize( + public override async Task InitializeAsync( IServiceProvider? serviceProvider, Func? createContext, - Action? seed = null, - Action? clean = null) + Func? seed = null, + Func? clean = null) { - base.Initialize(serviceProvider, createContext, seed, clean); + await base.InitializeAsync(serviceProvider, createContext, seed, clean); if (ConnectionState != ConnectionState.Open) { - OpenConnection(); + await OpenConnectionAsync(); } return this; diff --git a/test/EFCore.Relational.Specification.Tests/TransactionInterceptionTestBase.cs b/test/EFCore.Relational.Specification.Tests/TransactionInterceptionTestBase.cs index 4302b4ecb80..ab4bbb162dd 100644 --- a/test/EFCore.Relational.Specification.Tests/TransactionInterceptionTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/TransactionInterceptionTestBase.cs @@ -19,7 +19,7 @@ protected TransactionInterceptionTestBase(InterceptionFixtureBase fixture) [InlineData(true)] public virtual async Task BeginTransaction_without_interceptor(bool async) { - using var context = CreateContext(Enumerable.Empty()); + using var context = await CreateContextAsync(Enumerable.Empty()); using var listener = Fixture.SubscribeToDiagnosticListener(context.ContextId); using (var transaction = async ? await context.Database.BeginTransactionAsync() @@ -36,7 +36,7 @@ public virtual async Task BeginTransaction_without_interceptor(bool async) [InlineData(true)] public virtual async Task UseTransaction_without_interceptor(bool async) { - using var context = CreateContext(Enumerable.Empty()); + using var context = await CreateContextAsync(Enumerable.Empty()); using var listener = Fixture.SubscribeToDiagnosticListener(context.ContextId); using var transaction = context.Database.GetDbConnection().BeginTransaction(); var contextTransaction = async @@ -56,7 +56,7 @@ public virtual async Task UseTransaction_without_interceptor(bool async) [InlineData(true)] public virtual async Task Intercept_BeginTransaction(bool async) { - var (context, interceptor) = CreateContext(); + var (context, interceptor) = await CreateContextAsync(); using (context) { using var listener = Fixture.SubscribeToDiagnosticListener(context.ContextId); @@ -76,7 +76,7 @@ public virtual async Task Intercept_BeginTransaction(bool async) [InlineData(true)] public virtual async Task Intercept_BeginTransaction_with_isolation_level(bool async) { - var (context, interceptor) = CreateContext(); + var (context, interceptor) = await CreateContextAsync(); using (context) { using var listener = Fixture.SubscribeToDiagnosticListener(context.ContextId); @@ -96,7 +96,7 @@ public virtual async Task Intercept_BeginTransaction_with_isolation_level(bool a [InlineData(true)] public virtual async Task Intercept_BeginTransaction_to_suppress(bool async) { - var (context, interceptor) = CreateContext(); + var (context, interceptor) = await CreateContextAsync(); using (context) { using var listener = Fixture.SubscribeToDiagnosticListener(context.ContextId); @@ -143,7 +143,7 @@ public override async ValueTask> TransactionSt [InlineData(true)] public virtual async Task Intercept_BeginTransaction_to_wrap(bool async) { - var (context, interceptor) = CreateContext(); + var (context, interceptor) = await CreateContextAsync(); using (context) { using var listener = Fixture.SubscribeToDiagnosticListener(context.ContextId); @@ -208,7 +208,7 @@ public override async ValueTask TransactionUsedAsync( [InlineData(true)] public virtual async Task Intercept_UseTransaction(bool async) { - var (context, interceptor) = CreateContext(); + var (context, interceptor) = await CreateContextAsync(); using (context) { using var listener = Fixture.SubscribeToDiagnosticListener(context.ContextId); @@ -230,7 +230,7 @@ public virtual async Task Intercept_UseTransaction(bool async) [InlineData(true)] public virtual async Task Intercept_UseTransaction_to_wrap(bool async) { - var (context, interceptor) = CreateContext(); + var (context, interceptor) = await CreateContextAsync(); using (context) { using var listener = Fixture.SubscribeToDiagnosticListener(context.ContextId); @@ -252,7 +252,7 @@ public virtual async Task Intercept_UseTransaction_to_wrap(bool async) [InlineData(true)] public virtual async Task Intercept_Commit(bool async) { - var (context, interceptor) = CreateContext(); + var (context, interceptor) = await CreateContextAsync(); using (context) { using var contextTransaction = async @@ -281,7 +281,7 @@ public virtual async Task Intercept_Commit(bool async) [InlineData(true)] public virtual async Task Intercept_Commit_to_suppress(bool async) { - var (context, interceptor) = CreateContext(); + var (context, interceptor) = await CreateContextAsync(); using (context) { using var contextTransaction = async @@ -313,7 +313,7 @@ public virtual async Task Intercept_Commit_to_suppress(bool async) [InlineData(true)] public virtual async Task Intercept_Rollback(bool async) { - var (context, interceptor) = CreateContext(); + var (context, interceptor) = await CreateContextAsync(); using (context) { using var contextTransaction = async @@ -342,7 +342,7 @@ public virtual async Task Intercept_Rollback(bool async) [InlineData(true)] public virtual async Task Intercept_Rollback_to_suppress(bool async) { - var (context, interceptor) = CreateContext(); + var (context, interceptor) = await CreateContextAsync(); using (context) { using var contextTransaction = async @@ -374,7 +374,7 @@ public virtual async Task Intercept_Rollback_to_suppress(bool async) [InlineData(true)] public virtual async Task Intercept_CreateSavepoint(bool async) { - var (context, interceptor) = CreateContext(); + var (context, interceptor) = await CreateContextAsync(); using (context) { using var contextTransaction = async @@ -403,7 +403,7 @@ public virtual async Task Intercept_CreateSavepoint(bool async) [InlineData(true)] public virtual async Task Intercept_RollbackToSavepoint(bool async) { - var (context, interceptor) = CreateContext(); + var (context, interceptor) = await CreateContextAsync(); using (context) { using var contextTransaction = async @@ -441,7 +441,7 @@ public virtual async Task Intercept_RollbackToSavepoint(bool async) [InlineData(true)] public virtual async Task Intercept_ReleaseSavepoint(bool async) { - var (context, interceptor) = CreateContext(); + var (context, interceptor) = await CreateContextAsync(); using (context) { using var contextTransaction = async @@ -526,7 +526,7 @@ public override async ValueTask TransactionRollingBackAsync( [InlineData(true, false)] public virtual async Task Intercept_error_on_commit_or_rollback(bool async, bool commit) { - var (context, interceptor) = CreateContext(); + var (context, interceptor) = await CreateContextAsync(); using (context) { using var contextTransaction = async @@ -581,7 +581,7 @@ public virtual async Task Intercept_connection_with_multiple_interceptors(bool a var interceptor2 = new WrappingTransactionInterceptor(); var interceptor3 = new TransactionInterceptor(); var interceptor4 = new WrappingTransactionInterceptor(); - using var context = CreateContext( + using var context = await CreateContextAsync( new IInterceptor[] { new NoOpTransactionInterceptor(), interceptor1, interceptor2 }, new IInterceptor[] { interceptor3, interceptor4, new NoOpTransactionInterceptor() }); using var listener = Fixture.SubscribeToDiagnosticListener(context.ContextId); @@ -633,8 +633,8 @@ public override void Rollback() protected override DbConnection DbConnection { get; } = dbConnection; public override IsolationLevel IsolationLevel { get; } = isolationLevel == IsolationLevel.Unspecified - ? IsolationLevel.Snapshot - : isolationLevel; + ? IsolationLevel.Snapshot + : isolationLevel; } private static void AssertBeginTransaction(DbContext context, TransactionInterceptor interceptor, bool async) diff --git a/test/EFCore.Relational.Specification.Tests/TransactionTestBase.cs b/test/EFCore.Relational.Specification.Tests/TransactionTestBase.cs index e04c1be051b..dd2a03c11c0 100644 --- a/test/EFCore.Relational.Specification.Tests/TransactionTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/TransactionTestBase.cs @@ -12,20 +12,12 @@ namespace Microsoft.EntityFrameworkCore; #nullable disable -public abstract class TransactionTestBase : IClassFixture +public abstract class TransactionTestBase : IClassFixture, IAsyncLifetime where TFixture : TransactionTestBase.TransactionFixtureBase, new() { protected TransactionTestBase(TFixture fixture) { Fixture = fixture; - Fixture.Reseed(); - - if (TestStore.ConnectionState == ConnectionState.Closed) - { - TestStore.OpenConnection(); - } - - Fixture.ListLoggerFactory.Log.Clear(); } protected TFixture Fixture { get; set; } @@ -1579,12 +1571,12 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con }); } - protected override void Seed(PoolableDbContext context) + protected override Task SeedAsync(PoolableDbContext context) { context.AddRange(Customers); context.AddRange(Orders); - context.SaveChanges(); + return context.SaveChangesAsync(); } } @@ -1616,4 +1608,19 @@ public override int GetHashCode() protected class TransactionCustomer : TransactionEntity; protected class TransactionOrder : TransactionEntity; + + public async Task InitializeAsync() + { + await Fixture.ReseedAsync(); + + if (TestStore.ConnectionState == ConnectionState.Closed) + { + TestStore.OpenConnection(); + } + + Fixture.ListLoggerFactory.Log.Clear(); + } + + public Task DisposeAsync() + => Task.CompletedTask; } diff --git a/test/EFCore.Relational.Specification.Tests/Update/JsonUpdateFixtureBase.cs b/test/EFCore.Relational.Specification.Tests/Update/JsonUpdateFixtureBase.cs index 474eed6949e..da28dda859c 100644 --- a/test/EFCore.Relational.Specification.Tests/Update/JsonUpdateFixtureBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Update/JsonUpdateFixtureBase.cs @@ -204,7 +204,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con base.OnModelCreating(modelBuilder, context); } - protected override void Seed(JsonQueryContext context) + protected override Task SeedAsync(JsonQueryContext context) { var jsonEntitiesBasic = JsonQueryData.CreateJsonEntitiesBasic(); var jsonEntitiesInheritance = JsonQueryData.CreateJsonEntitiesInheritance(); @@ -215,6 +215,7 @@ protected override void Seed(JsonQueryContext context) context.JsonEntitiesInheritance.AddRange(jsonEntitiesInheritance); context.JsonEntitiesAllTypes.AddRange(jsonEntitiesAllTypes); context.JsonEntitiesConverters.AddRange(jsonEntitiesConverters); - context.SaveChanges(); + + return context.SaveChangesAsync(); } } diff --git a/test/EFCore.Relational.Specification.Tests/Update/NonSharedModelUpdatesTestBase.cs b/test/EFCore.Relational.Specification.Tests/Update/NonSharedModelUpdatesTestBase.cs index f4ad7a2a519..23c3daadf32 100644 --- a/test/EFCore.Relational.Specification.Tests/Update/NonSharedModelUpdatesTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Update/NonSharedModelUpdatesTestBase.cs @@ -127,15 +127,6 @@ public class Blog public string? Name { get; set; } } - protected virtual void ExecuteWithStrategyInTransaction( - ContextFactory contextFactory, - Action testOperation, - Action? nestedTestOperation1 = null, - Action? nestedTestOperation2 = null, - Action? nestedTestOperation3 = null) - => TestHelpers.ExecuteWithStrategyInTransaction( - contextFactory.CreateContext, UseTransaction, testOperation, nestedTestOperation1, nestedTestOperation2, nestedTestOperation3); - protected virtual Task ExecuteWithStrategyInTransactionAsync( ContextFactory contextFactory, Func testOperation, diff --git a/test/EFCore.Relational.Specification.Tests/Update/StoreValueGenerationFixtureBase.cs b/test/EFCore.Relational.Specification.Tests/Update/StoreValueGenerationFixtureBase.cs index 26f6e6e0edf..3678679a873 100644 --- a/test/EFCore.Relational.Specification.Tests/Update/StoreValueGenerationFixtureBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Update/StoreValueGenerationFixtureBase.cs @@ -58,7 +58,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con } } - protected override void Seed(StoreValueGenerationContext context) + protected override Task SeedAsync(StoreValueGenerationContext context) { context.WithSomeDatabaseGenerated.AddRange(new StoreValueGenerationData { Data2 = 1 }, new StoreValueGenerationData { Data2 = 2 }); context.WithSomeDatabaseGenerated2.AddRange(new StoreValueGenerationData { Data2 = 1 }, new StoreValueGenerationData { Data2 = 2 }); @@ -91,13 +91,13 @@ protected override void Seed(StoreValueGenerationContext context) context.WithAllDatabaseGenerated.AddRange(new StoreValueGenerationData(), new StoreValueGenerationData()); context.WithAllDatabaseGenerated2.AddRange(new StoreValueGenerationData(), new StoreValueGenerationData()); - context.SaveChanges(); + return context.SaveChangesAsync(); } - public void Seed() + public async Task SeedAsync() { using var context = CreateContext(); - Seed(context); + await SeedAsync(context); } public virtual void CleanData() diff --git a/test/EFCore.Relational.Specification.Tests/Update/StoreValueGenerationTestBase.cs b/test/EFCore.Relational.Specification.Tests/Update/StoreValueGenerationTestBase.cs index 68a09f7913e..0fcecd9bfc0 100644 --- a/test/EFCore.Relational.Specification.Tests/Update/StoreValueGenerationTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Update/StoreValueGenerationTestBase.cs @@ -7,17 +7,12 @@ namespace Microsoft.EntityFrameworkCore.Update; #nullable disable -public abstract class StoreValueGenerationTestBase : IClassFixture +public abstract class StoreValueGenerationTestBase : IClassFixture, IAsyncLifetime where TFixture : StoreValueGenerationFixtureBase { protected StoreValueGenerationTestBase(TFixture fixture) { Fixture = fixture; - - fixture.CleanData(); - fixture.Seed(); - - ClearLog(); } #region Single operation @@ -387,4 +382,15 @@ protected enum GeneratedValues None, All } + + public async Task InitializeAsync() + { + Fixture.CleanData(); + await Fixture.SeedAsync(); + + ClearLog(); + } + + public Task DisposeAsync() + => Task.CompletedTask; } diff --git a/test/EFCore.Relational.Specification.Tests/Update/StoredProcedureUpdateTestBase.cs b/test/EFCore.Relational.Specification.Tests/Update/StoredProcedureUpdateTestBase.cs index aed4e176d6b..ad801d0c031 100644 --- a/test/EFCore.Relational.Specification.Tests/Update/StoredProcedureUpdateTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Update/StoredProcedureUpdateTestBase.cs @@ -1130,13 +1130,13 @@ protected void AssertSql(params string[] expected) protected virtual void ClearLog() => TestSqlLoggerFactory.Clear(); - protected virtual void CreateStoredProcedures(DbContext context, string createSprocSql) + protected virtual async Task CreateStoredProcedures(DbContext context, string createSprocSql) { foreach (var batch in new Regex("^GO", RegexOptions.IgnoreCase | RegexOptions.Multiline, TimeSpan.FromMilliseconds(1000.0)) .Split(createSprocSql).Where(b => !string.IsNullOrEmpty(b))) { - context.Database.ExecuteSqlRaw(batch); + await context.Database.ExecuteSqlRawAsync(batch); } } } diff --git a/test/EFCore.Relational.Specification.Tests/Update/UpdatesRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Update/UpdatesRelationalTestBase.cs index 0525d5f0736..fc71ab6f33d 100644 --- a/test/EFCore.Relational.Specification.Tests/Update/UpdatesRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Update/UpdatesRelationalTestBase.cs @@ -17,11 +17,11 @@ protected UpdatesRelationalTestBase(TFixture fixture) } [ConditionalFact] - public virtual void SaveChanges_works_for_entities_also_mapped_to_view() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task SaveChanges_works_for_entities_also_mapped_to_view() + => ExecuteWithStrategyInTransactionAsync( + async context => { - var category = context.Categories.Single(); + var category = await context.Categories.SingleAsync(); context.Add( new ProductTableWithView @@ -40,23 +40,22 @@ public virtual void SaveChanges_works_for_entities_also_mapped_to_view() DependentId = category.Id }); - context.SaveChanges(); - }, - context => + await context.SaveChangesAsync(); + }, async context => { - var viewProduct = context.Set().Single(); - var tableProduct = context.Set().Single(); + var viewProduct = await context.Set().SingleAsync(); + var tableProduct = await context.Set().SingleAsync(); Assert.Equal("Pear Cider", tableProduct.Name); Assert.Equal("Pear Cobler", viewProduct.Name); }); [ConditionalFact] - public virtual void SaveChanges_throws_for_entities_only_mapped_to_view() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task SaveChanges_throws_for_entities_only_mapped_to_view() + => ExecuteWithStrategyInTransactionAsync( + async context => { - var category = context.Categories.Single(); + var category = await context.Categories.SingleAsync(); context.Add( new ProductTableView { @@ -68,66 +67,62 @@ public virtual void SaveChanges_throws_for_entities_only_mapped_to_view() Assert.Equal( RelationalStrings.ReadonlyEntitySaved(nameof(ProductTableView)), - Assert.Throws(() => context.SaveChanges()).Message); + (await Assert.ThrowsAsync(() => context.SaveChangesAsync())).Message); }); [ConditionalFact] - public virtual void Save_with_shared_foreign_key() + public virtual Task Save_with_shared_foreign_key() { Guid productId = default; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var product = new ProductWithBytes(); context.Add(product); - context.SaveChanges(); + await context.SaveChangesAsync(); productId = product.Id; - }, - context => + }, async context => { - var product = context.ProductWithBytes.Find(productId)!; + var product = (await context.ProductWithBytes.FindAsync(productId))!; var category = new SpecialCategory { PrincipalId = 777 }; var productCategory = new ProductCategory { Category = category }; product.ProductCategories = new List { productCategory }; - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.True(category.Id > 0); Assert.Equal(category.Id, productCategory.CategoryId); - }, - context => + }, async context => { - var product = context.Set() + var product = await context.Set() .Include(p => ((ProductWithBytes)p).ProductCategories) .Include(p => ((Product)p).ProductCategories) .OfType() - .Single(); + .SingleAsync(); var productCategory = product.ProductCategories.Single(); - Assert.Equal(productCategory.CategoryId, context.Set().Single().CategoryId); - Assert.Equal(productCategory.CategoryId, context.Set().Single(c => c.PrincipalId == 777).Id); + Assert.Equal(productCategory.CategoryId, (await context.Set().SingleAsync()).CategoryId); + Assert.Equal(productCategory.CategoryId, (await context.Set().SingleAsync(c => c.PrincipalId == 777)).Id); }); } [ConditionalFact] - public virtual void Can_use_shared_columns_with_conversion() - => ExecuteWithStrategyInTransaction( + public virtual Task Can_use_shared_columns_with_conversion() + => ExecuteWithStrategyInTransactionAsync( context => { var person = new Person("1", null) { - Address = new Address { Country = Country.Eswatini, City = "Bulembu" }, - Country = "Eswatini" + Address = new Address { Country = Country.Eswatini, City = "Bulembu" }, Country = "Eswatini" }; context.Add(person); - context.SaveChanges(); - }, - context => + return context.SaveChangesAsync(); + }, async context => { - var person = context.Set().Single(); + var person = await context.Set().SingleAsync(); person.Address = new Address { Country = Country.Türkiye, @@ -135,11 +130,11 @@ public virtual void Can_use_shared_columns_with_conversion() ZipCode = 42100 }; - context.SaveChanges(); + await context.SaveChangesAsync(); }, - context => + async context => { - var person = context.Set().Single(); + var person = await context.Set().SingleAsync(); Assert.Equal(Country.Türkiye, person.Address!.Country); Assert.Equal("Konya", person.Address.City); @@ -149,36 +144,34 @@ public virtual void Can_use_shared_columns_with_conversion() }); [ConditionalFact] - public virtual void Swap_filtered_unique_index_values() + public virtual Task Swap_filtered_unique_index_values() { var productId1 = new Guid("984ade3c-2f7b-4651-a351-642e92ab7146"); var productId2 = new Guid("0edc9136-7eed-463b-9b97-bdb9648ab877"); - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var product1 = context.Products.Find(productId1)!; - var product2 = context.Products.Find(productId2)!; + var product1 = (await context.Products.FindAsync(productId1))!; + var product2 = (await context.Products.FindAsync(productId2))!; product2.Name = null; product2.Price = product1.Price; - context.SaveChanges(); - }, - context => + await context.SaveChangesAsync(); + }, async context => { - var product1 = context.Products.Find(productId1)!; - var product2 = context.Products.Find(productId2)!; + var product1 = (await context.Products.FindAsync(productId1))!; + var product2 = (await context.Products.FindAsync(productId2))!; product2.Name = product1.Name; product1.Name = null; - context.SaveChanges(); - }, - context => + await context.SaveChangesAsync(); + }, async context => { - var product1 = context.Products.Find(productId1)!; - var product2 = context.Products.Find(productId2)!; + var product1 = (await context.Products.FindAsync(productId1))!; + var product2 = (await context.Products.FindAsync(productId2))!; Assert.Equal(1.49M, product1.Price); Assert.Null(product1.Name); @@ -188,20 +181,20 @@ public virtual void Swap_filtered_unique_index_values() } [ConditionalFact] - public virtual void Update_non_indexed_values() + public virtual Task Update_non_indexed_values() { var productId1 = new Guid("984ade3c-2f7b-4651-a351-642e92ab7146"); var productId2 = new Guid("0edc9136-7eed-463b-9b97-bdb9648ab877"); - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var product1 = context.Products.Find(productId1)!; - var product2 = context.Products.Find(productId2)!; + var product1 = (await context.Products.FindAsync(productId1))!; + var product2 = (await context.Products.FindAsync(productId2))!; product2.Price = product1.Price; - context.SaveChanges(); + await context.SaveChangesAsync(); }, context => { @@ -221,12 +214,11 @@ public virtual void Update_non_indexed_values() context.Attach(product1).Property(p => p.DependentId).IsModified = true; context.Attach(product2).Property(p => p.DependentId).IsModified = true; - context.SaveChanges(); - }, - context => + return context.SaveChangesAsync(); + }, async context => { - var product1 = context.Products.Find(productId1)!; - var product2 = context.Products.Find(productId2)!; + var product1 = (await context.Products.FindAsync(productId1))!; + var product2 = (await context.Products.FindAsync(productId2))!; Assert.Equal(1.49M, product1.Price); Assert.Null(product1.DependentId); diff --git a/test/EFCore.Specification.Tests/BuiltInDataTypesTestBase.cs b/test/EFCore.Specification.Tests/BuiltInDataTypesTestBase.cs index bf6296ca6ef..e1bb59eb5c1 100644 --- a/test/EFCore.Specification.Tests/BuiltInDataTypesTestBase.cs +++ b/test/EFCore.Specification.Tests/BuiltInDataTypesTestBase.cs @@ -66,7 +66,7 @@ public virtual async Task Can_filter_projection_with_inline_enum_variable(bool a } [ConditionalFact] - public virtual void Can_perform_query_with_max_length() + public virtual async Task Can_perform_query_with_max_length() { var shortString = "Sky"; var shortBinary = new byte[] { 8, 8, 7, 8, 7 }; @@ -90,32 +90,35 @@ public virtual void Can_perform_query_with_max_length() ByteArray9000 = longBinary }); - Assert.Equal(1, context.SaveChanges()); + Assert.Equal(1, await context.SaveChangesAsync()); } using (var context = CreateContext()) { Assert.NotNull( - context.Set().Where(e => e.Id == 799 && e.String3 == shortString).ToList().SingleOrDefault()); + (await context.Set().Where(e => e.Id == 799 && e.String3 == shortString).ToListAsync()) + .SingleOrDefault()); Assert.NotNull( - context.Set().Where(e => e.Id == 799 && e.String9000 == longString).ToList().SingleOrDefault()); + (await context.Set().Where(e => e.Id == 799 && e.String9000 == longString).ToListAsync()) + .SingleOrDefault()); Assert.NotNull( - context.Set().Where(e => e.Id == 799 && e.StringUnbounded == longString).ToList().SingleOrDefault()); + (await context.Set().Where(e => e.Id == 799 && e.StringUnbounded == longString).ToListAsync()) + .SingleOrDefault()); Assert.NotNull( - context.Set().Where(e => e.Id == 799 && e.ByteArray5 == shortBinary).ToList() - .SingleOrDefault()); + (await context.Set().Where(e => e.Id == 799 && e.ByteArray5 == shortBinary).ToListAsync()) + .SingleOrDefault()); Assert.NotNull( - context.Set().Where(e => e.Id == 799 && e.ByteArray9000 == longBinary).ToList() - .SingleOrDefault()); + (await context.Set().Where(e => e.Id == 799 && e.ByteArray9000 == longBinary).ToListAsync()) + .SingleOrDefault()); } } [ConditionalFact] - public virtual void Can_perform_query_with_ansi_strings_test() + public virtual async Task Can_perform_query_with_ansi_strings_test() { var shortString = Fixture.SupportsUnicodeToAnsiConversion ? "Ϩky" : "sky"; var longString = Fixture.SupportsUnicodeToAnsiConversion @@ -135,29 +138,33 @@ public virtual void Can_perform_query_with_ansi_strings_test() StringUnicode = shortString }); - Assert.Equal(1, context.SaveChanges()); + Assert.Equal(1, await context.SaveChangesAsync()); } using (var context = CreateContext()) { Assert.NotNull( - context.Set().Where(e => e.Id == 799 && e.StringDefault == shortString).ToList().SingleOrDefault()); + (await context.Set().Where(e => e.Id == 799 && e.StringDefault == shortString).ToListAsync()) + .SingleOrDefault()); Assert.NotNull( - context.Set().Where(e => e.Id == 799 && e.StringAnsi == shortString).ToList().SingleOrDefault()); + (await context.Set().Where(e => e.Id == 799 && e.StringAnsi == shortString).ToListAsync()) + .SingleOrDefault()); Assert.NotNull( - context.Set().Where(e => e.Id == 799 && e.StringAnsi3 == shortString).ToList().SingleOrDefault()); + (await context.Set().Where(e => e.Id == 799 && e.StringAnsi3 == shortString).ToListAsync()) + .SingleOrDefault()); if (Fixture.SupportsLargeStringComparisons) { Assert.NotNull( - context.Set().Where(e => e.Id == 799 && e.StringAnsi9000 == longString).ToList() - .SingleOrDefault()); + (await context.Set().Where(e => e.Id == 799 && e.StringAnsi9000 == longString).ToListAsync()) + .SingleOrDefault()); } Assert.NotNull( - context.Set().Where(e => e.Id == 799 && e.StringUnicode == shortString).ToList().SingleOrDefault()); + (await context.Set().Where(e => e.Id == 799 && e.StringUnicode == shortString).ToListAsync()) + .SingleOrDefault()); - var entity = context.Set().Where(e => e.Id == 799).ToList().Single(); + var entity = (await context.Set().Where(e => e.Id == 799).ToListAsync()).Single(); Assert.Equal(shortString, entity.StringDefault); Assert.Equal(shortString, entity.StringUnicode); @@ -179,93 +186,95 @@ public virtual void Can_perform_query_with_ansi_strings_test() } [ConditionalFact] - public virtual void Can_query_using_any_data_type() + public virtual async Task Can_query_using_any_data_type() { using var context = CreateContext(); var source = AddTestBuiltInDataTypes(context.Set()); - Assert.Equal(1, context.SaveChanges()); + Assert.Equal(1, await context.SaveChangesAsync()); - QueryBuiltInDataTypesTest(source); + await QueryBuiltInDataTypesTest(source); } [ConditionalFact] - public virtual void Can_query_using_any_data_type_shadow() + public virtual async Task Can_query_using_any_data_type_shadow() { using var context = CreateContext(); var source = AddTestBuiltInDataTypes(context.Set()); - Assert.Equal(1, context.SaveChanges()); + Assert.Equal(1, await context.SaveChangesAsync()); - QueryBuiltInDataTypesTest(source); + await QueryBuiltInDataTypesTest(source); } - private void QueryBuiltInDataTypesTest(EntityEntry source) + private async Task QueryBuiltInDataTypesTest(EntityEntry source) where TEntity : BuiltInDataTypesBase { using var context = CreateContext(); var set = context.Set(); - var entity = set.Where(e => e.Id == 11).ToList().Single(); + var entity = (await set.Where(e => e.Id == 11).ToListAsync()).Single(); var entityType = context.Model.FindEntityType(typeof(TEntity)); var param1 = (short)-1234; Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.TestInt16)) == param1).ToList().Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.TestInt16)) == param1).ToListAsync()) + .Single()); var param2 = -123456789; Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.TestInt32)) == param2).ToList().Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.TestInt32)) == param2).ToListAsync()).Single()); var param3 = -1234567890123456789L; if (Fixture.IntegerPrecision == 64) { Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.TestInt64)) == param3).ToList().Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.TestInt64)) == param3).ToListAsync()) + .Single()); } double? param4 = -1.23456789; if (Fixture.StrictEquality) { Assert.Same( - entity, set.Where( + entity, (await set.Where( e => e.Id == 11 - && EF.Property(e, nameof(BuiltInDataTypes.TestDouble)) == param4).ToList().Single()); + && EF.Property(e, nameof(BuiltInDataTypes.TestDouble)) == param4).ToListAsync()).Single()); } else if (Fixture.SupportsDecimalComparisons) { double? param4l = -1.234567891; double? param4h = -1.234567889; Assert.Same( - entity, set.Where( + entity, (await set.Where( e => e.Id == 11 && (EF.Property(e, nameof(BuiltInDataTypes.TestDouble)) == param4 || (EF.Property(e, nameof(BuiltInDataTypes.TestDouble)) > param4l && EF.Property(e, nameof(BuiltInDataTypes.TestDouble)) < param4h))) - .ToList().Single()); + .ToListAsync()).Single()); } var param5 = -1234567890.01M; Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.TestDecimal)) == param5).ToList() - .Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.TestDecimal)) == param5).ToListAsync()) + .Single()); var param6 = Fixture.DefaultDateTime; Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.TestDateTime)) == param6).ToList() - .Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.TestDateTime)) == param6).ToListAsync()) + .Single()); if (entityType.FindProperty(nameof(BuiltInDataTypes.TestDateTimeOffset)) != null) { var param7 = new DateTimeOffset(new DateTime(), TimeSpan.FromHours(-8.0)); Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.TestDateTimeOffset)) == param7) - .ToList().Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.TestDateTimeOffset)) == param7) + .ToListAsync()).Single()); } if (entityType.FindProperty(nameof(BuiltInDataTypes.TestTimeSpan)) != null) @@ -273,8 +282,9 @@ private void QueryBuiltInDataTypesTest(EntityEntry source) var param8 = new TimeSpan(0, 10, 9, 8, 7); Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.TestTimeSpan)) == param8).ToList() - .Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.TestTimeSpan)) == param8) + .ToListAsync()) + .Single()); } if (entityType.FindProperty(nameof(BuiltInDataTypes.TestDateOnly)) != null) @@ -282,8 +292,9 @@ private void QueryBuiltInDataTypesTest(EntityEntry source) var param9 = new DateOnly(2020, 3, 1); Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.TestDateOnly)) == param9).ToList() - .Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.TestDateOnly)) == param9) + .ToListAsync()) + .Single()); } if (entityType.FindProperty(nameof(BuiltInDataTypes.TestTimeOnly)) != null) @@ -291,64 +302,71 @@ private void QueryBuiltInDataTypesTest(EntityEntry source) var param10 = new TimeOnly(12, 30, 45, 123); Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.TestTimeOnly)) == param10).ToList() - .Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.TestTimeOnly)) == param10) + .ToListAsync()) + .Single()); } var param11 = -1.234F; if (Fixture.StrictEquality) { Assert.Same( - entity, set.Where( + entity, (await set.Where( e => e.Id == 11 - && EF.Property(e, nameof(BuiltInDataTypes.TestSingle)) == param11).ToList().Single()); + && EF.Property(e, nameof(BuiltInDataTypes.TestSingle)) == param11).ToListAsync()).Single()); } else if (Fixture.SupportsDecimalComparisons) { var param11l = -1.2341F; var param11h = -1.2339F; Assert.Same( - entity, set.Where( + entity, (await set.Where( e => e.Id == 11 && (EF.Property(e, nameof(BuiltInDataTypes.TestSingle)) == param11 || (EF.Property(e, nameof(BuiltInDataTypes.TestSingle)) > param11l - && EF.Property(e, nameof(BuiltInDataTypes.TestSingle)) < param11h))).ToList().Single()); + && EF.Property(e, nameof(BuiltInDataTypes.TestSingle)) < param11h))).ToListAsync()).Single()); } var param12 = true; Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.TestBoolean)) == param12).ToList().Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.TestBoolean)) == param12).ToListAsync()) + .Single()); if (entityType.FindProperty(nameof(BuiltInDataTypes.TestByte)) != null) { var param13 = (byte)255; Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.TestByte)) == param13).ToList().Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.TestByte)) == param13).ToListAsync()) + .Single()); } var param14 = Enum64.SomeValue; Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.Enum64)) == param14).ToList().Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.Enum64)) == param14).ToListAsync()) + .Single()); var param15 = Enum32.SomeValue; Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.Enum32)) == param15).ToList().Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.Enum32)) == param15).ToListAsync()) + .Single()); var param16 = Enum16.SomeValue; Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.Enum16)) == param16).ToList().Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.Enum16)) == param16).ToListAsync()) + .Single()); if (entityType.FindProperty(nameof(BuiltInDataTypes.Enum8)) != null) { var param17 = Enum8.SomeValue; Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.Enum8)) == param17).ToList().Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.Enum8)) == param17).ToListAsync()) + .Single()); } if (entityType.FindProperty(nameof(BuiltInDataTypes.TestUnsignedInt16)) != null) @@ -356,8 +374,9 @@ private void QueryBuiltInDataTypesTest(EntityEntry source) var param18 = (ushort)1234; Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.TestUnsignedInt16)) == param18).ToList() - .Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.TestUnsignedInt16)) == param18) + .ToListAsync()) + .Single()); } if (entityType.FindProperty(nameof(BuiltInDataTypes.TestUnsignedInt32)) != null) @@ -365,8 +384,9 @@ private void QueryBuiltInDataTypesTest(EntityEntry source) var param19 = 1234565789U; Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.TestUnsignedInt32)) == param19).ToList() - .Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.TestUnsignedInt32)) == param19) + .ToListAsync()) + .Single()); } if (entityType.FindProperty(nameof(BuiltInDataTypes.TestUnsignedInt64)) != null) @@ -374,8 +394,9 @@ private void QueryBuiltInDataTypesTest(EntityEntry source) var param20 = 1234567890123456789UL; Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.TestUnsignedInt64)) == param20).ToList() - .Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.TestUnsignedInt64)) == param20) + .ToListAsync()) + .Single()); } if (entityType.FindProperty(nameof(BuiltInDataTypes.TestCharacter)) != null) @@ -383,8 +404,8 @@ private void QueryBuiltInDataTypesTest(EntityEntry source) var param21 = 'a'; Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.TestCharacter)) == param21).ToList() - .Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.TestCharacter)) == param21).ToListAsync()) + .Single()); } if (entityType.FindProperty(nameof(BuiltInDataTypes.TestSignedByte)) != null) @@ -392,8 +413,9 @@ private void QueryBuiltInDataTypesTest(EntityEntry source) var param22 = (sbyte)-128; Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.TestSignedByte)) == param22).ToList() - .Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.TestSignedByte)) == param22) + .ToListAsync()) + .Single()); } if (entityType.FindProperty(nameof(BuiltInDataTypes.EnumU64)) != null) @@ -401,8 +423,8 @@ private void QueryBuiltInDataTypesTest(EntityEntry source) var param23 = EnumU64.SomeValue; Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.EnumU64)) == param23).ToList() - .Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.EnumU64)) == param23).ToListAsync()) + .Single()); } if (entityType.FindProperty(nameof(BuiltInDataTypes.EnumU32)) != null) @@ -410,8 +432,8 @@ private void QueryBuiltInDataTypesTest(EntityEntry source) var param24 = EnumU32.SomeValue; Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.EnumU32)) == param24).ToList() - .Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.EnumU32)) == param24).ToListAsync()) + .Single()); } if (entityType.FindProperty(nameof(BuiltInDataTypes.EnumU16)) != null) @@ -419,8 +441,8 @@ private void QueryBuiltInDataTypesTest(EntityEntry source) var param25 = EnumU16.SomeValue; Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.EnumU16)) == param25).ToList() - .Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.EnumU16)) == param25).ToListAsync()) + .Single()); } if (entityType.FindProperty(nameof(BuiltInDataTypes.EnumS8)) != null) @@ -428,7 +450,8 @@ private void QueryBuiltInDataTypesTest(EntityEntry source) var param26 = EnumS8.SomeValue; Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.EnumS8)) == param26).ToList().Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.EnumS8)) == param26).ToListAsync()) + .Single()); } if (UnwrapNullableType(entityType.FindProperty(nameof(BuiltInDataTypes.Enum64))?.GetProviderClrType()) == typeof(long)) @@ -436,12 +459,13 @@ private void QueryBuiltInDataTypesTest(EntityEntry source) var param27 = 1; Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.Enum64)) == (Enum64)param27).ToList() - .Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.Enum64)) == (Enum64)param27) + .ToListAsync()) + .Single()); Assert.Same( entity, - set.Where(e => e.Id == 11 && (int)EF.Property(e, nameof(BuiltInDataTypes.Enum64)) == param27).ToList() - .Single()); + (await set.Where(e => e.Id == 11 && (int)EF.Property(e, nameof(BuiltInDataTypes.Enum64)) == param27).ToListAsync()) + .Single()); } if (UnwrapNullableType(entityType.FindProperty(nameof(BuiltInDataTypes.Enum32))?.GetProviderClrType()) == typeof(int)) @@ -449,12 +473,13 @@ private void QueryBuiltInDataTypesTest(EntityEntry source) var param28 = 1; Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.Enum32)) == (Enum32)param28).ToList() - .Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.Enum32)) == (Enum32)param28) + .ToListAsync()) + .Single()); Assert.Same( entity, - set.Where(e => e.Id == 11 && (int)EF.Property(e, nameof(BuiltInDataTypes.Enum32)) == param28).ToList() - .Single()); + (await set.Where(e => e.Id == 11 && (int)EF.Property(e, nameof(BuiltInDataTypes.Enum32)) == param28).ToListAsync()) + .Single()); } if (UnwrapNullableType(entityType.FindProperty(nameof(BuiltInDataTypes.Enum16))?.GetProviderClrType()) == typeof(short)) @@ -462,12 +487,13 @@ private void QueryBuiltInDataTypesTest(EntityEntry source) var param29 = 1; Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.Enum16)) == (Enum16)param29).ToList() - .Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.Enum16)) == (Enum16)param29) + .ToListAsync()) + .Single()); Assert.Same( entity, - set.Where(e => e.Id == 11 && (int)EF.Property(e, nameof(BuiltInDataTypes.Enum16)) == param29).ToList() - .Single()); + (await set.Where(e => e.Id == 11 && (int)EF.Property(e, nameof(BuiltInDataTypes.Enum16)) == param29).ToListAsync()) + .Single()); } if (UnwrapNullableType(entityType.FindProperty(nameof(BuiltInDataTypes.Enum8))?.GetProviderClrType()) == typeof(byte)) @@ -475,12 +501,12 @@ private void QueryBuiltInDataTypesTest(EntityEntry source) var param30 = 1; Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.Enum8)) == (Enum8)param30).ToList() - .Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInDataTypes.Enum8)) == (Enum8)param30).ToListAsync()) + .Single()); Assert.Same( entity, - set.Where(e => e.Id == 11 && (int)EF.Property(e, nameof(BuiltInDataTypes.Enum8)) == param30).ToList() - .Single()); + (await set.Where(e => e.Id == 11 && (int)EF.Property(e, nameof(BuiltInDataTypes.Enum8)) == param30).ToListAsync()) + .Single()); } foreach (var propertyEntry in context.Entry(entity).Properties) @@ -539,96 +565,96 @@ protected EntityEntry AddTestBuiltInDataTypes(DbSet s } [ConditionalFact] - public virtual void Can_query_using_any_nullable_data_type() + public virtual async Task Can_query_using_any_nullable_data_type() { using var context = CreateContext(); var source = AddTestBuiltInNullableDataTypes(context.Set()); - Assert.Equal(1, context.SaveChanges()); + Assert.Equal(1, await context.SaveChangesAsync()); - QueryBuiltInNullableDataTypesTest(source); + await QueryBuiltInNullableDataTypesTest(source); } [ConditionalFact] - public virtual void Can_query_using_any_data_type_nullable_shadow() + public virtual async Task Can_query_using_any_data_type_nullable_shadow() { using var context = CreateContext(); var source = AddTestBuiltInNullableDataTypes(context.Set()); - Assert.Equal(1, context.SaveChanges()); + Assert.Equal(1, await context.SaveChangesAsync()); - QueryBuiltInNullableDataTypesTest(source); + await QueryBuiltInNullableDataTypesTest(source); } - private void QueryBuiltInNullableDataTypesTest(EntityEntry source) + private async Task QueryBuiltInNullableDataTypesTest(EntityEntry source) where TEntity : BuiltInNullableDataTypesBase { using var context = CreateContext(); var set = context.Set(); - var entity = set.Where(e => e.Id == 11).ToList().Single(); + var entity = (await set.Where(e => e.Id == 11).ToListAsync()).Single(); var entityType = context.Model.FindEntityType(typeof(TEntity)); short? param1 = -1234; Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInNullableDataTypes.TestNullableInt16)) == param1) - .ToList().Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInNullableDataTypes.TestNullableInt16)) == param1) + .ToListAsync()).Single()); int? param2 = -123456789; Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInNullableDataTypes.TestNullableInt32)) == param2) - .ToList().Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInNullableDataTypes.TestNullableInt32)) == param2) + .ToListAsync()).Single()); long? param3 = -1234567890123456789L; Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInNullableDataTypes.TestNullableInt64)) == param3) - .ToList().Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInNullableDataTypes.TestNullableInt64)) == param3) + .ToListAsync()).Single()); double? param4 = -1.23456789; if (Fixture.StrictEquality) { Assert.Same( - entity, set.Where( - e => e.Id == 11 - && EF.Property(e, nameof(BuiltInNullableDataTypes.TestNullableDouble)) == param4).ToList() - .Single()); + entity, (await set.Where( + e => e.Id == 11 + && EF.Property(e, nameof(BuiltInNullableDataTypes.TestNullableDouble)) == param4).ToListAsync()) + .Single()); } else if (Fixture.SupportsDecimalComparisons) { double? param4l = -1.234567891; double? param4h = -1.234567889; Assert.Same( - entity, set.Where( + entity, (await set.Where( e => e.Id == 11 && (EF.Property(e, nameof(BuiltInNullableDataTypes.TestNullableDouble)) == param4 || (EF.Property(e, nameof(BuiltInNullableDataTypes.TestNullableDouble)) > param4l && EF.Property(e, nameof(BuiltInNullableDataTypes.TestNullableDouble)) < param4h))) - .ToList().Single()); + .ToListAsync()).Single()); } decimal? param5 = -1234567890.01M; Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInNullableDataTypes.TestNullableDecimal)) == param5) - .ToList().Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInNullableDataTypes.TestNullableDecimal)) == param5) + .ToListAsync()).Single()); DateTime? param6 = Fixture.DefaultDateTime; Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInNullableDataTypes.TestNullableDateTime)) == param6) - .ToList().Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInNullableDataTypes.TestNullableDateTime)) == param6) + .ToListAsync()).Single()); if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.TestNullableDateTimeOffset)) != null) { DateTimeOffset? param7 = new DateTimeOffset(new DateTime(), TimeSpan.FromHours(-8.0)); Assert.Same( entity, - set.Where( + (await set.Where( e => e.Id == 11 && EF.Property(e, nameof(BuiltInNullableDataTypes.TestNullableDateTimeOffset)) - == param7).ToList().Single()); + == param7).ToListAsync()).Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.TestNullableTimeSpan)) != null) @@ -636,11 +662,11 @@ private void QueryBuiltInNullableDataTypesTest(EntityEntry sou TimeSpan? param8 = new TimeSpan(0, 10, 9, 8, 7); Assert.Same( entity, - set.Where( + (await set.Where( e => e.Id == 11 && EF.Property(e, nameof(BuiltInNullableDataTypes.TestNullableTimeSpan)) == param8) - .ToList().Single()); + .ToListAsync()).Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.TestNullableDateOnly)) != null) @@ -648,11 +674,11 @@ private void QueryBuiltInNullableDataTypesTest(EntityEntry sou DateOnly? param9 = new DateOnly(2020, 3, 1); Assert.Same( entity, - set.Where( + (await set.Where( e => e.Id == 11 && EF.Property(e, nameof(BuiltInNullableDataTypes.TestNullableDateOnly)) == param9) - .ToList().Single()); + .ToListAsync()).Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.TestNullableTimeOnly)) != null) @@ -660,75 +686,76 @@ private void QueryBuiltInNullableDataTypesTest(EntityEntry sou TimeOnly? param10 = new TimeOnly(12, 30, 45, 123); Assert.Same( entity, - set.Where( + (await set.Where( e => e.Id == 11 && EF.Property(e, nameof(BuiltInNullableDataTypes.TestNullableTimeOnly)) == param10) - .ToList().Single()); + .ToListAsync()).Single()); } float? param11 = -1.234F; if (Fixture.StrictEquality) { Assert.Same( - entity, set.Where( - e => e.Id == 11 - && EF.Property(e, nameof(BuiltInNullableDataTypes.TestNullableSingle)) == param11).ToList() - .Single()); + entity, (await set.Where( + e => e.Id == 11 + && EF.Property(e, nameof(BuiltInNullableDataTypes.TestNullableSingle)) == param11).ToListAsync()) + .Single()); } else if (Fixture.SupportsDecimalComparisons) { float? param11l = -1.2341F; float? param11h = -1.2339F; Assert.Same( - entity, set.Where( + entity, (await set.Where( e => e.Id == 11 && (EF.Property(e, nameof(BuiltInNullableDataTypes.TestNullableSingle)) == param11 || (EF.Property(e, nameof(BuiltInNullableDataTypes.TestNullableSingle)) > param11l && EF.Property(e, nameof(BuiltInNullableDataTypes.TestNullableSingle)) < param11h))) - .ToList().Single()); + .ToListAsync()).Single()); } bool? param12 = true; Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInNullableDataTypes.TestNullableBoolean)) == param12) - .ToList().Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInNullableDataTypes.TestNullableBoolean)) == param12) + .ToListAsync()).Single()); if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.TestNullableByte)) != null) { byte? param13 = 255; Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInNullableDataTypes.TestNullableByte)) == param13) - .ToList().Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInNullableDataTypes.TestNullableByte)) == param13) + .ToListAsync()).Single()); } Enum64? param14 = Enum64.SomeValue; Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInNullableDataTypes.Enum64)) == param14).ToList() - .Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInNullableDataTypes.Enum64)) == param14).ToListAsync()) + .Single()); Enum32? param15 = Enum32.SomeValue; Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInNullableDataTypes.Enum32)) == param15).ToList() - .Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInNullableDataTypes.Enum32)) == param15).ToListAsync()) + .Single()); Enum16? param16 = Enum16.SomeValue; Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInNullableDataTypes.Enum16)) == param16).ToList() - .Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInNullableDataTypes.Enum16)) == param16).ToListAsync()) + .Single()); if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.Enum8)) != null) { Enum8? param17 = Enum8.SomeValue; Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInNullableDataTypes.Enum8)) == param17).ToList() - .Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInNullableDataTypes.Enum8)) == param17) + .ToListAsync()) + .Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.TestNullableUnsignedInt16)) != null) @@ -736,10 +763,10 @@ private void QueryBuiltInNullableDataTypesTest(EntityEntry sou ushort? param18 = 1234; Assert.Same( entity, - set.Where( + (await set.Where( e => e.Id == 11 && EF.Property(e, nameof(BuiltInNullableDataTypes.TestNullableUnsignedInt16)) - == param18).ToList().Single()); + == param18).ToListAsync()).Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.TestNullableUnsignedInt32)) != null) @@ -747,11 +774,11 @@ private void QueryBuiltInNullableDataTypesTest(EntityEntry sou uint? param19 = 1234565789U; Assert.Same( entity, - set.Where( + (await set.Where( e => e.Id == 11 && EF.Property(e, nameof(BuiltInNullableDataTypes.TestNullableUnsignedInt32)) == param19) - .ToList().Single()); + .ToListAsync()).Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.TestNullableUnsignedInt64)) != null) @@ -759,11 +786,11 @@ private void QueryBuiltInNullableDataTypesTest(EntityEntry sou ulong? param20 = 1234567890123456789UL; Assert.Same( entity, - set.Where( + (await set.Where( e => e.Id == 11 && EF.Property( e, nameof(BuiltInNullableDataTypes.TestNullableUnsignedInt64)) - == param20).ToList().Single()); + == param20).ToListAsync()).Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.TestNullableCharacter)) != null) @@ -771,9 +798,9 @@ private void QueryBuiltInNullableDataTypesTest(EntityEntry sou char? param21 = 'a'; Assert.Same( entity, - set.Where( + (await set.Where( e => e.Id == 11 && EF.Property(e, nameof(BuiltInNullableDataTypes.TestNullableCharacter)) == param21) - .ToList().Single()); + .ToListAsync()).Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.TestNullableSignedByte)) != null) @@ -781,11 +808,11 @@ private void QueryBuiltInNullableDataTypesTest(EntityEntry sou sbyte? param22 = -128; Assert.Same( entity, - set.Where( + (await set.Where( e => e.Id == 11 && EF.Property(e, nameof(BuiltInNullableDataTypes.TestNullableSignedByte)) == param22) - .ToList().Single()); + .ToListAsync()).Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.EnumU64)) != null) @@ -793,8 +820,9 @@ private void QueryBuiltInNullableDataTypesTest(EntityEntry sou var param23 = EnumU64.SomeValue; Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInNullableDataTypes.EnumU64)) == param23).ToList() - .Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInNullableDataTypes.EnumU64)) == param23) + .ToListAsync()) + .Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.EnumU32)) != null) @@ -802,8 +830,9 @@ private void QueryBuiltInNullableDataTypesTest(EntityEntry sou var param24 = EnumU32.SomeValue; Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInNullableDataTypes.EnumU32)) == param24).ToList() - .Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInNullableDataTypes.EnumU32)) == param24) + .ToListAsync()) + .Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.EnumU16)) != null) @@ -811,8 +840,9 @@ private void QueryBuiltInNullableDataTypesTest(EntityEntry sou var param25 = EnumU16.SomeValue; Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInNullableDataTypes.EnumU16)) == param25).ToList() - .Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInNullableDataTypes.EnumU16)) == param25) + .ToListAsync()) + .Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.EnumS8)) != null) @@ -820,8 +850,9 @@ private void QueryBuiltInNullableDataTypesTest(EntityEntry sou var param26 = EnumS8.SomeValue; Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInNullableDataTypes.EnumS8)) == param26).ToList() - .Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInNullableDataTypes.EnumS8)) == param26) + .ToListAsync()) + .Single()); } if (UnwrapNullableType(entityType.FindProperty(nameof(BuiltInNullableDataTypes.Enum64))?.GetProviderClrType()) @@ -830,12 +861,12 @@ private void QueryBuiltInNullableDataTypesTest(EntityEntry sou int? param27 = 1; Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInNullableDataTypes.Enum64)) == (Enum64)param27) - .ToList().Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInNullableDataTypes.Enum64)) == (Enum64)param27) + .ToListAsync()).Single()); Assert.Same( entity, - set.Where(e => e.Id == 11 && (int)EF.Property(e, nameof(BuiltInNullableDataTypes.Enum64)) == param27) - .ToList().Single()); + (await set.Where(e => e.Id == 11 && (int)EF.Property(e, nameof(BuiltInNullableDataTypes.Enum64)) == param27) + .ToListAsync()).Single()); } if (UnwrapNullableType(entityType.FindProperty(nameof(BuiltInNullableDataTypes.Enum32))?.GetProviderClrType()) @@ -844,12 +875,12 @@ private void QueryBuiltInNullableDataTypesTest(EntityEntry sou int? param28 = 1; Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInNullableDataTypes.Enum32)) == (Enum32)param28) - .ToList().Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInNullableDataTypes.Enum32)) == (Enum32)param28) + .ToListAsync()).Single()); Assert.Same( entity, - set.Where(e => e.Id == 11 && (int)EF.Property(e, nameof(BuiltInNullableDataTypes.Enum32)) == param28) - .ToList().Single()); + (await set.Where(e => e.Id == 11 && (int)EF.Property(e, nameof(BuiltInNullableDataTypes.Enum32)) == param28) + .ToListAsync()).Single()); } if (UnwrapNullableType(entityType.FindProperty(nameof(BuiltInNullableDataTypes.Enum16))?.GetProviderClrType()) @@ -858,12 +889,12 @@ private void QueryBuiltInNullableDataTypesTest(EntityEntry sou int? param29 = 1; Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInNullableDataTypes.Enum16)) == (Enum16)param29) - .ToList().Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInNullableDataTypes.Enum16)) == (Enum16)param29) + .ToListAsync()).Single()); Assert.Same( entity, - set.Where(e => e.Id == 11 && (int)EF.Property(e, nameof(BuiltInNullableDataTypes.Enum16)) == param29) - .ToList().Single()); + (await set.Where(e => e.Id == 11 && (int)EF.Property(e, nameof(BuiltInNullableDataTypes.Enum16)) == param29) + .ToListAsync()).Single()); } if (UnwrapNullableType(entityType.FindProperty(nameof(BuiltInNullableDataTypes.Enum8))?.GetProviderClrType()) @@ -872,12 +903,12 @@ private void QueryBuiltInNullableDataTypesTest(EntityEntry sou int? param30 = 1; Assert.Same( entity, - set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInNullableDataTypes.Enum8)) == (Enum8)param30) - .ToList().Single()); + (await set.Where(e => e.Id == 11 && EF.Property(e, nameof(BuiltInNullableDataTypes.Enum8)) == (Enum8)param30) + .ToListAsync()).Single()); Assert.Same( entity, - set.Where(e => e.Id == 11 && (int)EF.Property(e, nameof(BuiltInNullableDataTypes.Enum8)) == param30) - .ToList().Single()); + (await set.Where(e => e.Id == 11 && (int)EF.Property(e, nameof(BuiltInNullableDataTypes.Enum8)) == param30) + .ToListAsync()).Single()); } foreach (var propertyEntry in context.Entry(entity).Properties) @@ -936,7 +967,7 @@ protected virtual EntityEntry AddTestBuiltInNullableDataTypes( } [ConditionalFact] - public virtual void Can_query_using_any_nullable_data_type_as_literal() + public virtual async Task Can_query_using_any_nullable_data_type_as_literal() { using (var context = CreateContext()) { @@ -973,311 +1004,349 @@ public virtual void Can_query_using_any_nullable_data_type_as_literal() EnumS8 = EnumS8.SomeValue }); - Assert.Equal(1, context.SaveChanges()); + Assert.Equal(1, await context.SaveChangesAsync()); } using (var context = CreateContext()) { - var entity = context.Set().Where(e => e.Id == 12).ToList().Single(); + var entity = (await context.Set().Where(e => e.Id == 12).ToListAsync()).Single(); var entityType = context.Model.FindEntityType(typeof(BuiltInNullableDataTypes)); Assert.Same( entity, - context.Set().Where(e => e.Id == 12 && e.TestNullableInt16 == -1234).ToList().Single()); + (await context.Set().Where(e => e.Id == 12 && e.TestNullableInt16 == -1234).ToListAsync()) + .Single()); Assert.Same( entity, - context.Set().Where(e => e.Id == 12 && e.TestNullableInt32 == -123456789).ToList().Single()); + (await context.Set().Where(e => e.Id == 12 && e.TestNullableInt32 == -123456789).ToListAsync()) + .Single()); Assert.Same( entity, - context.Set().Where(e => e.Id == 12 && e.TestNullableInt64 == -1234567890123456789L).ToList() - .Single()); + (await context.Set().Where(e => e.Id == 12 && e.TestNullableInt64 == -1234567890123456789L) + .ToListAsync()) + .Single()); if (Fixture.StrictEquality) { Assert.Same( entity, - context.Set().Where(e => e.Id == 12 && e.TestNullableDouble == -1.23456789).ToList() - .Single()); + (await context.Set().Where(e => e.Id == 12 && e.TestNullableDouble == -1.23456789) + .ToListAsync()) + .Single()); } else if (Fixture.SupportsDecimalComparisons) { Assert.Same( entity, - context.Set().Where( + (await context.Set().Where( e => e.Id == 12 && -e.TestNullableDouble + -1.23456789 < 1E-5 - && -e.TestNullableDouble + -1.23456789 > -1E-5).ToList().Single()); + && -e.TestNullableDouble + -1.23456789 > -1E-5).ToListAsync()).Single()); } Assert.Same( entity, - context.Set().Where(e => e.Id == 12 && e.TestNullableDouble != 1E18).ToList().Single()); + (await context.Set().Where(e => e.Id == 12 && e.TestNullableDouble != 1E18).ToListAsync()) + .Single()); Assert.Same( entity, - context.Set().Where(e => e.Id == 12 && e.TestNullableDecimal == -1234567890.01M).ToList() - .Single()); + (await context.Set().Where(e => e.Id == 12 && e.TestNullableDecimal == -1234567890.01M) + .ToListAsync()) + .Single()); Assert.Same( entity, - context.Set().Where(e => e.Id == 12 && e.TestNullableDateTime == Fixture.DefaultDateTime) - .ToList().Single()); + (await context.Set().Where(e => e.Id == 12 && e.TestNullableDateTime == Fixture.DefaultDateTime) + .ToListAsync()).Single()); if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.TestNullableDateTimeOffset)) != null) { Assert.Same( entity, - context.Set().Where( + (await context.Set().Where( e => e.Id == 12 && e.TestNullableDateTimeOffset == new DateTimeOffset(new DateTime(), TimeSpan.FromHours(-8.0))) - .ToList().Single()); + .ToListAsync()).Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.TestNullableTimeSpan)) != null) { Assert.Same( entity, - context.Set() - .Where(e => e.Id == 12 && e.TestNullableTimeSpan == new TimeSpan(0, 10, 9, 8, 7)).ToList().Single()); + (await context.Set() + .Where(e => e.Id == 12 && e.TestNullableTimeSpan == new TimeSpan(0, 10, 9, 8, 7)).ToListAsync()).Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.TestNullableDateOnly)) != null) { Assert.Same( entity, - context.Set() - .Where(e => e.Id == 12 && e.TestNullableDateOnly == new DateOnly(2020, 3, 1)).ToList().Single()); + (await context.Set() + .Where(e => e.Id == 12 && e.TestNullableDateOnly == new DateOnly(2020, 3, 1)).ToListAsync()).Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.TestNullableTimeOnly)) != null) { Assert.Same( entity, - context.Set() - .Where(e => e.Id == 12 && e.TestNullableTimeOnly == new TimeOnly(12, 30, 45, 123)).ToList().Single()); + (await context.Set() + .Where(e => e.Id == 12 && e.TestNullableTimeOnly == new TimeOnly(12, 30, 45, 123)).ToListAsync()).Single()); } if (Fixture.StrictEquality) { Assert.Same( entity, - context.Set().Where(e => e.Id == 12 && e.TestNullableSingle == -1.234F).ToList() - .Single()); + (await context.Set().Where(e => e.Id == 12 && e.TestNullableSingle == -1.234F).ToListAsync()) + .Single()); } else if (Fixture.SupportsDecimalComparisons) { Assert.Same( entity, - context.Set().Where(e => e.Id == 12 && -e.TestNullableSingle + -1.234F < 1E-5).ToList() - .Single()); + (await context.Set().Where(e => e.Id == 12 && -e.TestNullableSingle + -1.234F < 1E-5) + .ToListAsync()) + .Single()); } Assert.Same( entity, - context.Set().Where(e => e.Id == 12 && e.TestNullableSingle != 1E-8).ToList().Single()); + (await context.Set().Where(e => e.Id == 12 && e.TestNullableSingle != 1E-8).ToListAsync()) + .Single()); Assert.Same( entity, - context.Set().Where(e => e.Id == 12 && e.TestNullableBoolean == true).ToList().Single()); + (await context.Set().Where(e => e.Id == 12 && e.TestNullableBoolean == true).ToListAsync()) + .Single()); if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.TestNullableByte)) != null) { Assert.Same( entity, - context.Set().Where(e => e.Id == 12 && e.TestNullableByte == 255).ToList().Single()); + (await context.Set().Where(e => e.Id == 12 && e.TestNullableByte == 255).ToListAsync()) + .Single()); } Assert.Same( entity, - context.Set().Where(e => e.Id == 12 && e.Enum64 == Enum64.SomeValue).ToList().Single()); + (await context.Set().Where(e => e.Id == 12 && e.Enum64 == Enum64.SomeValue).ToListAsync()) + .Single()); Assert.Same( entity, - context.Set().Where(e => e.Id == 12 && e.Enum32 == Enum32.SomeValue).ToList().Single()); + (await context.Set().Where(e => e.Id == 12 && e.Enum32 == Enum32.SomeValue).ToListAsync()) + .Single()); Assert.Same( entity, - context.Set().Where(e => e.Id == 12 && e.Enum16 == Enum16.SomeValue).ToList().Single()); + (await context.Set().Where(e => e.Id == 12 && e.Enum16 == Enum16.SomeValue).ToListAsync()) + .Single()); if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.Enum8)) != null) { Assert.Same( entity, - context.Set().Where(e => e.Id == 12 && e.Enum8 == Enum8.SomeValue).ToList().Single()); + (await context.Set().Where(e => e.Id == 12 && e.Enum8 == Enum8.SomeValue).ToListAsync()) + .Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.TestNullableUnsignedInt16)) != null) { Assert.Same( entity, - context.Set().Where(e => e.Id == 12 && e.TestNullableUnsignedInt16 == 1234).ToList() - .Single()); + (await context.Set().Where(e => e.Id == 12 && e.TestNullableUnsignedInt16 == 1234) + .ToListAsync()) + .Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.TestNullableUnsignedInt32)) != null) { Assert.Same( entity, - context.Set().Where(e => e.Id == 12 && e.TestNullableUnsignedInt32 == 1234565789U) - .ToList().Single()); + (await context.Set().Where(e => e.Id == 12 && e.TestNullableUnsignedInt32 == 1234565789U) + .ToListAsync()).Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.TestNullableUnsignedInt64)) != null) { Assert.Same( entity, - context.Set() - .Where(e => e.Id == 12 && e.TestNullableUnsignedInt64 == 1234567890123456789UL).ToList().Single()); + (await context.Set() + .Where(e => e.Id == 12 && e.TestNullableUnsignedInt64 == 1234567890123456789UL).ToListAsync()).Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.TestNullableCharacter)) != null) { Assert.Same( entity, - context.Set().Where(e => e.Id == 12 && e.TestNullableCharacter == 'a').ToList().Single()); + (await context.Set().Where(e => e.Id == 12 && e.TestNullableCharacter == 'a').ToListAsync()) + .Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.TestNullableSignedByte)) != null) { Assert.Same( entity, - context.Set().Where(e => e.Id == 12 && e.TestNullableSignedByte == -128).ToList() - .Single()); + (await context.Set().Where(e => e.Id == 12 && e.TestNullableSignedByte == -128).ToListAsync()) + .Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.EnumU64)) != null) { Assert.Same( entity, - context.Set().Where(e => e.Id == 12 && e.EnumU64 == EnumU64.SomeValue).ToList().Single()); + (await context.Set().Where(e => e.Id == 12 && e.EnumU64 == EnumU64.SomeValue).ToListAsync()) + .Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.EnumU32)) != null) { Assert.Same( entity, - context.Set().Where(e => e.Id == 12 && e.EnumU32 == EnumU32.SomeValue).ToList().Single()); + (await context.Set().Where(e => e.Id == 12 && e.EnumU32 == EnumU32.SomeValue).ToListAsync()) + .Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.EnumU16)) != null) { Assert.Same( entity, - context.Set().Where(e => e.Id == 12 && e.EnumU16 == EnumU16.SomeValue).ToList().Single()); + (await context.Set().Where(e => e.Id == 12 && e.EnumU16 == EnumU16.SomeValue).ToListAsync()) + .Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.EnumS8)) != null) { Assert.Same( entity, - context.Set().Where(e => e.Id == 12 && e.EnumS8 == EnumS8.SomeValue).ToList().Single()); + (await context.Set().Where(e => e.Id == 12 && e.EnumS8 == EnumS8.SomeValue).ToListAsync()) + .Single()); } } } [ConditionalFact] - public virtual void Can_query_with_null_parameters_using_any_nullable_data_type() + public virtual async Task Can_query_with_null_parameters_using_any_nullable_data_type() { using (var context = CreateContext()) { context.Set().Add( new BuiltInNullableDataTypes { Id = 711 }); - Assert.Equal(1, context.SaveChanges()); + Assert.Equal(1, await context.SaveChangesAsync()); } using (var context = CreateContext()) { - var entity = context.Set().Where(e => e.Id == 711).ToList().Single(); + var entity = (await context.Set().Where(e => e.Id == 711).ToListAsync()).Single(); short? param1 = null; Assert.Same( entity, - context.Set().Where(e => e.Id == 711 && e.TestNullableInt16 == param1).ToList().Single()); + (await context.Set().Where(e => e.Id == 711 && e.TestNullableInt16 == param1).ToListAsync()) + .Single()); Assert.Same( entity, - context.Set().Where(e => e.Id == 711 && (long?)e.TestNullableInt16 == param1).ToList() - .Single()); + (await context.Set().Where(e => e.Id == 711 && (long?)e.TestNullableInt16 == param1) + .ToListAsync()) + .Single()); int? param2 = null; Assert.Same( entity, - context.Set().Where(e => e.Id == 711 && e.TestNullableInt32 == param2).ToList().Single()); + (await context.Set().Where(e => e.Id == 711 && e.TestNullableInt32 == param2).ToListAsync()) + .Single()); long? param3 = null; Assert.Same( entity, - context.Set().Where(e => e.Id == 711 && e.TestNullableInt64 == param3).ToList().Single()); + (await context.Set().Where(e => e.Id == 711 && e.TestNullableInt64 == param3).ToListAsync()) + .Single()); double? param4 = null; Assert.Same( entity, - context.Set().Where(e => e.Id == 711 && e.TestNullableDouble == param4).ToList().Single()); + (await context.Set().Where(e => e.Id == 711 && e.TestNullableDouble == param4).ToListAsync()) + .Single()); decimal? param5 = null; Assert.Same( entity, - context.Set().Where(e => e.Id == 711 && e.TestNullableDecimal == param5).ToList().Single()); + (await context.Set().Where(e => e.Id == 711 && e.TestNullableDecimal == param5).ToListAsync()) + .Single()); DateTime? param6 = null; Assert.Same( entity, - context.Set().Where(e => e.Id == 711 && e.TestNullableDateTime == param6).ToList().Single()); + (await context.Set().Where(e => e.Id == 711 && e.TestNullableDateTime == param6).ToListAsync()) + .Single()); DateTimeOffset? param7 = null; Assert.Same( entity, - context.Set().Where(e => e.Id == 711 && e.TestNullableDateTimeOffset == param7).ToList() - .Single()); + (await context.Set().Where(e => e.Id == 711 && e.TestNullableDateTimeOffset == param7) + .ToListAsync()) + .Single()); TimeSpan? param8 = null; Assert.Same( entity, - context.Set().Where(e => e.Id == 711 && e.TestNullableTimeSpan == param8).ToList().Single()); + (await context.Set().Where(e => e.Id == 711 && e.TestNullableTimeSpan == param8).ToListAsync()) + .Single()); DateOnly? param9 = null; Assert.Same( entity, - context.Set().Where(e => e.Id == 711 && e.TestNullableDateOnly == param9).ToList().Single()); + (await context.Set().Where(e => e.Id == 711 && e.TestNullableDateOnly == param9).ToListAsync()) + .Single()); TimeOnly? param10 = null; Assert.Same( entity, - context.Set().Where(e => e.Id == 711 && e.TestNullableTimeOnly == param10).ToList().Single()); + (await context.Set().Where(e => e.Id == 711 && e.TestNullableTimeOnly == param10).ToListAsync()) + .Single()); float? param11 = null; Assert.Same( entity, - context.Set().Where(e => e.Id == 711 && e.TestNullableSingle == param11).ToList().Single()); + (await context.Set().Where(e => e.Id == 711 && e.TestNullableSingle == param11).ToListAsync()) + .Single()); bool? param12 = null; Assert.Same( entity, - context.Set().Where(e => e.Id == 711 && e.TestNullableBoolean == param12).ToList().Single()); + (await context.Set().Where(e => e.Id == 711 && e.TestNullableBoolean == param12).ToListAsync()) + .Single()); byte? param13 = null; Assert.Same( entity, - context.Set().Where(e => e.Id == 711 && e.TestNullableByte == param13).ToList().Single()); + (await context.Set().Where(e => e.Id == 711 && e.TestNullableByte == param13).ToListAsync()) + .Single()); Enum64? param14 = null; Assert.Same( - entity, context.Set().Where(e => e.Id == 711 && e.Enum64 == param14).ToList().Single()); + entity, + (await context.Set().Where(e => e.Id == 711 && e.Enum64 == param14).ToListAsync()).Single()); Enum32? param15 = null; Assert.Same( - entity, context.Set().Where(e => e.Id == 711 && e.Enum32 == param15).ToList().Single()); + entity, + (await context.Set().Where(e => e.Id == 711 && e.Enum32 == param15).ToListAsync()).Single()); Enum16? param16 = null; Assert.Same( - entity, context.Set().Where(e => e.Id == 711 && e.Enum16 == param16).ToList().Single()); + entity, + (await context.Set().Where(e => e.Id == 711 && e.Enum16 == param16).ToListAsync()).Single()); Enum8? param17 = null; Assert.Same( - entity, context.Set().Where(e => e.Id == 711 && e.Enum8 == param17).ToList().Single()); + entity, + (await context.Set().Where(e => e.Id == 711 && e.Enum8 == param17).ToListAsync()).Single()); var entityType = context.Model.FindEntityType(typeof(BuiltInNullableDataTypes)); if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.TestNullableUnsignedInt16)) != null) @@ -1285,8 +1354,9 @@ public virtual void Can_query_with_null_parameters_using_any_nullable_data_type( ushort? param18 = null; Assert.Same( entity, - context.Set().Where(e => e.Id == 711 && e.TestNullableUnsignedInt16 == param18).ToList() - .Single()); + (await context.Set().Where(e => e.Id == 711 && e.TestNullableUnsignedInt16 == param18) + .ToListAsync()) + .Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.TestNullableUnsignedInt32)) != null) @@ -1294,8 +1364,9 @@ public virtual void Can_query_with_null_parameters_using_any_nullable_data_type( uint? param19 = null; Assert.Same( entity, - context.Set().Where(e => e.Id == 711 && e.TestNullableUnsignedInt32 == param19).ToList() - .Single()); + (await context.Set().Where(e => e.Id == 711 && e.TestNullableUnsignedInt32 == param19) + .ToListAsync()) + .Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.TestNullableUnsignedInt64)) != null) @@ -1303,8 +1374,9 @@ public virtual void Can_query_with_null_parameters_using_any_nullable_data_type( ulong? param20 = null; Assert.Same( entity, - context.Set().Where(e => e.Id == 711 && e.TestNullableUnsignedInt64 == param20).ToList() - .Single()); + (await context.Set().Where(e => e.Id == 711 && e.TestNullableUnsignedInt64 == param20) + .ToListAsync()) + .Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.TestNullableCharacter)) != null) @@ -1312,8 +1384,9 @@ public virtual void Can_query_with_null_parameters_using_any_nullable_data_type( char? param21 = null; Assert.Same( entity, - context.Set().Where(e => e.Id == 711 && e.TestNullableCharacter == param21).ToList() - .Single()); + (await context.Set().Where(e => e.Id == 711 && e.TestNullableCharacter == param21) + .ToListAsync()) + .Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.TestNullableSignedByte)) != null) @@ -1321,42 +1394,47 @@ public virtual void Can_query_with_null_parameters_using_any_nullable_data_type( sbyte? param22 = null; Assert.Same( entity, - context.Set().Where(e => e.Id == 711 && e.TestNullableSignedByte == param22).ToList() - .Single()); + (await context.Set().Where(e => e.Id == 711 && e.TestNullableSignedByte == param22) + .ToListAsync()) + .Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.EnumU64)) != null) { EnumU64? param23 = null; Assert.Same( - entity, context.Set().Where(e => e.Id == 711 && e.EnumU64 == param23).ToList().Single()); + entity, + (await context.Set().Where(e => e.Id == 711 && e.EnumU64 == param23).ToListAsync()).Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.EnumU32)) != null) { EnumU32? param24 = null; Assert.Same( - entity, context.Set().Where(e => e.Id == 711 && e.EnumU32 == param24).ToList().Single()); + entity, + (await context.Set().Where(e => e.Id == 711 && e.EnumU32 == param24).ToListAsync()).Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.EnumU16)) != null) { EnumU16? param25 = null; Assert.Same( - entity, context.Set().Where(e => e.Id == 711 && e.EnumU16 == param25).ToList().Single()); + entity, + (await context.Set().Where(e => e.Id == 711 && e.EnumU16 == param25).ToListAsync()).Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.EnumS8)) != null) { EnumS8? param26 = null; Assert.Same( - entity, context.Set().Where(e => e.Id == 711 && e.EnumS8 == param26).ToList().Single()); + entity, + (await context.Set().Where(e => e.Id == 711 && e.EnumS8 == param26).ToListAsync()).Single()); } } } [ConditionalFact] - public virtual void Can_insert_and_read_back_all_non_nullable_data_types() + public virtual async Task Can_insert_and_read_back_all_non_nullable_data_types() { using (var context = CreateContext()) { @@ -1393,12 +1471,12 @@ public virtual void Can_insert_and_read_back_all_non_nullable_data_types() EnumS8 = EnumS8.SomeValue }); - Assert.Equal(1, context.SaveChanges()); + Assert.Equal(1, await context.SaveChangesAsync()); } using (var context = CreateContext()) { - var dt = context.Set().Where(e => e.Id == 1).ToList().Single(); + var dt = (await context.Set().Where(e => e.Id == 1).ToListAsync()).Single(); var entityType = context.Model.FindEntityType(typeof(BuiltInDataTypes)); AssertEqualIfMapped(entityType, (short)-1234, () => dt.TestInt16); @@ -1435,7 +1513,7 @@ public virtual void Can_insert_and_read_back_all_non_nullable_data_types() } [ConditionalFact] - public virtual void Can_insert_and_read_with_max_length_set() + public virtual async Task Can_insert_and_read_with_max_length_set() { const string shortString = "Sky"; var shortBinary = new byte[] { 8, 8, 7, 8, 7 }; @@ -1460,12 +1538,12 @@ public virtual void Can_insert_and_read_with_max_length_set() ByteArray9000 = longBinary }); - Assert.Equal(1, context.SaveChanges()); + Assert.Equal(1, await context.SaveChangesAsync()); } using (var context = CreateContext()) { - var dt = context.Set().Where(e => e.Id == 79).ToList().Single(); + var dt = (await context.Set().Where(e => e.Id == 79).ToListAsync()).Single(); Assert.Equal(shortString, dt.String3); Assert.Equal(shortBinary, dt.ByteArray5); @@ -1476,7 +1554,7 @@ public virtual void Can_insert_and_read_with_max_length_set() } [ConditionalFact] - public virtual void Can_insert_and_read_back_with_binary_key() + public virtual async Task Can_insert_and_read_back_with_binary_key() { if (!Fixture.SupportsBinaryKeys) { @@ -1495,27 +1573,27 @@ public virtual void Can_insert_and_read_back_with_binary_key() new BinaryForeignKeyDataType { Id = 777, BinaryKeyDataTypeId = [1, 2, 3] }, new BinaryForeignKeyDataType { Id = 7777, BinaryKeyDataTypeId = [1, 2, 3, 4, 5] }); - Assert.Equal(6, context.SaveChanges()); + Assert.Equal(6, await context.SaveChangesAsync()); } - BinaryKeyDataType QueryByBinaryKey(DbContext context, byte[] bytes) - => context + async Task QueryByBinaryKey(DbContext context, byte[] bytes) + => (await context .Set() .Include(e => e.Dependents) .Where(e => e.Id == bytes) - .ToList().Single(); + .ToListAsync()).Single(); using (var context = CreateContext()) { - var entity1 = QueryByBinaryKey(context, [1, 2, 3]); + var entity1 = await QueryByBinaryKey(context, [1, 2, 3]); Assert.Equal(new byte[] { 1, 2, 3 }, entity1.Id); Assert.Equal(1, entity1.Dependents.Count); - var entity2 = QueryByBinaryKey(context, [1, 2, 3, 4]); + var entity2 = await QueryByBinaryKey(context, [1, 2, 3, 4]); Assert.Equal(new byte[] { 1, 2, 3, 4 }, entity2.Id); Assert.Equal(1, entity2.Dependents.Count); - var entity3 = QueryByBinaryKey(context, [1, 2, 3, 4, 5]); + var entity3 = await QueryByBinaryKey(context, [1, 2, 3, 4, 5]); Assert.Equal(new byte[] { 1, 2, 3, 4, 5 }, entity3.Id); Assert.Equal(1, entity3.Dependents.Count); @@ -1527,46 +1605,46 @@ BinaryKeyDataType QueryByBinaryKey(DbContext context, byte[] bytes) entity2.Dependents.Single().BinaryKeyDataTypeId = [1, 2, 3, 4, 5]; - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - var entity1 = QueryByBinaryKey(context, [1, 2, 3]); + var entity1 = await QueryByBinaryKey(context, [1, 2, 3]); Assert.Equal("Xx7", entity1.Ex); Assert.Equal(0, entity1.Dependents.Count); - var entity2 = QueryByBinaryKey(context, [1, 2, 3, 4]); + var entity2 = await QueryByBinaryKey(context, [1, 2, 3, 4]); Assert.Equal("Xx3", entity2.Ex); Assert.Equal(0, entity2.Dependents.Count); - var entity3 = QueryByBinaryKey(context, [1, 2, 3, 4, 5]); + var entity3 = await QueryByBinaryKey(context, [1, 2, 3, 4, 5]); Assert.Equal("Xx1", entity3.Ex); Assert.Equal(3, entity3.Dependents.Count); } } [ConditionalFact] - public virtual void Can_insert_and_read_back_with_null_binary_foreign_key() + public virtual async Task Can_insert_and_read_back_with_null_binary_foreign_key() { using (var context = CreateContext()) { context.Set().Add( new BinaryForeignKeyDataType { Id = 78 }); - Assert.Equal(1, context.SaveChanges()); + Assert.Equal(1, await context.SaveChangesAsync()); } using (var context = CreateContext()) { - var entity = context.Set().Where(e => e.Id == 78).ToList().Single(); + var entity = (await context.Set().Where(e => e.Id == 78).ToListAsync()).Single(); Assert.Null(entity.BinaryKeyDataTypeId); } } [ConditionalFact] - public virtual void Can_insert_and_read_back_with_string_key() + public virtual async Task Can_insert_and_read_back_with_string_key() { using (var context = CreateContext()) { @@ -1578,16 +1656,16 @@ public virtual void Can_insert_and_read_back_with_string_key() Assert.Same(principal, dependent.Principal); - Assert.Equal(2, context.SaveChanges()); + Assert.Equal(2, await context.SaveChangesAsync()); } using (var context = CreateContext()) { - var entity = context + var entity = (await context .Set() .Include(e => e.Dependents) .Where(e => e.Id == "Gumball!") - .ToList().Single(); + .ToListAsync()).Single(); Assert.Equal("Gumball!", entity.Id); Assert.Equal("Gumball!", entity.Dependents.First().StringKeyDataTypeId); @@ -1595,19 +1673,19 @@ public virtual void Can_insert_and_read_back_with_string_key() } [ConditionalFact] - public virtual void Can_insert_and_read_back_with_null_string_foreign_key() + public virtual async Task Can_insert_and_read_back_with_null_string_foreign_key() { using (var context = CreateContext()) { context.Set().Add( new StringForeignKeyDataType { Id = 78 }); - Assert.Equal(1, context.SaveChanges()); + Assert.Equal(1, await context.SaveChangesAsync()); } using (var context = CreateContext()) { - var entity = context.Set().Where(e => e.Id == 78).ToList().Single(); + var entity = (await context.Set().Where(e => e.Id == 78).ToListAsync()).Single(); Assert.Null(entity.StringKeyDataTypeId); } @@ -1711,19 +1789,19 @@ private static bool IsUnsignedInteger(Type type) || type == typeof(char); [ConditionalFact] - public virtual void Can_insert_and_read_back_all_nullable_data_types_with_values_set_to_null() + public virtual async Task Can_insert_and_read_back_all_nullable_data_types_with_values_set_to_null() { using (var context = CreateContext()) { context.Set().Add( new BuiltInNullableDataTypes { Id = 100, PartitionId = 100 }); - Assert.Equal(1, context.SaveChanges()); + Assert.Equal(1, await context.SaveChangesAsync()); } using (var context = CreateContext()) { - var dt = context.Set().Where(ndt => ndt.Id == 100).ToList().Single(); + var dt = (await context.Set().Where(ndt => ndt.Id == 100).ToListAsync()).Single(); Assert.Null(dt.TestString); Assert.Null(dt.TestByteArray); @@ -1757,7 +1835,7 @@ public virtual void Can_insert_and_read_back_all_nullable_data_types_with_values } [ConditionalFact] - public virtual void Can_insert_and_read_back_all_nullable_data_types_with_values_set_to_non_null() + public virtual async Task Can_insert_and_read_back_all_nullable_data_types_with_values_set_to_non_null() { using (var context = CreateContext()) { @@ -1796,12 +1874,12 @@ public virtual void Can_insert_and_read_back_all_nullable_data_types_with_values EnumS8 = EnumS8.SomeValue }); - Assert.Equal(1, context.SaveChanges()); + Assert.Equal(1, await context.SaveChangesAsync()); } using (var context = CreateContext()) { - var dt = context.Set().Where(ndt => ndt.Id == 101).ToList().Single(); + var dt = (await context.Set().Where(ndt => ndt.Id == 101).ToListAsync()).Single(); var entityType = context.Model.FindEntityType(typeof(BuiltInNullableDataTypes)); AssertEqualIfMapped(entityType, "TestString", () => dt.TestString); @@ -1838,7 +1916,7 @@ public virtual void Can_insert_and_read_back_all_nullable_data_types_with_values } [ConditionalFact] - public virtual void Can_insert_and_read_back_object_backed_data_types() + public virtual async Task Can_insert_and_read_back_object_backed_data_types() { using (var context = CreateContext()) { @@ -1877,12 +1955,12 @@ public virtual void Can_insert_and_read_back_object_backed_data_types() EnumS8 = EnumS8.SomeValue }); - Assert.Equal(1, context.SaveChanges()); + Assert.Equal(1, await context.SaveChangesAsync()); } using (var context = CreateContext()) { - var dt = context.Set().Where(ndt => ndt.Id == 101).ToList().Single(); + var dt = (await context.Set().Where(ndt => ndt.Id == 101).ToListAsync()).Single(); var entityType = context.Model.FindEntityType(typeof(ObjectBackedDataTypes)); AssertEqualIfMapped(entityType, "TestString", () => dt.String); @@ -1919,7 +1997,7 @@ public virtual void Can_insert_and_read_back_object_backed_data_types() } [ConditionalFact] - public virtual void Can_insert_and_read_back_nullable_backed_data_types() + public virtual async Task Can_insert_and_read_back_nullable_backed_data_types() { using (var context = CreateContext()) { @@ -1956,12 +2034,12 @@ public virtual void Can_insert_and_read_back_nullable_backed_data_types() EnumS8 = EnumS8.SomeValue }); - Assert.Equal(1, context.SaveChanges()); + Assert.Equal(1, await context.SaveChangesAsync()); } using (var context = CreateContext()) { - var dt = context.Set().Where(ndt => ndt.Id == 101).ToList().Single(); + var dt = (await context.Set().Where(ndt => ndt.Id == 101).ToListAsync()).Single(); var entityType = context.Model.FindEntityType(typeof(NullableBackedDataTypes)); AssertEqualIfMapped(entityType, (short)-1234, () => dt.Int16); @@ -1996,7 +2074,7 @@ public virtual void Can_insert_and_read_back_nullable_backed_data_types() } [ConditionalFact] - public virtual void Can_insert_and_read_back_non_nullable_backed_data_types() + public virtual async Task Can_insert_and_read_back_non_nullable_backed_data_types() { using (var context = CreateContext()) { @@ -2033,12 +2111,12 @@ public virtual void Can_insert_and_read_back_non_nullable_backed_data_types() EnumS8 = EnumS8.SomeValue }); - Assert.Equal(1, context.SaveChanges()); + Assert.Equal(1, await context.SaveChangesAsync()); } using (var context = CreateContext()) { - var dt = context.Set().Where(ndt => ndt.Id == 101).ToList().Single(); + var dt = (await context.Set().Where(ndt => ndt.Id == 101).ToListAsync()).Single(); var entityType = context.Model.FindEntityType(typeof(NonNullableBackedDataTypes)); AssertEqualIfMapped(entityType, (short)-1234, () => dt.Int16); @@ -2074,60 +2152,60 @@ public virtual void Can_insert_and_read_back_non_nullable_backed_data_types() } [ConditionalFact] - public virtual void Can_read_back_mapped_enum_from_collection_first_or_default() + public virtual async Task Can_read_back_mapped_enum_from_collection_first_or_default() { using var context = CreateContext(); var query = from animal in context.Set() select new { animal.Id, animal.IdentificationMethods.FirstOrDefault().Method }; - var result = query.SingleOrDefault(); + var result = await query.SingleOrDefaultAsync(); Assert.Equal(IdentificationMethod.EarTag, result.Method); } [ConditionalFact] - public virtual void Can_read_back_bool_mapped_as_int_through_navigation() + public virtual async Task Can_read_back_bool_mapped_as_int_through_navigation() { using var context = CreateContext(); var query = from animal in context.Set() where animal.Details != null select new { animal.Details.BoolField }; - var result = Assert.Single(query.ToList()); + var result = Assert.Single(await query.ToListAsync()); Assert.True(result.BoolField); } [ConditionalFact] - public virtual void Can_compare_enum_to_constant() + public virtual async Task Can_compare_enum_to_constant() { using var context = CreateContext(); - var query = context.Set() + var query = await context.Set() .Where(a => a.Method == IdentificationMethod.EarTag) - .ToList(); + .ToListAsync(); var result = Assert.Single(query); Assert.Equal(IdentificationMethod.EarTag, result.Method); } [ConditionalFact] - public virtual void Can_compare_enum_to_parameter() + public virtual async Task Can_compare_enum_to_parameter() { var method = IdentificationMethod.EarTag; using var context = CreateContext(); - var query = context.Set() + var query = (await context.Set() .Where(a => a.Method == method) - .ToList(); + .ToListAsync()); var result = Assert.Single(query); Assert.Equal(IdentificationMethod.EarTag, result.Method); } [ConditionalFact] - public virtual void Object_to_string_conversion() + public virtual async Task Object_to_string_conversion() { using var context = CreateContext(); - var expected = context.Set() - .Where(e => e.Id == 13) - .AsEnumerable() + var expected = (await context.Set() + .Where(e => e.Id == 13) + .ToListAsync()) .Select( b => new { @@ -2146,7 +2224,7 @@ public virtual void Object_to_string_conversion() Fixture.ListLoggerFactory.Clear(); - var query = context.Set() + var query = await context.Set() .Where(e => e.Id == 13) .Select( b => new @@ -2169,7 +2247,7 @@ public virtual void Object_to_string_conversion() DateOnly = b.TestDateOnly.ToString(), TimeOnly = b.TestTimeOnly.ToString(), }) - .ToList(); + .ToListAsync(); var actual = Assert.Single(query); Assert.Equal(expected.Sbyte, actual.Sbyte); @@ -2185,14 +2263,14 @@ public virtual void Object_to_string_conversion() } [ConditionalFact] - public virtual void Optional_datetime_reading_null_from_database() + public virtual async Task Optional_datetime_reading_null_from_database() { using var context = CreateContext(); - var expected = context.Set().ToList() + var expected = (await context.Set().ToListAsync()) .Select(e => new { DT = e.DateTimeOffset == null ? (DateTime?)null : e.DateTimeOffset.Value.DateTime.Date }).ToList(); - var actual = context.Set() - .Select(e => new { DT = e.DateTimeOffset == null ? (DateTime?)null : e.DateTimeOffset.Value.DateTime.Date }).ToList(); + var actual = await context.Set() + .Select(e => new { DT = e.DateTimeOffset == null ? (DateTime?)null : e.DateTimeOffset.Value.DateTime.Date }).ToListAsync(); for (var i = 0; i < expected.Count; i++) { @@ -2201,11 +2279,11 @@ public virtual void Optional_datetime_reading_null_from_database() } [ConditionalFact] - public virtual void Can_insert_query_multiline_string() + public virtual async Task Can_insert_query_multiline_string() { using var context = CreateContext(); - Assert.Equal(Fixture.ReallyLargeString, Assert.Single(context.Set()).Value); + Assert.Equal(Fixture.ReallyLargeString, Assert.Single((await context.Set().ToListAsync())).Value); } public abstract class BuiltInDataTypesFixtureBase : SharedStoreFixtureBase diff --git a/test/EFCore.Specification.Tests/ComplexTypesTrackingTestBase.cs b/test/EFCore.Specification.Tests/ComplexTypesTrackingTestBase.cs index 505fcb6162f..0e855cc7871 100644 --- a/test/EFCore.Specification.Tests/ComplexTypesTrackingTestBase.cs +++ b/test/EFCore.Specification.Tests/ComplexTypesTrackingTestBase.cs @@ -1000,14 +1000,6 @@ protected static EntityEntry TrackFromQuery(DbContext context, => new(context.GetService().StartTrackingFromQuery( context.Model.FindEntityType(typeof(TEntity))!, pub, Snapshot.Empty)); - protected virtual void ExecuteWithStrategyInTransaction( - Action testOperation, - Action? nestedTestOperation1 = null, - Action? nestedTestOperation2 = null) - => TestHelpers.ExecuteWithStrategyInTransaction( - CreateContext, UseTransaction, - testOperation, nestedTestOperation1, nestedTestOperation2); - protected virtual Task ExecuteWithStrategyInTransactionAsync( Func testOperation, Func? nestedTestOperation1 = null, diff --git a/test/EFCore.Specification.Tests/ConcurrencyDetectorTestBase.cs b/test/EFCore.Specification.Tests/ConcurrencyDetectorTestBase.cs index 44adbc47f7d..a01300ebe0d 100644 --- a/test/EFCore.Specification.Tests/ConcurrencyDetectorTestBase.cs +++ b/test/EFCore.Specification.Tests/ConcurrencyDetectorTestBase.cs @@ -77,10 +77,10 @@ public class ConcurrencyDetectorDbContext(DbContextOptions Products { get; set; } - public static void Seed(ConcurrencyDetectorDbContext context) + public static Task SeedAsync(ConcurrencyDetectorDbContext context) { context.Products.Add(new Product { Id = 1, Name = "Unicorn Party Pack" }); - context.SaveChanges(); + return context.SaveChangesAsync(); } } @@ -98,8 +98,8 @@ protected override string StoreName protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext context) => modelBuilder.Entity().Property(p => p.Id).ValueGeneratedNever(); - protected override void Seed(ConcurrencyDetectorDbContext context) - => ConcurrencyDetectorDbContext.Seed(context); + protected override Task SeedAsync(ConcurrencyDetectorDbContext context) + => ConcurrencyDetectorDbContext.SeedAsync(context); } public static IEnumerable IsAsyncData = new object[][] { [false], [true] }; diff --git a/test/EFCore.Specification.Tests/ConferencePlannerTestBase.cs b/test/EFCore.Specification.Tests/ConferencePlannerTestBase.cs index 1768271bebe..7176e11a2f7 100644 --- a/test/EFCore.Specification.Tests/ConferencePlannerTestBase.cs +++ b/test/EFCore.Specification.Tests/ConferencePlannerTestBase.cs @@ -711,7 +711,7 @@ protected override string StoreName protected override bool UsePooling => false; - protected override void Seed(ApplicationDbContext context) + protected override Task SeedAsync(ApplicationDbContext context) { var attendees1 = new List { @@ -830,7 +830,7 @@ protected override void Seed(ApplicationDbContext context) } context.AddRange(tracks.Values); - context.SaveChanges(); + return context.SaveChangesAsync(); } } } diff --git a/test/EFCore.Specification.Tests/ConvertToProviderTypesTestBase.cs b/test/EFCore.Specification.Tests/ConvertToProviderTypesTestBase.cs index c63c615432c..fda241cd8a7 100644 --- a/test/EFCore.Specification.Tests/ConvertToProviderTypesTestBase.cs +++ b/test/EFCore.Specification.Tests/ConvertToProviderTypesTestBase.cs @@ -31,7 +31,8 @@ public virtual void Object_equals_method_over_enum_works() Assert.Empty(query); } - public override void Object_to_string_conversion() { } + public override Task Object_to_string_conversion() + => Task.CompletedTask; public abstract class ConvertToProviderTypesFixtureBase : BuiltInDataTypesFixtureBase { diff --git a/test/EFCore.Specification.Tests/CustomConvertersTestBase.cs b/test/EFCore.Specification.Tests/CustomConvertersTestBase.cs index 0fe296b19a1..2db01a06bec 100644 --- a/test/EFCore.Specification.Tests/CustomConvertersTestBase.cs +++ b/test/EFCore.Specification.Tests/CustomConvertersTestBase.cs @@ -16,7 +16,7 @@ protected CustomConvertersTestBase(TFixture fixture) } [ConditionalFact] - public virtual void Can_query_and_update_with_nullable_converter_on_unique_index() + public virtual async Task Can_query_and_update_with_nullable_converter_on_unique_index() { using (var context = CreateContext()) { @@ -36,12 +36,12 @@ public virtual void Can_query_and_update_with_nullable_converter_on_unique_index }, new Person { Id = 4, Name = "Valtteri" }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - var drivers = context.Set().OrderBy(p => p.Name).ToList(); + var drivers = await context.Set().OrderBy(p => p.Name).ToListAsync(); Assert.Equal(4, drivers.Count); @@ -67,12 +67,12 @@ public virtual void Can_query_and_update_with_nullable_converter_on_unique_index SSN = new SocialSecurityNumber { Number = 222222222 } }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - var drivers = context.Set().OrderBy(p => p.Name).ToList(); + var drivers = await context.Set().OrderBy(p => p.Name).ToListAsync(); Assert.Equal(4, drivers.Count); @@ -108,7 +108,7 @@ protected class Person } [ConditionalFact] - public virtual void Can_query_and_update_with_nullable_converter_on_primary_key() + public virtual async Task Can_query_and_update_with_nullable_converter_on_primary_key() { using (var context = CreateContext()) { @@ -124,12 +124,12 @@ public virtual void Can_query_and_update_with_nullable_converter_on_primary_key( Assert.Equal(1, pkEntry.CurrentValue); Assert.Equal(1, pkEntry.OriginalValue); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - var dependent = context.Set().Include(e => e.Principal).Single(); + var dependent = await context.Set().Include(e => e.Principal).SingleAsync(); Assert.Equal(1, dependent.PrincipalId); Assert.Equal(1, dependent.Principal.Id); @@ -160,7 +160,7 @@ protected class NonNullableDependent } [ConditionalFact] - public virtual void Can_query_and_update_with_conversion_for_custom_type() + public virtual async Task Can_query_and_update_with_conversion_for_custom_type() { Guid id; using (var context = CreateContext()) @@ -168,14 +168,14 @@ public virtual void Can_query_and_update_with_conversion_for_custom_type() var user = context.Set().Add( new User(Email.Create("eeky_bear@example.com"))).Entity; - Assert.Equal(1, context.SaveChanges()); + Assert.Equal(1, await context.SaveChangesAsync()); id = user.Id; } using (var context = CreateContext()) { - var user = context.Set().Single(e => e.Id == id && e.Email == "eeky_bear@example.com"); + var user = await context.Set().SingleAsync(e => e.Id == id && e.Email == "eeky_bear@example.com"); Assert.Equal(id, user.Id); Assert.Equal("eeky_bear@example.com", user.Email); @@ -215,19 +215,19 @@ public static implicit operator string(Email email) } [ConditionalFact] - public virtual void Can_query_and_update_with_conversion_for_custom_struct() + public virtual async Task Can_query_and_update_with_conversion_for_custom_struct() { using (var context = CreateContext()) { var load = context.Set().Add( new Load { LoadId = 1, Fuel = new Fuel(1.1) }).Entity; - Assert.Equal(1, context.SaveChanges()); + Assert.Equal(1, await context.SaveChangesAsync()); } using (var context = CreateContext()) { - var load = context.Set().Single(e => e.LoadId == 1 && e.Fuel.Equals(new Fuel(1.1))); + var load = await context.Set().SingleAsync(e => e.LoadId == 1 && e.Fuel.Equals(new Fuel(1.1))); Assert.Equal(1, load.LoadId); Assert.Equal(1.1, load.Fuel.Volume); @@ -247,7 +247,7 @@ protected struct Fuel(double volume) } [ConditionalFact] - public virtual void Can_insert_and_read_back_with_case_insensitive_string_key() + public virtual async Task Can_insert_and_read_back_with_case_insensitive_string_key() { using (var context = CreateContext()) { @@ -259,16 +259,16 @@ public virtual void Can_insert_and_read_back_with_case_insensitive_string_key() Assert.Same(principal, dependent.Principal); - Assert.Equal(2, context.SaveChanges()); + Assert.Equal(2, await context.SaveChangesAsync()); } using (var context = CreateContext()) { - var entity = context + var entity = (await context .Set() .Include(e => e.Dependents) .Where(e => e.Id == "Gumball!!") - .ToList().Single(); + .ToListAsync()).Single(); Assert.Equal("Gumball!!", entity.Id); Assert.Equal("gumball!!", entity.Dependents.First().StringKeyDataTypeId); @@ -276,11 +276,11 @@ public virtual void Can_insert_and_read_back_with_case_insensitive_string_key() using (var context = CreateContext()) { - var entity = context + var entity = (await context .Set() .Include(e => e.Dependents) .Where(e => e.Id == "gumball!!") - .ToList().Single(); + .ToListAsync()).Single(); Assert.Equal("Gumball!!", entity.Id); Assert.Equal("gumball!!", entity.Dependents.First().StringKeyDataTypeId); @@ -288,19 +288,19 @@ public virtual void Can_insert_and_read_back_with_case_insensitive_string_key() } [ConditionalFact] - public virtual void Can_insert_and_read_back_with_string_list() + public virtual async Task Can_insert_and_read_back_with_string_list() { using (var context = CreateContext()) { context.Set().Add( new StringListDataType { Id = 1, Strings = new List { "Gum", "Taffy" } }); - Assert.Equal(1, context.SaveChanges()); + Assert.Equal(1, await context.SaveChangesAsync()); } using (var context = CreateContext()) { - var entity = context.Set().Single(); + var entity = await context.Set().SingleAsync(); Assert.Equal(new[] { "Gum", "Taffy" }, entity.Strings); } @@ -314,30 +314,30 @@ protected class StringListDataType } [ConditionalFact] - public virtual void Can_insert_and_query_struct_to_string_converter_for_pk() + public virtual async Task Can_insert_and_query_struct_to_string_converter_for_pk() { using (var context = CreateContext()) { context.Set().Add(new Order { Id = OrderId.Parse("Id1") }); - Assert.Equal(1, context.SaveChanges()); + Assert.Equal(1, await context.SaveChangesAsync()); } using (var context = CreateContext()) { // Inline - var entity = context.Set().Where(o => (string)o.Id == "Id1").Single(); + var entity = await context.Set().Where(o => (string)o.Id == "Id1").SingleAsync(); // constant from closure const string idAsStringConstant = "Id1"; - entity = context.Set().Where(o => (string)o.Id == idAsStringConstant).Single(); + entity = await context.Set().Where(o => (string)o.Id == idAsStringConstant).SingleAsync(); // Variable from closure var idAsStringVariable = "Id1"; - entity = context.Set().Where(o => (string)o.Id == idAsStringVariable).Single(); + entity = await context.Set().Where(o => (string)o.Id == idAsStringVariable).SingleAsync(); // Inline parsing function - entity = context.Set().Where(o => (string)o.Id == OrderId.Parse("Id1").StringValue).Single(); + entity = await context.Set().Where(o => (string)o.Id == OrderId.Parse("Id1").StringValue).SingleAsync(); } } @@ -370,7 +370,7 @@ public virtual async Task Can_query_custom_type_not_mapped_by_default_equality(b using (var context = CreateContext()) { context.Set().Add(new SimpleCounter { CounterId = 1, StyleKey = "Swag" }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) @@ -384,7 +384,7 @@ public virtual async Task Can_query_custom_type_not_mapped_by_default_equality(b var result = async ? await query.SingleAsync() : query.Single(); Assert.NotNull(result); context.Remove(result); - context.SaveChanges(); + await context.SaveChangesAsync(); } } @@ -397,10 +397,10 @@ public class SimpleCounter } [ConditionalFact] - public virtual void Field_on_derived_type_retrieved_via_cast_applies_value_converter() + public virtual async Task Field_on_derived_type_retrieved_via_cast_applies_value_converter() { using var context = CreateContext(); - var query = context.Set() + var query = await context.Set() .Where(b => b.BlogId == 2) .Select( x => new @@ -408,91 +408,91 @@ public virtual void Field_on_derived_type_retrieved_via_cast_applies_value_conve x.BlogId, x.Url, RssUrl = x is RssBlog ? ((RssBlog)x).RssUrl : null - }).ToList(); + }).ToListAsync(); var result = Assert.Single(query); Assert.Equal("http://rssblog.com/rss", result.RssUrl); } [ConditionalFact] - public virtual void Value_conversion_is_appropriately_used_for_join_condition() + public virtual async Task Value_conversion_is_appropriately_used_for_join_condition() { using var context = CreateContext(); var blogId = 1; - var query = (from b in context.Set() - join p in context.Set() - on new - { - BlogId = (int?)b.BlogId, - b.IsVisible, - AnotherId = b.BlogId - } - equals new - { - p.BlogId, - IsVisible = true, - AnotherId = blogId - } - where b.IsVisible - select b.Url).ToList(); + var query = await ((from b in context.Set() + join p in context.Set() + on new + { + BlogId = (int?)b.BlogId, + b.IsVisible, + AnotherId = b.BlogId + } + equals new + { + p.BlogId, + IsVisible = true, + AnotherId = blogId + } + where b.IsVisible + select b.Url).ToListAsync()); var result = Assert.Single(query); Assert.Equal("http://blog.com", result); } [ConditionalFact] - public virtual void Value_conversion_is_appropriately_used_for_left_join_condition() + public virtual async Task Value_conversion_is_appropriately_used_for_left_join_condition() { using var context = CreateContext(); var blogId = 1; - var query = (from b in context.Set() - join p in context.Set() - on new - { - BlogId = (int?)b.BlogId, - b.IsVisible, - AnotherId = b.BlogId - } - equals new - { - p.BlogId, - IsVisible = true, - AnotherId = blogId - } into g - from p in g.DefaultIfEmpty() - where b.IsVisible - select b.Url).ToList(); + var query = await (from b in context.Set() + join p in context.Set() + on new + { + BlogId = (int?)b.BlogId, + b.IsVisible, + AnotherId = b.BlogId + } + equals new + { + p.BlogId, + IsVisible = true, + AnotherId = blogId + } into g + from p in g.DefaultIfEmpty() + where b.IsVisible + select b.Url).ToListAsync(); var result = Assert.Single(query); Assert.Equal("http://blog.com", result); } [ConditionalFact] - public virtual void Where_bool_gets_converted_to_equality_when_value_conversion_is_used() + public virtual async Task Where_bool_gets_converted_to_equality_when_value_conversion_is_used() { using var context = CreateContext(); - var query = context.Set().Where(b => b.IsVisible).ToList(); + var query = await context.Set().Where(b => b.IsVisible).ToListAsync(); var result = Assert.Single(query); Assert.Equal("http://blog.com", result.Url); } [ConditionalFact] - public virtual void Where_negated_bool_gets_converted_to_equality_when_value_conversion_is_used() + public virtual async Task Where_negated_bool_gets_converted_to_equality_when_value_conversion_is_used() { using var context = CreateContext(); - var query = context.Set().Where(b => !b.IsVisible).ToList(); + var query = await context.Set().Where(b => !b.IsVisible).ToListAsync(); var result = Assert.Single(query); Assert.Equal("http://rssblog.com", result.Url); } [ConditionalFact] - public virtual void Where_bool_with_value_conversion_inside_comparison_doesnt_get_converted_twice() + public virtual async Task Where_bool_with_value_conversion_inside_comparison_doesnt_get_converted_twice() { using var context = CreateContext(); - var query1 = context.Set().Where(b => b.IsVisible).ToList(); - var query2 = context.Set().Where(b => b.IsVisible != true).ToList(); + var query1 = await context.Set().Where(b => b.IsVisible).ToListAsync(); + var query2 = await context.Set().Where(b => b.IsVisible != true).ToListAsync(); var result1 = Assert.Single(query1); Assert.Equal("http://blog.com", result1.Url); @@ -502,10 +502,10 @@ public virtual void Where_bool_with_value_conversion_inside_comparison_doesnt_ge } [ConditionalFact] - public virtual void Select_bool_with_value_conversion_is_used() + public virtual async Task Select_bool_with_value_conversion_is_used() { using var context = CreateContext(); - var result = context.Set().Select(b => b.IsVisible).ToList(); + var result = await context.Set().Select(b => b.IsVisible).ToListAsync(); Assert.Equal(2, result.Count); Assert.Contains(true, result); @@ -513,20 +513,20 @@ public virtual void Select_bool_with_value_conversion_is_used() } [ConditionalFact] - public virtual void Where_conditional_bool_with_value_conversion_is_used() + public virtual async Task Where_conditional_bool_with_value_conversion_is_used() { using var context = CreateContext(); - var query = context.Set().Where(b => (b.IsVisible ? "Foo" : "Bar") == "Foo").ToList(); + var query = await context.Set().Where(b => (b.IsVisible ? "Foo" : "Bar") == "Foo").ToListAsync(); var result = Assert.Single(query); Assert.Equal("http://blog.com", result.Url); } [ConditionalFact] - public virtual void Select_conditional_bool_with_value_conversion_is_used() + public virtual async Task Select_conditional_bool_with_value_conversion_is_used() { using var context = CreateContext(); - var result = context.Set().Select(b => b.IsVisible ? "Foo" : "Bar").ToList(); + var result = await context.Set().Select(b => b.IsVisible ? "Foo" : "Bar").ToListAsync(); Assert.Equal(2, result.Count); Assert.Contains("Foo", result); @@ -534,20 +534,20 @@ public virtual void Select_conditional_bool_with_value_conversion_is_used() } [ConditionalFact] - public virtual void Where_bool_gets_converted_to_equality_when_value_conversion_is_used_using_EFProperty() + public virtual async Task Where_bool_gets_converted_to_equality_when_value_conversion_is_used_using_EFProperty() { using var context = CreateContext(); - var query = context.Set().Where(b => EF.Property(b, "IsVisible")).ToList(); + var query = await context.Set().Where(b => EF.Property(b, "IsVisible")).ToListAsync(); var result = Assert.Single(query); Assert.Equal("http://blog.com", result.Url); } [ConditionalFact] - public virtual void Where_bool_gets_converted_to_equality_when_value_conversion_is_used_using_indexer() + public virtual async Task Where_bool_gets_converted_to_equality_when_value_conversion_is_used_using_indexer() { using var context = CreateContext(); - var query = context.Set().Where(b => !(bool)b["IndexerVisible"]).ToList(); + var query = await context.Set().Where(b => !(bool)b["IndexerVisible"]).ToListAsync(); var result = Assert.Single(query); Assert.Equal("http://blog.com", result.Url); @@ -695,7 +695,8 @@ protected enum Roles Seller } - public override void Object_to_string_conversion() { } + public override Task Object_to_string_conversion() + => Task.CompletedTask; [ConditionalFact] public virtual void Optional_owned_with_converter_reading_non_nullable_column() @@ -719,10 +720,10 @@ protected class OwnedWithConverter } [ConditionalFact] - public virtual void Id_object_as_entity_key() + public virtual async Task Id_object_as_entity_key() { using var context = CreateContext(); - var books = context.Set().Where(b => b.Id == new BookId(1)).ToList(); + var books = await context.Set().Where(b => b.Id == new BookId(1)).ToListAsync(); Assert.Equal("Book1", Assert.Single(books).Value); } @@ -1435,10 +1436,10 @@ public static List Deserialize(string s) } private class OrderIdEntityFrameworkValueConverter(ConverterMappingHints mappingHints) : ValueConverter( - orderId => orderId.StringValue, - stringValue => OrderId.Parse(stringValue), - mappingHints - ) + orderId => orderId.StringValue, + stringValue => OrderId.Parse(stringValue), + mappingHints + ) { public OrderIdEntityFrameworkValueConverter() : this(null) diff --git a/test/EFCore.Specification.Tests/DataAnnotationTestBase.cs b/test/EFCore.Specification.Tests/DataAnnotationTestBase.cs index 33ae87f299a..16f871d9243 100644 --- a/test/EFCore.Specification.Tests/DataAnnotationTestBase.cs +++ b/test/EFCore.Specification.Tests/DataAnnotationTestBase.cs @@ -25,11 +25,11 @@ protected DataAnnotationTestBase(TFixture fixture) protected DbContext CreateContext() => Fixture.CreateContext(); - protected virtual void ExecuteWithStrategyInTransaction(Action testOperation) - => TestHelpers.ExecuteWithStrategyInTransaction(CreateContext, UseTransaction, testOperation); + protected virtual Task ExecuteWithStrategyInTransactionAsync(Func testOperation) + => TestHelpers.ExecuteWithStrategyInTransactionAsync(CreateContext, UseTransaction, testOperation); - protected virtual void ExecuteWithStrategyInTransaction(Action testOperation1, Action testOperation2) - => TestHelpers.ExecuteWithStrategyInTransaction(CreateContext, UseTransaction, testOperation1, testOperation2); + protected virtual Task ExecuteWithStrategyInTransactionAsync(Func testOperation1, Func testOperation2) + => TestHelpers.ExecuteWithStrategyInTransactionAsync(CreateContext, UseTransaction, testOperation1, testOperation2); protected virtual void UseTransaction(DatabaseFacade facade, IDbContextTransaction transaction) { @@ -1708,9 +1708,9 @@ protected class TNAttrDerived : TNAttrBase } [ConditionalFact] - public virtual void ConcurrencyCheckAttribute_throws_if_value_in_database_changed() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task ConcurrencyCheckAttribute_throws_if_value_in_database_changed() + => ExecuteWithStrategyInTransactionAsync( + async context => { var clientRow = context.Set().First(r => r.UniqueNo == 1); clientRow.RowVersion = new Guid("00000000-0000-0000-0002-000000000001"); @@ -1722,14 +1722,14 @@ public virtual void ConcurrencyCheckAttribute_throws_if_value_in_database_change storeRow.RowVersion = new Guid("00000000-0000-0000-0003-000000000001"); storeRow.RequiredColumn = "ModifiedData"; - innerContext.SaveChanges(); + await innerContext.SaveChangesAsync(); - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); }); [ConditionalFact] - public virtual void DatabaseGeneratedAttribute_autogenerates_values_when_set_to_identity() - => ExecuteWithStrategyInTransaction( + public virtual Task DatabaseGeneratedAttribute_autogenerates_values_when_set_to_identity() + => ExecuteWithStrategyInTransactionAsync( context => { context.Set().Add( @@ -1741,13 +1741,13 @@ public virtual void DatabaseGeneratedAttribute_autogenerates_values_when_set_to_ AdditionalDetails = new Details { Name = "Third Additional Name" } }); - context.SaveChanges(); + return context.SaveChangesAsync(); }); [ConditionalFact] - public virtual void MaxLengthAttribute_throws_while_inserting_value_longer_than_max_length() + public virtual async Task MaxLengthAttribute_throws_while_inserting_value_longer_than_max_length() { - ExecuteWithStrategyInTransaction( + await ExecuteWithStrategyInTransactionAsync( context => { context.Set().Add( @@ -1760,11 +1760,11 @@ public virtual void MaxLengthAttribute_throws_while_inserting_value_longer_than_ AdditionalDetails = new Details { Name = "Third Additional Name" } }); - context.SaveChanges(); + return context.SaveChangesAsync(); }); - ExecuteWithStrategyInTransaction( - context => + await ExecuteWithStrategyInTransactionAsync( + async context => { context.Set().Add( new One @@ -1778,7 +1778,7 @@ public virtual void MaxLengthAttribute_throws_while_inserting_value_longer_than_ Assert.Equal( "An error occurred while saving the entity changes. See the inner exception for details.", - Assert.Throws(() => context.SaveChanges()).Message); + (await Assert.ThrowsAsync(() => context.SaveChangesAsync())).Message); }); } @@ -2518,32 +2518,32 @@ protected class Profile13694 } [ConditionalFact] - public virtual void RequiredAttribute_for_navigation_throws_while_inserting_null_value() + public virtual async Task RequiredAttribute_for_navigation_throws_while_inserting_null_value() { - ExecuteWithStrategyInTransaction( + await ExecuteWithStrategyInTransactionAsync( context => { context.Set().Add( new BookDetails { AnotherBookId = 1 }); - context.SaveChanges(); + return context.SaveChangesAsync(); }); - ExecuteWithStrategyInTransaction( - context => + await ExecuteWithStrategyInTransactionAsync( + async context => { context.Set().Add(new BookDetails()); Assert.Equal( "An error occurred while saving the entity changes. See the inner exception for details.", - Assert.Throws(() => context.SaveChanges()).Message); + (await Assert.ThrowsAsync(() => context.SaveChangesAsync())).Message); }); } [ConditionalFact] - public virtual void RequiredAttribute_for_property_throws_while_inserting_null_value() + public virtual async Task RequiredAttribute_for_property_throws_while_inserting_null_value() { - ExecuteWithStrategyInTransaction( + await ExecuteWithStrategyInTransactionAsync( context => { context.Set().Add( @@ -2555,11 +2555,11 @@ public virtual void RequiredAttribute_for_property_throws_while_inserting_null_v AdditionalDetails = new Details { Name = "Two" } }); - context.SaveChanges(); + return context.SaveChangesAsync(); }); - ExecuteWithStrategyInTransaction( - context => + await ExecuteWithStrategyInTransactionAsync( + async context => { context.Set().Add( new One @@ -2572,38 +2572,38 @@ public virtual void RequiredAttribute_for_property_throws_while_inserting_null_v Assert.Equal( "An error occurred while saving the entity changes. See the inner exception for details.", - Assert.Throws(() => context.SaveChanges()).Message); + (await Assert.ThrowsAsync(() => context.SaveChangesAsync())).Message); }); } [ConditionalFact] - public virtual void StringLengthAttribute_throws_while_inserting_value_longer_than_max_length() + public virtual async Task StringLengthAttribute_throws_while_inserting_value_longer_than_max_length() { - ExecuteWithStrategyInTransaction( + await ExecuteWithStrategyInTransactionAsync( context => { context.Set().Add( new Two { Data = "ValidString" }); - context.SaveChanges(); + return context.SaveChangesAsync(); }); - ExecuteWithStrategyInTransaction( - context => + await ExecuteWithStrategyInTransactionAsync( + async context => { context.Set().Add( new Two { Data = "ValidButLongString" }); Assert.Equal( "An error occurred while saving the entity changes. See the inner exception for details.", - Assert.Throws(() => context.SaveChanges()).Message); + (await Assert.ThrowsAsync(() => context.SaveChangesAsync())).Message); }); } [ConditionalFact] - public virtual void TimestampAttribute_throws_if_value_in_database_changed() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task TimestampAttribute_throws_if_value_in_database_changed() + => ExecuteWithStrategyInTransactionAsync( + async context => { var clientRow = context.Set().First(r => r.Id == 1); clientRow.Data = "ChangedData"; @@ -2615,7 +2615,7 @@ public virtual void TimestampAttribute_throws_if_value_in_database_changed() innerContext.SaveChanges(); - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); }); [ConditionalFact] @@ -2800,7 +2800,7 @@ protected override bool ShouldLogCategory(string logCategory) => logCategory == DbLoggerCategory.Model.Name || logCategory == DbLoggerCategory.Model.Validation.Name; - protected override void Seed(PoolableDbContext context) + protected override Task SeedAsync(PoolableDbContext context) { context.Set().Add( new One @@ -2827,7 +2827,7 @@ protected override void Seed(PoolableDbContext context) context.Set().Add( new Book { Id = 1, AdditionalDetails = new Details { Name = "Book Name" } }); - context.SaveChanges(); + return context.SaveChangesAsync(); } } diff --git a/test/EFCore.Specification.Tests/F1FixtureBase.cs b/test/EFCore.Specification.Tests/F1FixtureBase.cs index 81907ab8ffc..0daf63bb51f 100644 --- a/test/EFCore.Specification.Tests/F1FixtureBase.cs +++ b/test/EFCore.Specification.Tests/F1FixtureBase.cs @@ -249,6 +249,6 @@ private static void ConfigureConstructorBinding( ); } - protected override void Seed(F1Context context) - => F1Context.Seed(context); + protected override Task SeedAsync(F1Context context) + => F1Context.SeedAsync(context); } diff --git a/test/EFCore.Specification.Tests/FieldMappingTestBase.cs b/test/EFCore.Specification.Tests/FieldMappingTestBase.cs index ea7242a3a50..05c2b38307d 100644 --- a/test/EFCore.Specification.Tests/FieldMappingTestBase.cs +++ b/test/EFCore.Specification.Tests/FieldMappingTestBase.cs @@ -141,8 +141,8 @@ public virtual void Projection_auto_props(bool tracking) => Projection("Id", "Title", tracking); [ConditionalFact] - public virtual void Update_auto_props() - => Update("Posts"); + public virtual Task Update_auto_props() + => UpdateAsync("Posts"); [ConditionalTheory] [InlineData(false)] @@ -235,8 +235,8 @@ public virtual void Projection_hiding_props(bool tracking) => Projection("Id", "Title", tracking); [ConditionalFact] - public virtual void Update_hiding_props() - => Update("Posts"); + public virtual Task Update_hiding_props() + => UpdateAsync("Posts"); [ConditionalTheory] [InlineData(false)] @@ -292,8 +292,8 @@ public virtual void Projection_full_props(bool tracking) => Projection("Id", "Title", tracking); [ConditionalFact] - public virtual void Update_full_props() - => Update("Posts"); + public virtual Task Update_full_props() + => UpdateAsync("Posts"); [ConditionalTheory] [InlineData(false)] @@ -349,8 +349,8 @@ public virtual void Projection_full_props_with_named_fields(bool tracking) => Projection("Id", "Title", tracking); [ConditionalFact] - public virtual void Update_full_props_with_named_fields() - => Update("Posts"); + public virtual Task Update_full_props_with_named_fields() + => UpdateAsync("Posts"); [ConditionalTheory] [InlineData(false)] @@ -406,8 +406,8 @@ public virtual void Projection_read_only_props(bool tracking) => Projection("Id", "Title", tracking); [ConditionalFact] - public virtual void Update_read_only_props() - => Update("Posts"); + public virtual Task Update_read_only_props() + => UpdateAsync("Posts"); [ConditionalTheory] [InlineData(false)] @@ -463,8 +463,8 @@ public virtual void Projection_props_with_IReadOnlyCollection(bool tracking) => Projection("Id", "Title", tracking); [ConditionalFact] - public virtual void Update_props_with_IReadOnlyCollection() - => Update("Posts"); + public virtual Task Update_props_with_IReadOnlyCollection() + => UpdateAsync("Posts"); [ConditionalTheory] [InlineData(false)] @@ -520,8 +520,8 @@ public virtual void Projection_read_only_props_with_named_fields(bool tracking) => Projection("Id", "Title", tracking); [ConditionalFact] - public virtual void Update_read_only_props_with_named_fields() - => Update("Posts"); + public virtual Task Update_read_only_props_with_named_fields() + => UpdateAsync("Posts"); [ConditionalTheory] [InlineData(false)] @@ -577,8 +577,8 @@ public virtual void Projection_write_only_props(bool tracking) => Projection("Id", "Title", tracking); [ConditionalFact] - public virtual void Update_write_only_props() - => Update("Posts"); + public virtual Task Update_write_only_props() + => UpdateAsync("Posts"); [ConditionalTheory] [InlineData(false)] @@ -634,8 +634,8 @@ public virtual void Projection_write_only_props_with_named_fields(bool tracking) => Projection("Id", "Title", tracking); [ConditionalFact] - public virtual void Update_write_only_props_with_named_fields() - => Update("Posts"); + public virtual Task Update_write_only_props_with_named_fields() + => UpdateAsync("Posts"); [ConditionalTheory] [InlineData(false)] @@ -691,8 +691,8 @@ public virtual void Projection_fields_only(bool tracking) => Projection("_id", "_title", tracking); [ConditionalFact] - public virtual void Update_fields_only() - => Update("Posts"); + public virtual Task Update_fields_only() + => UpdateAsync("Posts"); [ConditionalTheory] [InlineData(false)] @@ -748,8 +748,8 @@ public virtual void Projection_fields_only_only_for_navs_too(bool tracking) => Projection("_id", "_title", tracking); [ConditionalFact] - public virtual void Update_fields_only_only_for_navs_too() - => Update("_posts"); + public virtual Task Update_fields_only_only_for_navs_too() + => UpdateAsync("_posts"); protected virtual void Load_collection(string navigation) where TBlog : class, IBlogAccessor, new() @@ -826,17 +826,16 @@ protected virtual void Projection(string property1, string property2, boo Assert.Equal("Post21", posts.Single(e => e.Prop1 == 21).Prop2); } - protected virtual void Update(string navigation) + protected virtual Task UpdateAsync(string navigation) where TBlog : class, IBlogAccessor, new() - => TestHelpers.ExecuteWithStrategyInTransaction( - CreateContext, UseTransaction, - context => + => TestHelpers.ExecuteWithStrategyInTransactionAsync( + CreateContext, UseTransaction, async context => { - var blogs = context.Set().ToList(); + var blogs = await context.Set().ToListAsync(); foreach (var blog in blogs) { - context.Entry(blog).Collection(navigation).Load(); + await context.Entry(blog).Collection(navigation).LoadAsync(); blog.AccessTitle += "Updated"; @@ -848,17 +847,16 @@ protected virtual void Update(string navigation) AssertGraph(blogs, "Updated"); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertGraph(blogs, "Updated"); - }, - context => + }, async context => { var blogs = context.Set().ToList(); foreach (var blog in blogs) { - context.Entry(blog).Collection(navigation).Load(); + await context.Entry(blog).Collection(navigation).LoadAsync(); } AssertGraph(blogs, "Updated"); @@ -2146,7 +2144,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con } } - protected override void Seed(PoolableDbContext context) + protected override async Task SeedAsync(PoolableDbContext context) { _isSeeding.Value = true; try @@ -2194,7 +2192,7 @@ protected override void Seed(PoolableDbContext context) context.Add(new OneToOneFieldNavPrincipal { Id = 1, Name = "OneToOneFieldNavPrincipal1" }); - context.SaveChanges(); + await context.SaveChangesAsync(); } finally { diff --git a/test/EFCore.Specification.Tests/FieldsOnlyLoadTestBase.cs b/test/EFCore.Specification.Tests/FieldsOnlyLoadTestBase.cs index 30efc851aeb..94da8549e69 100644 --- a/test/EFCore.Specification.Tests/FieldsOnlyLoadTestBase.cs +++ b/test/EFCore.Specification.Tests/FieldsOnlyLoadTestBase.cs @@ -4847,7 +4847,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con }); } - protected override void Seed(PoolableDbContext context) + protected override Task SeedAsync(PoolableDbContext context) { context.Add( new Parent @@ -4868,7 +4868,7 @@ protected override void Seed(PoolableDbContext context) // context.Add( // new SimpleProduct { Deposit = new Deposit() }); - context.SaveChanges(); + return context.SaveChangesAsync(); } } } diff --git a/test/EFCore.Specification.Tests/FindTestBase.cs b/test/EFCore.Specification.Tests/FindTestBase.cs index 236fe939a78..982523e9895 100644 --- a/test/EFCore.Specification.Tests/FindTestBase.cs +++ b/test/EFCore.Specification.Tests/FindTestBase.cs @@ -785,7 +785,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con modelBuilder.Entity().Property(typeof(int), "Id").ValueGeneratedNever(); } - protected override void Seed(PoolableDbContext context) + protected override Task SeedAsync(PoolableDbContext context) { context.AddRange( new IntKey { Id = 77, Foo = "Smokey" }, @@ -810,7 +810,7 @@ protected override void Seed(PoolableDbContext context) entry.Property("Id").CurrentValue = 77; entry.State = EntityState.Added; - context.SaveChanges(); + return context.SaveChangesAsync(); } } diff --git a/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBase.cs b/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBase.cs index 5cabd819b70..b98aabdf0de 100644 --- a/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBase.cs +++ b/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBase.cs @@ -620,21 +620,39 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con modelBuilder.Entity>( b => { - b.HasKey(e => new { e.TargetId, e.SourceId, e.PrimaryGroup }); + b.HasKey( + e => new + { + e.TargetId, + e.SourceId, + e.PrimaryGroup + }); b.Property(e => e.PrimaryGroup).ValueGeneratedOnAdd(); }); modelBuilder.Entity>( b => { - b.HasKey(e => new { e.TargetId, e.SourceId, e.PrimaryGroup }); + b.HasKey( + e => new + { + e.TargetId, + e.SourceId, + e.PrimaryGroup + }); b.Property(e => e.PrimaryGroup).ValueGeneratedOnAdd(); }); modelBuilder.Entity>( b => { - b.HasKey(e => new { e.TargetId, e.SourceId, e.PrimaryGroup }); + b.HasKey( + e => new + { + e.TargetId, + e.SourceId, + e.PrimaryGroup + }); b.Property(e => e.PrimaryGroup).ValueGeneratedOnAdd(); }); @@ -822,7 +840,7 @@ protected virtual object CreateFullGraph() } }; - protected override void Seed(PoolableDbContext context) + protected override Task SeedAsync(PoolableDbContext context) { var tracker = new KeyValueEntityTracker(); @@ -848,7 +866,7 @@ protected override void Seed(PoolableDbContext context) context.Add(new SharedFkDependant { Root = root, Parent = parent }); - context.SaveChanges(); + return context.SaveChangesAsync(); } public class KeyValueEntityTracker @@ -897,9 +915,9 @@ protected virtual OwnerRoot CreateOwnerRoot() } }; - protected Root LoadRequiredGraph(DbContext context) + protected Task LoadRequiredGraphAsync(DbContext context) => QueryRequiredGraph(context) - .Single(IsTheRoot); + .SingleAsync(IsTheRoot); protected IOrderedQueryable QueryRequiredGraph(DbContext context) => ModifyQueryRoot(context.Set()) @@ -907,9 +925,9 @@ protected IOrderedQueryable QueryRequiredGraph(DbContext context) .Include(e => e.RequiredSingle).ThenInclude(e => e.Single) .OrderBy(e => e.Id); - protected Root LoadOptionalGraph(DbContext context) + protected Task LoadOptionalGraphAsync(DbContext context) => QueryOptionalGraph(context) - .Single(IsTheRoot); + .SingleAsync(IsTheRoot); protected IOrderedQueryable QueryOptionalGraph(DbContext context) => ModifyQueryRoot(context.Set()) @@ -920,9 +938,9 @@ protected IOrderedQueryable QueryOptionalGraph(DbContext context) .Include(e => e.OptionalSingleMoreDerived).ThenInclude(e => e.Single) .OrderBy(e => e.Id); - protected Root LoadRequiredNonPkGraph(DbContext context) + protected Task LoadRequiredNonPkGraphAsync(DbContext context) => QueryRequiredNonPkGraph(context) - .Single(IsTheRoot); + .SingleAsync(IsTheRoot); protected IOrderedQueryable QueryRequiredNonPkGraph(DbContext context) => ModifyQueryRoot(context.Set()) @@ -934,9 +952,9 @@ protected IOrderedQueryable QueryRequiredNonPkGraph(DbContext context) .Include(e => e.RequiredNonPkSingleMoreDerived).ThenInclude(e => e.DerivedRoot) .OrderBy(e => e.Id); - protected Root LoadRequiredAkGraph(DbContext context) + protected Task LoadRequiredAkGraphAsync(DbContext context) => QueryRequiredAkGraph(context) - .Single(IsTheRoot); + .SingleAsync(IsTheRoot); protected IOrderedQueryable QueryRequiredAkGraph(DbContext context) => ModifyQueryRoot(context.Set()) @@ -946,9 +964,9 @@ protected IOrderedQueryable QueryRequiredAkGraph(DbContext context) .Include(e => e.RequiredSingleAk).ThenInclude(e => e.SingleComposite) .OrderBy(e => e.Id); - protected Root LoadOptionalAkGraph(DbContext context) + protected Task LoadOptionalAkGraphAsync(DbContext context) => QueryOptionalAkGraph(context) - .Single(IsTheRoot); + .SingleAsync(IsTheRoot); protected IOrderedQueryable QueryOptionalAkGraph(DbContext context) => ModifyQueryRoot(context.Set()) @@ -960,9 +978,9 @@ protected IOrderedQueryable QueryOptionalAkGraph(DbContext context) .Include(e => e.OptionalSingleAkMoreDerived).ThenInclude(e => e.Single) .OrderBy(e => e.Id); - protected Root LoadRequiredNonPkAkGraph(DbContext context) + protected Task LoadRequiredNonPkAkGraphAsync(DbContext context) => QueryRequiredNonPkAkGraph(context) - .Single(IsTheRoot); + .SingleAsync(IsTheRoot); protected IOrderedQueryable QueryRequiredNonPkAkGraph(DbContext context) => ModifyQueryRoot(context.Set()) @@ -974,9 +992,9 @@ protected IOrderedQueryable QueryRequiredNonPkAkGraph(DbContext context) .Include(e => e.RequiredNonPkSingleAkMoreDerived).ThenInclude(e => e.DerivedRoot) .OrderBy(e => e.Id); - protected Root LoadOptionalOneToManyGraph(DbContext context) + protected Task LoadOptionalOneToManyGraphAsync(DbContext context) => QueryOptionalOneToManyGraph(context) - .Single(IsTheRoot); + .SingleAsync(IsTheRoot); protected IOrderedQueryable QueryOptionalOneToManyGraph(DbContext context) => ModifyQueryRoot(context.Set()) @@ -986,9 +1004,9 @@ protected IOrderedQueryable QueryOptionalOneToManyGraph(DbContext context) .Include(e => e.OptionalChildrenAk).ThenInclude(e => e.CompositeChildren) .OrderBy(e => e.Id); - protected Root LoadRequiredCompositeGraph(DbContext context) + protected Task LoadRequiredCompositeGraphAsync(DbContext context) => QueryRequiredCompositeGraph(context) - .Single(IsTheRoot); + .SingleAsync(IsTheRoot); protected IOrderedQueryable QueryRequiredCompositeGraph(DbContext context) => ModifyQueryRoot(context.Set()) @@ -4577,15 +4595,6 @@ private void NotifyChanging(string propertyName) protected DbContext CreateContext() => Fixture.CreateContext(); - protected virtual void ExecuteWithStrategyInTransaction( - Action testOperation, - Action nestedTestOperation1 = null, - Action nestedTestOperation2 = null, - Action nestedTestOperation3 = null) - => TestHelpers.ExecuteWithStrategyInTransaction( - CreateContext, UseTransaction, - testOperation, nestedTestOperation1, nestedTestOperation2, nestedTestOperation3); - protected virtual Task ExecuteWithStrategyInTransactionAsync( Func testOperation, Func nestedTestOperation1 = null, diff --git a/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBaseMiscellaneous.cs b/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBaseMiscellaneous.cs index 32831cd660b..33c7d260379 100644 --- a/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBaseMiscellaneous.cs +++ b/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBaseMiscellaneous.cs @@ -184,10 +184,7 @@ public virtual Task Throws_for_single_property_nullable_bool_key_with_default_va protected async Task Throws_for_single_property_key_with_default_value_generation(bool async, T initialValue) where T : new() { - var inserted = new BoolOnlyKey() - { - PrimaryGroup = initialValue - }; + var inserted = new BoolOnlyKey() { PrimaryGroup = initialValue }; await ExecuteWithStrategyInTransactionAsync( async context => @@ -219,10 +216,9 @@ public virtual async Task Saving_multiple_modified_entities_with_the_same_key_do context.Add(city); context.SaveChanges(); } - }, - context => + }, async context => { - var city = context.Set().Include(x => x.Colleges).Single(); + var city = await context.Set().Include(x => x.Colleges).SingleAsync(); var college = city.Colleges.Single(); city.Colleges.Clear(); @@ -241,8 +237,6 @@ public virtual async Task Saving_multiple_modified_entities_with_the_same_key_do Assert.Equal(EntityState.Deleted, context.Entry(college).State); Assert.Equal(EntityState.Unchanged, context.Entry(city).State); } - - return Task.CompletedTask; }); [ConditionalTheory] // Issue #22465 @@ -783,15 +777,15 @@ public async Task Discriminator_values_are_not_marked_as_unknown(bool async) }); [ConditionalFact] - public virtual void Avoid_nulling_shared_FK_property_when_deleting() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Avoid_nulling_shared_FK_property_when_deleting() + => ExecuteWithStrategyInTransactionAsync( + async context => { - var root = context + var root = await context .Set() .Include(e => e.Parents) .Include(e => e.Dependants) - .Single(); + .SingleAsync(); Assert.Equal(3, context.ChangeTracker.Entries().Count()); @@ -826,7 +820,7 @@ public virtual void Avoid_nulling_shared_FK_property_when_deleting() Assert.Equal(root.Id, parent.RootId); Assert.Equal(parent.Id, parent.DependantId); - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { @@ -839,7 +833,7 @@ public virtual void Avoid_nulling_shared_FK_property_when_deleting() Assert.Equal(root.Id, parent.RootId); Assert.Null(parent.DependantId); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.Equal(2, context.ChangeTracker.Entries().Count()); @@ -856,16 +850,15 @@ public virtual void Avoid_nulling_shared_FK_property_when_deleting() Assert.Equal(root.Id, parent.RootId); Assert.Null(parent.DependantId); } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction) { - var root = context + var root = await context .Set() .Include(e => e.Parents) .Include(e => e.Dependants) - .Single(); + .SingleAsync(); Assert.Equal(2, context.ChangeTracker.Entries().Count()); @@ -883,15 +876,15 @@ public virtual void Avoid_nulling_shared_FK_property_when_deleting() [ConditionalTheory] [InlineData(false)] [InlineData(true)] - public virtual void Avoid_nulling_shared_FK_property_when_nulling_navigation(bool nullPrincipal) - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Avoid_nulling_shared_FK_property_when_nulling_navigation(bool nullPrincipal) + => ExecuteWithStrategyInTransactionAsync( + async context => { - var root = context + var root = await context .Set() .Include(e => e.Parents) .Include(e => e.Dependants) - .Single(); + .SingleAsync(); Assert.Equal(3, context.ChangeTracker.Entries().Count()); @@ -933,7 +926,7 @@ public virtual void Avoid_nulling_shared_FK_property_when_nulling_navigation(boo Assert.Equal(root.Id, parent.RootId); Assert.Null(parent.DependantId); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.Equal(3, context.ChangeTracker.Entries().Count()); @@ -945,14 +938,13 @@ public virtual void Avoid_nulling_shared_FK_property_when_nulling_navigation(boo Assert.Equal(root.Id, dependent.RootId); Assert.Equal(root.Id, parent.RootId); Assert.Null(parent.DependantId); - }, - context => + }, async context => { - var root = context + var root = await context .Set() .Include(e => e.Parents) .Include(e => e.Dependants) - .Single(); + .SingleAsync(); Assert.Equal(3, context.ChangeTracker.Entries().Count()); @@ -970,11 +962,11 @@ public virtual void Avoid_nulling_shared_FK_property_when_nulling_navigation(boo }); [ConditionalFact] - public virtual void Mutating_discriminator_value_throws_by_convention() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Mutating_discriminator_value_throws_by_convention() + => ExecuteWithStrategyInTransactionAsync( + async context => { - var instance = context.Set().First(); + var instance = await context.Set().FirstAsync(); var propertyEntry = context.Entry(instance).Property("Discriminator"); @@ -984,17 +976,17 @@ public virtual void Mutating_discriminator_value_throws_by_convention() Assert.Equal( CoreStrings.PropertyReadOnlyAfterSave("Discriminator", nameof(OptionalSingle1Derived)), - Assert.Throws(() => context.SaveChanges()).Message); + (await Assert.ThrowsAsync(() => context.SaveChangesAsync())).Message); }); [ConditionalFact] - public virtual void Mutating_discriminator_value_can_be_configured_to_allow_mutation() + public virtual Task Mutating_discriminator_value_can_be_configured_to_allow_mutation() { var id = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var instance = context.Set().First(); + var instance = await context.Set().FirstAsync(); var propertyEntry = context.Entry(instance).Property(e => e.Disc); id = instance.Id; @@ -1003,11 +995,10 @@ public virtual void Mutating_discriminator_value_can_be_configured_to_allow_muta propertyEntry.CurrentValue = new MyDiscriminator(1); - context.SaveChanges(); - }, - context => + await context.SaveChangesAsync(); + }, async context => { - var instance = context.Set().First(e => e.Id == id); + var instance = await context.Set().FirstAsync(e => e.Id == id); var propertyEntry = context.Entry(instance).Property(e => e.Disc); Assert.IsType(instance); @@ -1019,12 +1010,12 @@ public virtual void Mutating_discriminator_value_can_be_configured_to_allow_muta [InlineData((int)ChangeMechanism.Fk)] [InlineData((int)ChangeMechanism.Dependent)] [InlineData((int)(ChangeMechanism.Dependent | ChangeMechanism.Fk))] - public virtual void Changes_to_Added_relationships_are_picked_up(ChangeMechanism changeMechanism) + public virtual Task Changes_to_Added_relationships_are_picked_up(ChangeMechanism changeMechanism) { var id = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var entity = new OptionalSingle1(); @@ -1057,15 +1048,14 @@ public virtual void Changes_to_Added_relationships_are_picked_up(ChangeMechanism Assert.True(context.ChangeTracker.HasChanges()); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); id = entity.Id; - }, - context => + }, async context => { - var entity = context.Set().Include(e => e.Root).Single(e => e.Id == id); + var entity = await context.Set().Include(e => e.Root).SingleAsync(e => e.Id == id); Assert.Null(entity.Root); Assert.Null(entity.RootId); @@ -1081,7 +1071,7 @@ public virtual void Changes_to_Added_relationships_are_picked_up(ChangeMechanism [InlineData(true, CascadeTiming.Immediate)] [InlineData(true, CascadeTiming.Never)] [InlineData(true, null)] - public virtual void New_FK_is_not_cleared_on_old_dependent_delete( + public virtual Task New_FK_is_not_cleared_on_old_dependent_delete( bool loadNewParent, CascadeTiming? deleteOrphansTiming) { @@ -1089,18 +1079,18 @@ public virtual void New_FK_is_not_cleared_on_old_dependent_delete( var childId = 0; int? newFk = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - var removed = context.Set().OrderBy(e => e.Id).First(); - var child = context.Set().OrderBy(e => e.Id).First(e => e.ParentId == removed.Id); + var removed = await context.Set().OrderBy(e => e.Id).FirstAsync(); + var child = await context.Set().OrderBy(e => e.Id).FirstAsync(e => e.ParentId == removed.Id); removedId = removed.Id; childId = child.Id; - newFk = context.Set().AsNoTracking().Single(e => e.Id != removed.Id).Id; + newFk = (await context.Set().AsNoTracking().SingleAsync(e => e.Id != removed.Id)).Id; var newParent = loadNewParent ? context.Set().Find(newFk) : null; @@ -1112,11 +1102,11 @@ public virtual void New_FK_is_not_cleared_on_old_dependent_delete( if (Fixture.ForceClientNoAction) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -1133,16 +1123,15 @@ public virtual void New_FK_is_not_cleared_on_old_dependent_delete( Assert.Null((child.Parent)); } } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction && !Fixture.NoStoreCascades) { - Assert.Null(context.Set().Find(removedId)); + Assert.Null(await context.Set().FindAsync(removedId)); - var child = context.Set().Find(childId); - var newParent = loadNewParent ? context.Set().Find(newFk) : null; + var child = await context.Set().FindAsync(childId); + var newParent = loadNewParent ? await context.Set().FindAsync(newFk) : null; Assert.Equal(newFk, child.ParentId); @@ -1166,13 +1155,13 @@ public virtual void New_FK_is_not_cleared_on_old_dependent_delete( [InlineData(CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never)] [InlineData(null)] - public virtual void No_fixup_to_Deleted_entities( + public virtual async Task No_fixup_to_Deleted_entities( CascadeTiming? deleteOrphansTiming) { using var context = CreateContext(); context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - var root = LoadOptionalGraph(context); + var root = await LoadOptionalGraphAsync(context); var existing = root.OptionalChildren.OrderBy(e => e.Id).First(); Assert.False(context.ChangeTracker.HasChanges()); @@ -1185,7 +1174,7 @@ public virtual void No_fixup_to_Deleted_entities( Assert.True(context.ChangeTracker.HasChanges()); - var queried = context.Set().ToList(); + var queried = await context.Set().ToListAsync(); Assert.Null(existing.Parent); Assert.Null(existing.ParentId); @@ -1197,9 +1186,9 @@ public virtual void No_fixup_to_Deleted_entities( } [ConditionalFact] - public virtual void Notification_entities_can_have_indexes() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Notification_entities_can_have_indexes() + => ExecuteWithStrategyInTransactionAsync( + async context => { var produce = new Produce { Name = "Apple", BarCode = 77 }; context.Add(produce); @@ -1208,7 +1197,7 @@ public virtual void Notification_entities_can_have_indexes() Assert.True(context.ChangeTracker.HasChanges()); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -1223,7 +1212,7 @@ public virtual void Notification_entities_can_have_indexes() Assert.True(context.ChangeTracker.HasChanges()); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -1231,11 +1220,11 @@ public virtual void Notification_entities_can_have_indexes() }); [ConditionalFact] - public virtual void Resetting_a_deleted_reference_fixes_up_again() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Resetting_a_deleted_reference_fixes_up_again() + => ExecuteWithStrategyInTransactionAsync( + async context => { - var bloog = context.Set().Include(e => e.Poosts).Single(); + var bloog = await context.Set().Include(e => e.Poosts).SingleAsync(); var poost1 = bloog.Poosts.First(); var poost2 = bloog.Poosts.Skip(1).First(); @@ -1294,7 +1283,7 @@ public virtual void Resetting_a_deleted_reference_fixes_up_again() { Assert.True(context.ChangeTracker.HasChanges()); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -1305,18 +1294,18 @@ public virtual void Resetting_a_deleted_reference_fixes_up_again() }); [ConditionalFact] - public virtual void Detaching_principal_entity_will_remove_references_to_it() - => ExecuteWithStrategyInTransaction( - context => - { - var root = LoadOptionalGraph(context); - LoadRequiredGraph(context); - LoadOptionalAkGraph(context); - LoadRequiredAkGraph(context); - LoadRequiredCompositeGraph(context); - LoadRequiredNonPkGraph(context); - LoadOptionalOneToManyGraph(context); - LoadRequiredNonPkAkGraph(context); + public virtual Task Detaching_principal_entity_will_remove_references_to_it() + => ExecuteWithStrategyInTransactionAsync( + async context => + { + var root = await LoadOptionalGraphAsync(context); + await LoadRequiredGraphAsync(context); + await LoadOptionalAkGraphAsync(context); + await LoadRequiredAkGraphAsync(context); + await LoadRequiredCompositeGraphAsync(context); + await LoadRequiredNonPkGraphAsync(context); + await LoadOptionalOneToManyGraphAsync(context); + await LoadRequiredNonPkAkGraphAsync(context); var optionalSingle = root.OptionalSingle; var requiredSingle = root.RequiredSingle; @@ -1396,18 +1385,18 @@ public virtual void Detaching_principal_entity_will_remove_references_to_it() }); [ConditionalFact] - public virtual void Detaching_dependent_entity_will_not_remove_references_to_it() - => ExecuteWithStrategyInTransaction( - context => - { - var root = LoadOptionalGraph(context); - LoadRequiredGraph(context); - LoadOptionalAkGraph(context); - LoadRequiredAkGraph(context); - LoadRequiredCompositeGraph(context); - LoadRequiredNonPkGraph(context); - LoadOptionalOneToManyGraph(context); - LoadRequiredNonPkAkGraph(context); + public virtual Task Detaching_dependent_entity_will_not_remove_references_to_it() + => ExecuteWithStrategyInTransactionAsync( + async context => + { + var root = await LoadOptionalGraphAsync(context); + await LoadRequiredGraphAsync(context); + await LoadOptionalAkGraphAsync(context); + await LoadRequiredAkGraphAsync(context); + await LoadRequiredCompositeGraphAsync(context); + await LoadRequiredNonPkGraphAsync(context); + await LoadOptionalOneToManyGraphAsync(context); + await LoadRequiredNonPkAkGraphAsync(context); var optionalSingle = root.OptionalSingle; var requiredSingle = root.RequiredSingle; @@ -1540,20 +1529,20 @@ public virtual void Detaching_dependent_entity_will_not_remove_references_to_it( [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] [InlineData(null, null)] - public virtual void Re_childing_parent_to_new_child_with_delete( + public virtual Task Re_childing_parent_to_new_child_with_delete( CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) { var oldId = 0; var newId = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming ?? CascadeTiming.Never; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - var parent = context.Set().Include(p => p.ChildAsAParent).Single(); + var parent = await context.Set().Include(p => p.ChildAsAParent).SingleAsync(); var oldChild = parent.ChildAsAParent; oldId = oldChild.Id; @@ -1565,7 +1554,7 @@ public virtual void Re_childing_parent_to_new_child_with_delete( Assert.True(context.ChangeTracker.HasChanges()); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -1583,10 +1572,9 @@ public virtual void Re_childing_parent_to_new_child_with_delete( Assert.Equal(EntityState.Detached, context.Entry(oldChild).State); Assert.Equal(EntityState.Unchanged, context.Entry(newChild).State); Assert.Equal(EntityState.Unchanged, context.Entry(parent).State); - }, - context => + }, async context => { - var parent = context.Set().Include(p => p.ChildAsAParent).Single(); + var parent = await context.Set().Include(p => p.ChildAsAParent).SingleAsync(); Assert.Equal(newId, parent.ChildAsAParentId); Assert.Equal(newId, parent.ChildAsAParent.Id); @@ -1595,15 +1583,15 @@ public virtual void Re_childing_parent_to_new_child_with_delete( } [ConditionalFact] - public virtual void Sometimes_not_calling_DetectChanges_when_required_does_not_throw_for_null_ref() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Sometimes_not_calling_DetectChanges_when_required_does_not_throw_for_null_ref() + => ExecuteWithStrategyInTransactionAsync( + async context => { - var dependent = context.Set().Single(); + var dependent = await context.Set().SingleAsync(); dependent.BadCustomerId = null; - var principal = context.Set().Single(); + var principal = await context.Set().SingleAsync(); principal.Status++; @@ -1613,18 +1601,17 @@ public virtual void Sometimes_not_calling_DetectChanges_when_required_does_not_t Assert.True(context.ChangeTracker.HasChanges()); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); Assert.Null(dependent.BadCustomerId); Assert.Null(dependent.BadCustomer); Assert.Empty(principal.BadOrders); - }, - context => + }, async context => { - var dependent = context.Set().Single(); - var principal = context.Set().Single(); + var dependent = await context.Set().SingleAsync(); + var principal = await context.Set().SingleAsync(); Assert.Null(dependent.BadCustomerId); Assert.Null(dependent.BadCustomer); @@ -1632,9 +1619,9 @@ public virtual void Sometimes_not_calling_DetectChanges_when_required_does_not_t }); [ConditionalFact] - public virtual void Can_add_valid_first_dependent_when_multiple_possible_principal_sides() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Can_add_valid_first_dependent_when_multiple_possible_principal_sides() + => ExecuteWithStrategyInTransactionAsync( + async context => { var quizTask = new QuizTask(); quizTask.Choices.Add(new TaskChoice()); @@ -1643,25 +1630,24 @@ public virtual void Can_add_valid_first_dependent_when_multiple_possible_princip Assert.True(context.ChangeTracker.HasChanges()); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); - }, - context => + }, async context => { - var quizTask = context.Set().Include(e => e.Choices).Single(); + var quizTask = await context.Set().Include(e => e.Choices).SingleAsync(); Assert.Equal(quizTask.Id, quizTask.Choices.Single().QuestTaskId); - Assert.Same(quizTask.Choices.Single(), context.Set().Single()); + Assert.Same(quizTask.Choices.Single(), await context.Set().SingleAsync()); Assert.Empty(context.Set().Include(e => e.Choices)); }); [ConditionalFact] - public virtual void Can_add_valid_second_dependent_when_multiple_possible_principal_sides() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Can_add_valid_second_dependent_when_multiple_possible_principal_sides() + => ExecuteWithStrategyInTransactionAsync( + async context => { var hiddenAreaTask = new HiddenAreaTask(); hiddenAreaTask.Choices.Add(new TaskChoice()); @@ -1670,25 +1656,24 @@ public virtual void Can_add_valid_second_dependent_when_multiple_possible_princi Assert.True(context.ChangeTracker.HasChanges()); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); - }, - context => + }, async context => { - var hiddenAreaTask = context.Set().Include(e => e.Choices).Single(); + var hiddenAreaTask = await context.Set().Include(e => e.Choices).SingleAsync(); Assert.Equal(hiddenAreaTask.Id, hiddenAreaTask.Choices.Single().QuestTaskId); - Assert.Same(hiddenAreaTask.Choices.Single(), context.Set().Single()); + Assert.Same(hiddenAreaTask.Choices.Single(), await context.Set().SingleAsync()); Assert.Empty(context.Set().Include(e => e.Choices)); }); [ConditionalFact] - public virtual void Can_add_multiple_dependents_when_multiple_possible_principal_sides() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Can_add_multiple_dependents_when_multiple_possible_principal_sides() + => ExecuteWithStrategyInTransactionAsync( + async context => { var quizTask = new QuizTask(); quizTask.Choices.Add(new TaskChoice()); @@ -1704,14 +1689,13 @@ public virtual void Can_add_multiple_dependents_when_multiple_possible_principal Assert.True(context.ChangeTracker.HasChanges()); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); - }, - context => + }, async context => { - var quizTask = context.Set().Include(e => e.Choices).Single(); - var hiddenAreaTask = context.Set().Include(e => e.Choices).Single(); + var quizTask = await context.Set().Include(e => e.Choices).SingleAsync(); + var hiddenAreaTask = await context.Set().Include(e => e.Choices).SingleAsync(); Assert.Equal(2, quizTask.Choices.Count); foreach (var quizTaskChoice in quizTask.Choices) @@ -1741,12 +1725,12 @@ public virtual Task Sever_relationship_that_will_later_be_deleted(bool async) => ExecuteWithStrategyInTransactionAsync( async context => { - var swedes = context.Set() + var swedes = await context.Set() .Include(x => x.Carrot) .ThenInclude(x => x.Turnips) .Include(x => x.Swede) .ThenInclude(x => x.TurnipSwedes) - .Single(x => x.Id == 1); + .SingleAsync(x => x.Id == 1); swedes.Carrot.Turnips.Clear(); swedes.Swede.TurnipSwedes.Clear(); @@ -1764,16 +1748,15 @@ public virtual Task Sever_relationship_that_will_later_be_deleted(bool async) }); [ConditionalFact] // Issue #32168 - public virtual void Save_changed_owned_one_to_one() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Save_changed_owned_one_to_one() + => ExecuteWithStrategyInTransactionAsync( + async context => { context.Add(CreateOwnerRoot()); - context.SaveChanges(); - }, - context => + await context.SaveChangesAsync(); + }, async context => { - var root = context.Set().Single(); + var root = await context.Set().SingleAsync(); if (Fixture.ForceClientNoAction) { @@ -1788,7 +1771,7 @@ public virtual void Save_changed_owned_one_to_one() Assert.True(context.ChangeTracker.HasChanges()); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -1796,10 +1779,9 @@ public virtual void Save_changed_owned_one_to_one() Assert.Equal("OS2`", root.OptionalSingle.Single.Name); Assert.Equal("RS`", root.RequiredSingle.Name); Assert.Equal("RS2`", root.RequiredSingle.Single.Name); - }, - context => + }, async context => { - var root = context.Set().Single(); + var root = await context.Set().SingleAsync(); Assert.Equal("OS`", root.OptionalSingle.Name); Assert.Equal("OS2`", root.OptionalSingle.Single.Name); Assert.Equal("RS`", root.RequiredSingle.Name); @@ -1807,17 +1789,16 @@ public virtual void Save_changed_owned_one_to_one() }); [ConditionalFact] - public virtual void Save_changed_owned_one_to_many() + public virtual Task Save_changed_owned_one_to_many() { - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.Add(CreateOwnerRoot()); - context.SaveChanges(); - }, - context => + await context.SaveChangesAsync(); + }, async context => { - var root = context.Set().Single(); + var root = await context.Set().SingleAsync(); var optionalChildren = root.OptionalChildren.Single(e => e.Name == "OC1"); var requiredChildren = root.RequiredChildren.Single(e => e.Name == "RC1"); @@ -1838,15 +1819,14 @@ public virtual void Save_changed_owned_one_to_many() Assert.True(context.ChangeTracker.HasChanges()); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); AssertGraph(root); - }, - context => + }, async context => { - var root = context.Set().Single(); + var root = await context.Set().SingleAsync(); AssertGraph(root); }); @@ -1890,7 +1870,7 @@ public virtual Task Update_root_by_collection_replacement_of_inserted_first_leve => ExecuteWithStrategyInTransactionAsync( async context => { - PopulateGraph(context); + await PopulateGraphAsync(context); var newRoot = BuildNewRoot(firstLevel1: true, secondLevel1: true, thirdLevel1: true, firstLevel2: true); Assert.Equal(1, context.Set().Count(x => x.BayazId == 1)); @@ -1910,7 +1890,7 @@ public virtual Task Update_root_by_collection_replacement_of_deleted_first_level => ExecuteWithStrategyInTransactionAsync( async context => { - PopulateGraph(context); + await PopulateGraphAsync(context); var newRoot = BuildNewRoot(); Assert.Equal(1, context.Set().Count(x => x.BayazId == 1)); @@ -1928,7 +1908,7 @@ public virtual Task Update_root_by_collection_replacement_of_inserted_second_lev => ExecuteWithStrategyInTransactionAsync( async context => { - PopulateGraph(context); + await PopulateGraphAsync(context); var newRoot = BuildNewRoot(firstLevel1: true, secondLevel1: true, thirdLevel1: true, firstLevel2: true, secondLevel2: true); Assert.Equal(1, context.Set().Count(x => x.BayazId == 1)); @@ -1957,7 +1937,7 @@ public virtual Task Update_root_by_collection_replacement_of_deleted_second_leve => ExecuteWithStrategyInTransactionAsync( async context => { - PopulateGraph(context); + await PopulateGraphAsync(context); var newRoot = BuildNewRoot(firstLevel1: true); Assert.Equal(1, context.Set().Count(x => x.BayazId == 1)); @@ -1977,7 +1957,7 @@ public virtual Task Update_root_by_collection_replacement_of_inserted_first_leve => ExecuteWithStrategyInTransactionAsync( async context => { - PopulateGraph(context); + await PopulateGraphAsync(context); var newRoot = BuildNewRoot( firstLevel1: true, secondLevel1: true, thirdLevel1: true, firstLevel2: true, secondLevel2: true, thirdLevel2: true); @@ -2009,7 +1989,7 @@ public virtual Task Update_root_by_collection_replacement_of_deleted_third_level => ExecuteWithStrategyInTransactionAsync( async context => { - PopulateGraph(context); + await PopulateGraphAsync(context); var newRoot = BuildNewRoot(firstLevel1: true, secondLevel1: true); Assert.Equal(1, context.Set().Count(x => x.BayazId == 1)); @@ -2026,11 +2006,11 @@ public virtual Task Update_root_by_collection_replacement_of_deleted_third_level protected async Task UpdateRoot(DbContext context, Bayaz newRoot, bool async) { - var existingRoot = context.Set() + var existingRoot = await context.Set() .Include(x => x.FirstLaw) .ThenInclude(x => x.SecondLaw) .ThenInclude(x => x.ThirdLaw) - .Single(x => x.BayazId == newRoot.BayazId); + .SingleAsync(x => x.BayazId == newRoot.BayazId); existingRoot.BayazName = newRoot.BayazName; existingRoot.FirstLaw = newRoot.FirstLaw; @@ -2057,7 +2037,7 @@ protected async Task UpdateRoot(DbContext context, Bayaz newRoot, bool asy return true; } - protected void PopulateGraph(DbContext context) + protected Task PopulateGraphAsync(DbContext context) { context.Add(new Bayaz { BayazId = 1, BayazName = "bayaz" }); @@ -2085,7 +2065,7 @@ protected void PopulateGraph(DbContext context) SecondLawId = 111 }); - context.SaveChanges(); + return context.SaveChangesAsync(); } protected Bayaz BuildNewRoot( diff --git a/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBaseOneToMany.cs b/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBaseOneToMany.cs index 428e81f17cf..43de76256a9 100644 --- a/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBaseOneToMany.cs +++ b/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBaseOneToMany.cs @@ -71,7 +71,7 @@ public abstract partial class GraphUpdatesTestBase [InlineData((int)(ChangeMechanism.Fk | ChangeMechanism.Dependent), true, null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), false, null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), true, null)] - public virtual void Save_optional_many_to_one_dependents( + public virtual Task Save_optional_many_to_one_dependents( ChangeMechanism changeMechanism, bool useExistingEntities, CascadeTiming? deleteOrphansTiming) @@ -86,31 +86,30 @@ public virtual void Save_optional_many_to_one_dependents( Root root = null; IReadOnlyList entries = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { if (useExistingEntities) { context.AddRange(new1, new1d, new1dd, new2a, new2d, new2dd, new2b); - context.SaveChanges(); + await context.SaveChangesAsync(); } - }, - context => + }, async context => { context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - root = LoadOptionalGraph(context); + root = await LoadOptionalGraphAsync(context); var existing = root.OptionalChildren.OrderBy(e => e.Id).First(); if (useExistingEntities) { - new1 = context.Set().Single(e => e.Id == new1.Id); - new1d = (Optional1Derived)context.Set().Single(e => e.Id == new1d.Id); - new1dd = (Optional1MoreDerived)context.Set().Single(e => e.Id == new1dd.Id); - new2a = context.Set().Single(e => e.Id == new2a.Id); - new2b = context.Set().Single(e => e.Id == new2b.Id); - new2d = (Optional2Derived)context.Set().Single(e => e.Id == new2d.Id); - new2dd = (Optional2MoreDerived)context.Set().Single(e => e.Id == new2dd.Id); + new1 = await context.Set().SingleAsync(e => e.Id == new1.Id); + new1d = (Optional1Derived)await context.Set().SingleAsync(e => e.Id == new1d.Id); + new1dd = (Optional1MoreDerived)await context.Set().SingleAsync(e => e.Id == new1dd.Id); + new2a = await context.Set().SingleAsync(e => e.Id == new2a.Id); + new2b = await context.Set().SingleAsync(e => e.Id == new2b.Id); + new2d = (Optional2Derived)await context.Set().SingleAsync(e => e.Id == new2d.Id); + new2dd = (Optional2MoreDerived)await context.Set().SingleAsync(e => e.Id == new2dd.Id); } else { @@ -152,7 +151,7 @@ public virtual void Save_optional_many_to_one_dependents( Assert.True(context.ChangeTracker.HasChanges()); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -181,10 +180,9 @@ public virtual void Save_optional_many_to_one_dependents( Assert.Equal(root.Id, new1dd.ParentId); entries = context.ChangeTracker.Entries().ToList(); - }, - context => + }, async context => { - var loadedRoot = LoadOptionalGraph(context); + var loadedRoot = await LoadOptionalGraphAsync(context); AssertEntries(entries, context.ChangeTracker.Entries().ToList()); AssertKeys(root, loadedRoot); @@ -251,7 +249,7 @@ public virtual void Save_optional_many_to_one_dependents( [InlineData((int)(ChangeMechanism.Fk | ChangeMechanism.Dependent), true, null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), false, null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), true, null)] - public virtual void Save_required_many_to_one_dependents( + public virtual Task Save_required_many_to_one_dependents( ChangeMechanism changeMechanism, bool useExistingEntities, CascadeTiming? deleteOrphansTiming) @@ -267,31 +265,30 @@ public virtual void Save_required_many_to_one_dependents( Root root = null; IReadOnlyList entries = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { if (useExistingEntities) { context.AddRange(newRoot, new1, new1d, new1dd, new2a, new2d, new2dd, new2b); - context.SaveChanges(); + await context.SaveChangesAsync(); } - }, - context => + }, async context => { context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - root = LoadRequiredGraph(context); + root = await LoadRequiredGraphAsync(context); var existing = root.RequiredChildren.OrderBy(e => e.Id).First(); if (useExistingEntities) { - new1 = context.Set().Single(e => e.Id == new1.Id); - new1d = (Required1Derived)context.Set().Single(e => e.Id == new1d.Id); - new1dd = (Required1MoreDerived)context.Set().Single(e => e.Id == new1dd.Id); - new2a = context.Set().Single(e => e.Id == new2a.Id); - new2b = context.Set().Single(e => e.Id == new2b.Id); - new2d = (Required2Derived)context.Set().Single(e => e.Id == new2d.Id); - new2dd = (Required2MoreDerived)context.Set().Single(e => e.Id == new2dd.Id); + new1 = await context.Set().SingleAsync(e => e.Id == new1.Id); + new1d = (Required1Derived)await context.Set().SingleAsync(e => e.Id == new1d.Id); + new1dd = (Required1MoreDerived)await context.Set().SingleAsync(e => e.Id == new1dd.Id); + new2a = await context.Set().SingleAsync(e => e.Id == new2a.Id); + new2b = await context.Set().SingleAsync(e => e.Id == new2b.Id); + new2d = (Required2Derived)await context.Set().SingleAsync(e => e.Id == new2d.Id); + new2dd = (Required2MoreDerived)await context.Set().SingleAsync(e => e.Id == new2dd.Id); } else { @@ -337,7 +334,7 @@ public virtual void Save_required_many_to_one_dependents( Assert.True(context.ChangeTracker.HasChanges()); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -366,10 +363,9 @@ public virtual void Save_required_many_to_one_dependents( Assert.Equal(root.Id, new1dd.ParentId); entries = context.ChangeTracker.Entries().ToList(); - }, - context => + }, async context => { - var loadedRoot = LoadRequiredGraph(context); + var loadedRoot = await LoadRequiredGraphAsync(context); AssertEntries(entries, context.ChangeTracker.Entries().ToList()); AssertKeys(root, loadedRoot); @@ -406,17 +402,17 @@ public virtual void Save_required_many_to_one_dependents( [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Fk), null)] [InlineData((int)(ChangeMechanism.Fk | ChangeMechanism.Dependent), null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), null)] - public virtual void Save_removed_optional_many_to_one_dependents( + public virtual Task Save_removed_optional_many_to_one_dependents( ChangeMechanism changeMechanism, CascadeTiming? deleteOrphansTiming) { Root root = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - root = LoadOptionalGraph(context); + root = await LoadOptionalGraphAsync(context); var childCollection = root.OptionalChildren.First().Children; var removed2 = childCollection.First(); @@ -442,7 +438,7 @@ public virtual void Save_removed_optional_many_to_one_dependents( Assert.True(context.ChangeTracker.HasChanges()); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -453,12 +449,11 @@ public virtual void Save_removed_optional_many_to_one_dependents( Assert.Null(removed2.Parent); Assert.Null(removed1.ParentId); Assert.Null(removed2.ParentId); - }, - context => + }, async context => { if ((changeMechanism & ChangeMechanism.Fk) == 0) { - var loadedRoot = LoadOptionalGraph(context); + var loadedRoot = await LoadOptionalGraphAsync(context); AssertKeys(root, loadedRoot); AssertNavigations(loadedRoot); @@ -498,7 +493,7 @@ public virtual void Save_removed_optional_many_to_one_dependents( [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Fk), null)] [InlineData((int)(ChangeMechanism.Fk | ChangeMechanism.Dependent), null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), null)] - public virtual void Save_removed_required_many_to_one_dependents( + public virtual Task Save_removed_required_many_to_one_dependents( ChangeMechanism changeMechanism, CascadeTiming? deleteOrphansTiming) { @@ -506,12 +501,12 @@ public virtual void Save_removed_required_many_to_one_dependents( var removed2Id = 0; List removed1ChildrenIds = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - var root = LoadRequiredGraph(context); + var root = await LoadRequiredGraphAsync(context); var childCollection = root.RequiredChildren.First().Children; var removed2 = childCollection.First(); @@ -536,36 +531,44 @@ public virtual void Save_removed_required_many_to_one_dependents( if (Fixture.ForceClientNoAction || deleteOrphansTiming == CascadeTiming.Never) { - Action testCode; + Func testCode; if ((changeMechanism & ChangeMechanism.Fk) != 0 && deleteOrphansTiming == CascadeTiming.Immediate) { testCode = () => - context.Entry(removed2).GetInfrastructure()[context.Entry(removed2).Property(e => e.ParentId).Metadata] - = - null; + { + context.Entry(removed2).GetInfrastructure() + [context.Entry(removed2).Property(e => e.ParentId).Metadata] = null; + return Task.CompletedTask; + }; } else { if ((changeMechanism & ChangeMechanism.Fk) != 0) { - context.Entry(removed2).GetInfrastructure()[context.Entry(removed2).Property(e => e.ParentId).Metadata] - = - null; - context.Entry(removed1).GetInfrastructure()[context.Entry(removed1).Property(e => e.ParentId).Metadata] - = - null; + context.Entry(removed2).GetInfrastructure() + [context.Entry(removed2).Property(e => e.ParentId).Metadata] = null; + context.Entry(removed1).GetInfrastructure() + [context.Entry(removed1).Property(e => e.ParentId).Metadata] = null; } testCode = deleteOrphansTiming == CascadeTiming.Immediate - ? () => context.ChangeTracker.DetectChanges() + ? () => + { + context.ChangeTracker.DetectChanges(); + return Task.CompletedTask; + } : deleteOrphansTiming == null - ? () => context.ChangeTracker.CascadeChanges() - : () => context.SaveChanges(); + ? () => + { + context.ChangeTracker.CascadeChanges(); + return Task.CompletedTask; + } + : () => context.SaveChangesAsync(); } - var message = Assert.Throws(testCode).Message; + var message = (await Assert.ThrowsAsync(testCode)).Message; Assert.True( message @@ -592,18 +595,17 @@ public virtual void Save_removed_required_many_to_one_dependents( context.ChangeTracker.CascadeChanges(); } - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction && !Fixture.NoStoreCascades && deleteOrphansTiming != CascadeTiming.Never) { - var root = LoadRequiredGraph(context); + var root = await LoadRequiredGraphAsync(context); AssertNavigations(root); @@ -676,7 +678,7 @@ public virtual void Save_removed_required_many_to_one_dependents( [InlineData((int)(ChangeMechanism.Fk | ChangeMechanism.Dependent), true, null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), false, null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), true, null)] - public virtual void Reparent_to_different_one_to_many( + public virtual Task Reparent_to_different_one_to_many( ChangeMechanism changeMechanism, bool useExistingParent, CascadeTiming? deleteOrphansTiming) @@ -689,8 +691,8 @@ public virtual void Reparent_to_different_one_to_many( OptionalComposite2 oldComposite2 = null; Optional1 newParent = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { if (!useExistingParent) { @@ -700,14 +702,13 @@ public virtual void Reparent_to_different_one_to_many( }; context.Set().Add(newParent); - context.SaveChanges(); + await context.SaveChangesAsync(); } - }, - context => + }, async context => { context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - root = LoadOptionalOneToManyGraph(context); + root = await LoadOptionalOneToManyGraphAsync(context); compositeCount = context.Set().Count(); @@ -722,7 +723,7 @@ public virtual void Reparent_to_different_one_to_many( } else { - newParent = context.Set().Single(e => e.Id == newParent.Id); + newParent = await context.Set().SingleAsync(e => e.Id == newParent.Id); newParent.Parent = root; } @@ -746,7 +747,7 @@ public virtual void Reparent_to_different_one_to_many( Assert.True(context.ChangeTracker.HasChanges()); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -765,20 +766,19 @@ public virtual void Reparent_to_different_one_to_many( entries = context.ChangeTracker.Entries().ToList(); Assert.Equal(compositeCount, context.Set().Count()); - }, - context => + }, async context => { if ((changeMechanism & ChangeMechanism.Fk) == 0) { - var loadedRoot = LoadOptionalOneToManyGraph(context); + var loadedRoot = await LoadOptionalOneToManyGraphAsync(context); Assert.False(context.ChangeTracker.HasChanges()); AssertKeys(root, loadedRoot); AssertNavigations(loadedRoot); - oldParent = context.Set().Single(e => e.Id == oldParent.Id); - newParent = context.Set().Single(e => e.Id == newParent.Id); + oldParent = await context.Set().SingleAsync(e => e.Id == oldParent.Id); + newParent = await context.Set().SingleAsync(e => e.Id == newParent.Id); oldComposite1 = context.Set().Single(e => e.Id == oldComposite1.Id); oldComposite2 = context.Set().Single(e => e.Id == oldComposite2.Id); @@ -831,7 +831,7 @@ public virtual void Reparent_to_different_one_to_many( [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Fk), null)] [InlineData((int)(ChangeMechanism.Fk | ChangeMechanism.Dependent), null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), null)] - public virtual void Reparent_dependent_one_to_many( + public virtual Task Reparent_dependent_one_to_many( ChangeMechanism changeMechanism, CascadeTiming? deleteOrphansTiming) { @@ -839,12 +839,12 @@ public virtual void Reparent_dependent_one_to_many( Required1 newParent = null; Required2 child = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - var root = LoadRequiredGraph(context); + var root = await LoadRequiredGraphAsync(context); oldParent = root.RequiredChildren.OrderBy(e => e.Id).First(); newParent = root.RequiredChildren.OrderBy(e => e.Id).Last(); @@ -880,7 +880,7 @@ public virtual void Reparent_dependent_one_to_many( Assert.Equal(EntityState.Unchanged, context.Entry(oldParent).State); Assert.Equal(EntityState.Unchanged, context.Entry(newParent).State); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -895,15 +895,14 @@ public virtual void Reparent_dependent_one_to_many( { Assert.Throws(() => context.ChangeTracker.DetectChanges()); } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction || deleteOrphansTiming != CascadeTiming.Immediate || (changeMechanism & ChangeMechanism.Fk) != 0 || changeMechanism == ChangeMechanism.Dependent) { - var root = LoadRequiredGraph(context); + var root = await LoadRequiredGraphAsync(context); Assert.False(context.ChangeTracker.HasChanges()); @@ -950,7 +949,7 @@ public virtual void Reparent_dependent_one_to_many( [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Fk), null)] [InlineData((int)(ChangeMechanism.Fk | ChangeMechanism.Dependent), null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), null)] - public virtual void Reparent_dependent_one_to_many_ak( + public virtual Task Reparent_dependent_one_to_many_ak( ChangeMechanism changeMechanism, CascadeTiming? deleteOrphansTiming) { @@ -958,12 +957,12 @@ public virtual void Reparent_dependent_one_to_many_ak( RequiredAk1 newParent = null; RequiredAk2 child = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - var root = LoadRequiredAkGraph(context); + var root = await LoadRequiredAkGraphAsync(context); oldParent = root.RequiredChildrenAk.OrderBy(e => e.Id).First(); newParent = root.RequiredChildrenAk.OrderBy(e => e.Id).Last(); @@ -999,7 +998,7 @@ public virtual void Reparent_dependent_one_to_many_ak( Assert.Equal(EntityState.Unchanged, context.Entry(oldParent).State); Assert.Equal(EntityState.Unchanged, context.Entry(newParent).State); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -1014,15 +1013,14 @@ public virtual void Reparent_dependent_one_to_many_ak( { Assert.Throws(() => context.ChangeTracker.DetectChanges()); } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction || deleteOrphansTiming != CascadeTiming.Immediate || (changeMechanism & ChangeMechanism.Fk) != 0 || changeMechanism == ChangeMechanism.Dependent) { - var root = LoadRequiredAkGraph(context); + var root = await LoadRequiredAkGraphAsync(context); Assert.False(context.ChangeTracker.HasChanges()); @@ -1099,7 +1097,7 @@ public virtual void Reparent_dependent_one_to_many_ak( [InlineData((int)(ChangeMechanism.Fk | ChangeMechanism.Dependent), true, null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), false, null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), true, null)] - public virtual void Reparent_one_to_many_overlapping( + public virtual Task Reparent_one_to_many_overlapping( ChangeMechanism changeMechanism, bool useExistingParent, CascadeTiming? deleteOrphansTiming) @@ -1112,15 +1110,15 @@ public virtual void Reparent_one_to_many_overlapping( OptionalOverlapping2 oldChild2 = null; RequiredComposite1 newParent = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { if (!useExistingParent) { newParent = new RequiredComposite1 { Id = 3, - Parent = context.Set().Single(IsTheRoot), + Parent = await context.Set().SingleAsync(IsTheRoot), CompositeChildren = new ObservableHashSet(ReferenceEqualityComparer.Instance) { new() { Id = 5 }, new() { Id = 6 } @@ -1128,14 +1126,13 @@ public virtual void Reparent_one_to_many_overlapping( }; context.Set().Add(newParent); - context.SaveChanges(); + await context.SaveChangesAsync(); } - }, - context => + }, async context => { context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - root = LoadRequiredCompositeGraph(context); + root = await LoadRequiredCompositeGraphAsync(context); childCount = context.Set().Count(); @@ -1152,7 +1149,7 @@ public virtual void Reparent_one_to_many_overlapping( } else { - newParent = context.Set().Single(e => e.Id == newParent.Id); + newParent = await context.Set().SingleAsync(e => e.Id == newParent.Id); newParent.Parent = root; } @@ -1174,7 +1171,7 @@ public virtual void Reparent_one_to_many_overlapping( Assert.True(context.ChangeTracker.HasChanges()); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -1196,19 +1193,18 @@ public virtual void Reparent_one_to_many_overlapping( entries = context.ChangeTracker.Entries().ToList(); Assert.Equal(childCount, context.Set().Count()); - }, - context => + }, async context => { - var loadedRoot = LoadRequiredCompositeGraph(context); + var loadedRoot = await LoadRequiredCompositeGraphAsync(context); AssertKeys(root, loadedRoot); AssertNavigations(loadedRoot); - oldParent = context.Set().Single(e => e.Id == oldParent.Id); - newParent = context.Set().Single(e => e.Id == newParent.Id); + oldParent = await context.Set().SingleAsync(e => e.Id == oldParent.Id); + newParent = await context.Set().SingleAsync(e => e.Id == newParent.Id); - oldChild1 = context.Set().Single(e => e.Id == oldChild1.Id); - oldChild2 = context.Set().Single(e => e.Id == oldChild2.Id); + oldChild1 = await context.Set().SingleAsync(e => e.Id == oldChild1.Id); + oldChild2 = await context.Set().SingleAsync(e => e.Id == oldChild2.Id); Assert.Same(oldChild2, oldParent.CompositeChildren.Single()); Assert.Same(oldParent, oldChild2.Parent); @@ -1241,15 +1237,15 @@ public virtual void Reparent_one_to_many_overlapping( [InlineData((int)ChangeMechanism.Principal, null)] [InlineData((int)ChangeMechanism.Dependent, null)] [InlineData((int)ChangeMechanism.Fk, null)] - public virtual void Mark_modified_one_to_many_overlapping( + public virtual Task Mark_modified_one_to_many_overlapping( ChangeMechanism changeMechanism, CascadeTiming? deleteOrphansTiming) - => ExecuteWithStrategyInTransaction( - context => + => ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - var root = LoadRequiredCompositeGraph(context); + var root = await LoadRequiredCompositeGraphAsync(context); var parent = root.RequiredCompositeChildren.OrderBy(e => e.Id).First(); var child = parent.CompositeChildren.OrderBy(e => e.Id).First(); @@ -1272,7 +1268,7 @@ public virtual void Mark_modified_one_to_many_overlapping( Assert.True(context.ChangeTracker.HasChanges()); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -1297,20 +1293,20 @@ public virtual void Mark_modified_one_to_many_overlapping( [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] [InlineData(null, null)] - public virtual void Required_many_to_one_dependents_are_cascade_deleted( + public virtual Task Required_many_to_one_dependents_are_cascade_deleted( CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) { var removedId = 0; List orphanedIds = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming ?? CascadeTiming.Never; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - var root = LoadRequiredGraph(context); + var root = await LoadRequiredGraphAsync(context); Assert.Equal(2, root.RequiredChildren.Count()); @@ -1340,15 +1336,15 @@ public virtual void Required_many_to_one_dependents_are_cascade_deleted( if (Fixture.ForceClientNoAction) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else if (cascadeDeleteTiming == CascadeTiming.Never) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -1364,13 +1360,12 @@ public virtual void Required_many_to_one_dependents_are_cascade_deleted( Assert.Same(root, removed.Parent); Assert.Equal(2, removed.Children.Count()); } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction && cascadeDeleteTiming != CascadeTiming.Never) { - var root = LoadRequiredGraph(context); + var root = await LoadRequiredGraphAsync(context); Assert.Single(root.RequiredChildren); Assert.DoesNotContain(removedId, root.RequiredChildren.Select(e => e.Id)); @@ -1392,19 +1387,19 @@ public virtual void Required_many_to_one_dependents_are_cascade_deleted( [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] [InlineData(null, null)] - public virtual void Required_many_to_one_dependent_leaves_can_be_deleted( + public virtual Task Required_many_to_one_dependent_leaves_can_be_deleted( CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) { var removedId = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming ?? CascadeTiming.Never; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - var root = LoadRequiredGraph(context); + var root = await LoadRequiredGraphAsync(context); var parent = root.RequiredChildren.First(); Assert.Equal(2, parent.Children.Count()); @@ -1421,7 +1416,7 @@ public virtual void Required_many_to_one_dependent_leaves_can_be_deleted( context.ChangeTracker.CascadeChanges(); } - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); Assert.Equal(EntityState.Detached, context.Entry(removed).State); @@ -1432,10 +1427,9 @@ public virtual void Required_many_to_one_dependent_leaves_can_be_deleted( Assert.Empty(context.Set().Where(e => e.Id == removedId)); Assert.Same(parent, removed.Parent); - }, - context => + }, async context => { - var root = LoadRequiredGraph(context); + var root = await LoadRequiredGraphAsync(context); var parent = root.RequiredChildren.First(); Assert.Single(parent.Children); @@ -1456,20 +1450,20 @@ public virtual void Required_many_to_one_dependent_leaves_can_be_deleted( [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] [InlineData(null, null)] - public virtual void Optional_many_to_one_dependents_are_orphaned( + public virtual Task Optional_many_to_one_dependents_are_orphaned( CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) { var removedId = 0; List orphanedIds = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming ?? CascadeTiming.Never; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - var root = LoadOptionalGraph(context); + var root = await LoadOptionalGraphAsync(context); Assert.Equal(2, root.OptionalChildren.Count()); @@ -1516,11 +1510,11 @@ public virtual void Optional_many_to_one_dependents_are_orphaned( if (Fixture.ForceClientNoAction) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -1536,12 +1530,11 @@ public virtual void Optional_many_to_one_dependents_are_orphaned( Assert.Same(root, removed.Parent); Assert.Equal(2, removed.Children.Count()); } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction) { - var root = LoadOptionalGraph(context); + var root = await LoadOptionalGraphAsync(context); Assert.Single(root.OptionalChildren); Assert.DoesNotContain(removedId, root.OptionalChildren.Select(e => e.Id)); @@ -1563,11 +1556,11 @@ public virtual void Optional_many_to_one_dependents_are_orphaned( [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] [InlineData(null, null)] - public virtual void Optional_many_to_one_dependents_are_orphaned_with_Added_graph( + public virtual Task Optional_many_to_one_dependents_are_orphaned_with_Added_graph( CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) // Issue #29318 - => ExecuteWithStrategyInTransaction( - context => + => ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming ?? CascadeTiming.Never; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; @@ -1591,7 +1584,7 @@ public virtual void Optional_many_to_one_dependents_are_orphaned_with_Added_grap if (Fixture.ForceClientNoAction) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { @@ -1602,7 +1595,7 @@ public virtual void Optional_many_to_one_dependents_are_orphaned_with_Added_grap Assert.Null(orphanEntry.Property(e => e.ParentId).CurrentValue); } - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -1626,18 +1619,18 @@ public virtual void Optional_many_to_one_dependents_are_orphaned_with_Added_grap [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] [InlineData(null, null)] - public virtual void Optional_many_to_one_dependent_leaves_can_be_deleted( + public virtual Task Optional_many_to_one_dependent_leaves_can_be_deleted( CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) { var removedId = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming ?? CascadeTiming.Never; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - var root = LoadOptionalGraph(context); + var root = await LoadOptionalGraphAsync(context); var parent = root.OptionalChildren.First(); Assert.Equal(2, parent.Children.Count()); @@ -1654,7 +1647,7 @@ public virtual void Optional_many_to_one_dependent_leaves_can_be_deleted( context.ChangeTracker.CascadeChanges(); } - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -1666,10 +1659,9 @@ public virtual void Optional_many_to_one_dependent_leaves_can_be_deleted( Assert.Empty(context.Set().Where(e => e.Id == removedId)); Assert.Same(parent, removed.Parent); - }, - context => + }, async context => { - var root = LoadOptionalGraph(context); + var root = await LoadOptionalGraphAsync(context); var parent = root.OptionalChildren.First(); Assert.Single(parent.Children); @@ -1690,29 +1682,28 @@ public virtual void Optional_many_to_one_dependent_leaves_can_be_deleted( [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] [InlineData(null, null)] - public virtual void Required_many_to_one_dependents_are_cascade_deleted_in_store( + public virtual Task Required_many_to_one_dependents_are_cascade_deleted_in_store( CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) { var removedId = 0; List orphanedIds = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var removed = LoadRequiredGraph(context).RequiredChildren.First(); + var removed = (await LoadRequiredGraphAsync(context)).RequiredChildren.First(); removedId = removed.Id; orphanedIds = removed.Children.Select(e => e.Id).ToList(); Assert.Equal(2, orphanedIds.Count); - }, - context => + }, async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming ?? CascadeTiming.Never; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - var root = context.Set().Include(e => e.RequiredChildren).Single(IsTheRoot); + var root = await context.Set().Include(e => e.RequiredChildren).SingleAsync(IsTheRoot); context.Set().Load(); var removed = root.RequiredChildren.Single(e => e.Id == removedId); @@ -1731,11 +1722,11 @@ public virtual void Required_many_to_one_dependents_are_cascade_deleted_in_store if (Fixture.ForceClientNoAction || Fixture.NoStoreCascades) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -1750,13 +1741,12 @@ public virtual void Required_many_to_one_dependents_are_cascade_deleted_in_store Assert.Same(root, removed.Parent); Assert.Empty(removed.Children); } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction && !Fixture.NoStoreCascades) { - var root = LoadRequiredGraph(context); + var root = await LoadRequiredGraphAsync(context); Assert.Single(root.RequiredChildren); Assert.DoesNotContain(removedId, root.RequiredChildren.Select(e => e.Id)); @@ -1778,29 +1768,28 @@ public virtual void Required_many_to_one_dependents_are_cascade_deleted_in_store [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] [InlineData(null, null)] - public virtual void Optional_many_to_one_dependents_are_orphaned_in_store( + public virtual Task Optional_many_to_one_dependents_are_orphaned_in_store( CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) { var removedId = 0; List orphanedIds = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var removed = LoadOptionalGraph(context).OptionalChildren.First(); + var removed = (await LoadOptionalGraphAsync(context)).OptionalChildren.First(); removedId = removed.Id; orphanedIds = removed.Children.Select(e => e.Id).ToList(); Assert.Equal(2, orphanedIds.Count); - }, - context => + }, async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming ?? CascadeTiming.Never; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - var root = context.Set().Include(e => e.OptionalChildren).Single(IsTheRoot); + var root = await context.Set().Include(e => e.OptionalChildren).SingleAsync(IsTheRoot); context.Entry(root).Collection(e => e.OptionalChildren).Load(); var removed = root.OptionalChildren.First(e => e.Id == removedId); @@ -1818,11 +1807,11 @@ public virtual void Optional_many_to_one_dependents_are_orphaned_in_store( if (Fixture.ForceClientNoAction) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -1840,12 +1829,11 @@ public virtual void Optional_many_to_one_dependents_are_orphaned_in_store( Assert.Same(root, removed.Parent); Assert.Empty(removed.Children); // Never loaded } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction) { - var root = LoadOptionalGraph(context); + var root = await LoadOptionalGraphAsync(context); Assert.Single(root.OptionalChildren); Assert.DoesNotContain(removedId, root.OptionalChildren.Select(e => e.Id)); @@ -1870,7 +1858,7 @@ public virtual void Optional_many_to_one_dependents_are_orphaned_in_store( [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] [InlineData(null, null)] - public virtual void Required_many_to_one_dependents_are_cascade_deleted_starting_detached( + public virtual Task Required_many_to_one_dependents_are_cascade_deleted_starting_detached( CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) { @@ -1878,14 +1866,13 @@ public virtual void Required_many_to_one_dependents_are_cascade_deleted_starting List orphanedIds = null; Root root = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - root = LoadRequiredGraph(context); + root = await LoadRequiredGraphAsync(context); Assert.Equal(2, root.RequiredChildren.Count()); - }, - context => + }, async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming ?? CascadeTiming.Never; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; @@ -1920,15 +1907,15 @@ public virtual void Required_many_to_one_dependents_are_cascade_deleted_starting if (Fixture.ForceClientNoAction) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else if (cascadeDeleteTiming == CascadeTiming.Never) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -1938,13 +1925,12 @@ public virtual void Required_many_to_one_dependents_are_cascade_deleted_starting Assert.Same(root, removed.Parent); Assert.Equal(2, removed.Children.Count()); } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction && cascadeDeleteTiming != CascadeTiming.Never) { - root = LoadRequiredGraph(context); + root = await LoadRequiredGraphAsync(context); Assert.Single(root.RequiredChildren); Assert.DoesNotContain(removedId, root.RequiredChildren.Select(e => e.Id)); @@ -1966,7 +1952,7 @@ public virtual void Required_many_to_one_dependents_are_cascade_deleted_starting [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] [InlineData(null, null)] - public virtual void Optional_many_to_one_dependents_are_orphaned_starting_detached( + public virtual Task Optional_many_to_one_dependents_are_orphaned_starting_detached( CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) { @@ -1974,14 +1960,13 @@ public virtual void Optional_many_to_one_dependents_are_orphaned_starting_detach List orphanedIds = null; Root root = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - root = LoadOptionalGraph(context); + root = await LoadOptionalGraphAsync(context); Assert.Equal(2, root.OptionalChildren.Count()); - }, - context => + }, async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming ?? CascadeTiming.Never; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; @@ -2031,11 +2016,11 @@ public virtual void Optional_many_to_one_dependents_are_orphaned_starting_detach if (Fixture.ForceClientNoAction) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -2045,12 +2030,11 @@ public virtual void Optional_many_to_one_dependents_are_orphaned_starting_detach Assert.Same(root, removed.Parent); Assert.Equal(2, removed.Children.Count()); } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction) { - root = LoadOptionalGraph(context); + root = await LoadOptionalGraphAsync(context); Assert.Single(root.OptionalChildren); Assert.DoesNotContain(removedId, root.OptionalChildren.Select(e => e.Id)); @@ -2072,20 +2056,20 @@ public virtual void Optional_many_to_one_dependents_are_orphaned_starting_detach [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] [InlineData(null, null)] - public virtual void Required_many_to_one_dependents_are_cascade_detached_when_Added( + public virtual Task Required_many_to_one_dependents_are_cascade_detached_when_Added( CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) { var removedId = 0; List orphanedIds = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming ?? CascadeTiming.Never; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - var root = LoadRequiredGraph(context); + var root = await LoadRequiredGraphAsync(context); Assert.Equal(2, root.RequiredChildren.Count()); @@ -2137,15 +2121,15 @@ public virtual void Required_many_to_one_dependents_are_cascade_detached_when_Ad if (Fixture.ForceClientNoAction) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else if (cascadeDeleteTiming == CascadeTiming.Never) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -2156,13 +2140,12 @@ public virtual void Required_many_to_one_dependents_are_cascade_detached_when_Ad Assert.Same(root, removed.Parent); Assert.Equal(3, removed.Children.Count()); } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction && cascadeDeleteTiming != CascadeTiming.Never) { - var root = LoadRequiredGraph(context); + var root = await LoadRequiredGraphAsync(context); Assert.Single(root.RequiredChildren); Assert.DoesNotContain(removedId, root.RequiredChildren.Select(e => e.Id)); diff --git a/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBaseOneToManyAk.cs b/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBaseOneToManyAk.cs index fa86e3bf380..60584ae36ec 100644 --- a/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBaseOneToManyAk.cs +++ b/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBaseOneToManyAk.cs @@ -71,7 +71,7 @@ public abstract partial class GraphUpdatesTestBase [InlineData((int)(ChangeMechanism.Fk | ChangeMechanism.Dependent), true, null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), false, null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), true, null)] - public virtual void Save_optional_many_to_one_dependents_with_alternate_key( + public virtual Task Save_optional_many_to_one_dependents_with_alternate_key( ChangeMechanism changeMechanism, bool useExistingEntities, CascadeTiming? deleteOrphansTiming) @@ -88,33 +88,32 @@ public virtual void Save_optional_many_to_one_dependents_with_alternate_key( Root root = null; IReadOnlyList entries = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { if (useExistingEntities) { context.AddRange(new1, new1d, new1dd, new2a, new2d, new2dd, new2b, new2ca, new2cb); - context.SaveChanges(); + await context.SaveChangesAsync(); } - }, - context => + }, async context => { context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - root = LoadOptionalAkGraph(context); + root = await LoadOptionalAkGraphAsync(context); var existing = root.OptionalChildrenAk.OrderBy(e => e.Id).First(); if (useExistingEntities) { - new1 = context.Set().Single(e => e.Id == new1.Id); - new1d = (OptionalAk1Derived)context.Set().Single(e => e.Id == new1d.Id); - new1dd = (OptionalAk1MoreDerived)context.Set().Single(e => e.Id == new1dd.Id); - new2a = context.Set().Single(e => e.Id == new2a.Id); - new2b = context.Set().Single(e => e.Id == new2b.Id); - new2ca = context.Set().Single(e => e.Id == new2ca.Id); - new2cb = context.Set().Single(e => e.Id == new2cb.Id); - new2d = (OptionalAk2Derived)context.Set().Single(e => e.Id == new2d.Id); - new2dd = (OptionalAk2MoreDerived)context.Set().Single(e => e.Id == new2dd.Id); + new1 = await context.Set().SingleAsync(e => e.Id == new1.Id); + new1d = (OptionalAk1Derived)await context.Set().SingleAsync(e => e.Id == new1d.Id); + new1dd = (OptionalAk1MoreDerived)await context.Set().SingleAsync(e => e.Id == new1dd.Id); + new2a = await context.Set().SingleAsync(e => e.Id == new2a.Id); + new2b = await context.Set().SingleAsync(e => e.Id == new2b.Id); + new2ca = await context.Set().SingleAsync(e => e.Id == new2ca.Id); + new2cb = await context.Set().SingleAsync(e => e.Id == new2cb.Id); + new2d = (OptionalAk2Derived)await context.Set().SingleAsync(e => e.Id == new2d.Id); + new2dd = (OptionalAk2MoreDerived)await context.Set().SingleAsync(e => e.Id == new2dd.Id); } else { @@ -164,7 +163,7 @@ public virtual void Save_optional_many_to_one_dependents_with_alternate_key( Assert.True(context.ChangeTracker.HasChanges()); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -201,10 +200,9 @@ public virtual void Save_optional_many_to_one_dependents_with_alternate_key( Assert.Equal(root.AlternateId, new1dd.ParentId); entries = context.ChangeTracker.Entries().ToList(); - }, - context => + }, async context => { - var loadedRoot = LoadOptionalAkGraph(context); + var loadedRoot = await LoadOptionalAkGraphAsync(context); AssertEntries(entries, context.ChangeTracker.Entries().ToList()); AssertKeys(root, loadedRoot); @@ -271,7 +269,7 @@ public virtual void Save_optional_many_to_one_dependents_with_alternate_key( [InlineData((int)(ChangeMechanism.Fk | ChangeMechanism.Dependent), true, null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), false, null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), true, null)] - public virtual void Save_required_many_to_one_dependents_with_alternate_key( + public virtual Task Save_required_many_to_one_dependents_with_alternate_key( ChangeMechanism changeMechanism, bool useExistingEntities, CascadeTiming? deleteOrphansTiming) @@ -289,33 +287,32 @@ public virtual void Save_required_many_to_one_dependents_with_alternate_key( Root root = null; IReadOnlyList entries = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { if (useExistingEntities) { context.AddRange(newRoot, new1, new1d, new1dd, new2a, new2d, new2dd, new2b, new2ca, new2cb); - context.SaveChanges(); + await context.SaveChangesAsync(); } - }, - context => + }, async context => { context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - root = LoadRequiredAkGraph(context); + root = await LoadRequiredAkGraphAsync(context); var existing = root.RequiredChildrenAk.OrderBy(e => e.Id).First(); if (useExistingEntities) { - new1 = context.Set().Single(e => e.Id == new1.Id); - new1d = (RequiredAk1Derived)context.Set().Single(e => e.Id == new1d.Id); - new1dd = (RequiredAk1MoreDerived)context.Set().Single(e => e.Id == new1dd.Id); - new2a = context.Set().Single(e => e.Id == new2a.Id); - new2b = context.Set().Single(e => e.Id == new2b.Id); - new2ca = context.Set().Single(e => e.Id == new2ca.Id); - new2cb = context.Set().Single(e => e.Id == new2cb.Id); - new2d = (RequiredAk2Derived)context.Set().Single(e => e.Id == new2d.Id); - new2dd = (RequiredAk2MoreDerived)context.Set().Single(e => e.Id == new2dd.Id); + new1 = await context.Set().SingleAsync(e => e.Id == new1.Id); + new1d = (RequiredAk1Derived)await context.Set().SingleAsync(e => e.Id == new1d.Id); + new1dd = (RequiredAk1MoreDerived)await context.Set().SingleAsync(e => e.Id == new1dd.Id); + new2a = await context.Set().SingleAsync(e => e.Id == new2a.Id); + new2b = await context.Set().SingleAsync(e => e.Id == new2b.Id); + new2ca = await context.Set().SingleAsync(e => e.Id == new2ca.Id); + new2cb = await context.Set().SingleAsync(e => e.Id == new2cb.Id); + new2d = (RequiredAk2Derived)await context.Set().SingleAsync(e => e.Id == new2d.Id); + new2dd = (RequiredAk2MoreDerived)await context.Set().SingleAsync(e => e.Id == new2dd.Id); } else { @@ -376,7 +373,7 @@ public virtual void Save_required_many_to_one_dependents_with_alternate_key( Assert.True(context.ChangeTracker.HasChanges()); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -413,10 +410,9 @@ public virtual void Save_required_many_to_one_dependents_with_alternate_key( Assert.Equal(root.AlternateId, new1dd.ParentId); entries = context.ChangeTracker.Entries().ToList(); - }, - context => + }, async context => { - var loadedRoot = LoadRequiredAkGraph(context); + var loadedRoot = await LoadRequiredAkGraphAsync(context); AssertEntries(entries, context.ChangeTracker.Entries().ToList()); AssertKeys(root, loadedRoot); @@ -453,17 +449,17 @@ public virtual void Save_required_many_to_one_dependents_with_alternate_key( [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Fk), null)] [InlineData((int)(ChangeMechanism.Fk | ChangeMechanism.Dependent), null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), null)] - public virtual void Save_removed_optional_many_to_one_dependents_with_alternate_key( + public virtual Task Save_removed_optional_many_to_one_dependents_with_alternate_key( ChangeMechanism changeMechanism, CascadeTiming? deleteOrphansTiming) { Root root = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - root = LoadOptionalAkGraph(context); + root = await LoadOptionalAkGraphAsync(context); var firstChild = root.OptionalChildrenAk.OrderByDescending(c => c.Id).First(); var childCollection = firstChild.Children; @@ -495,7 +491,7 @@ public virtual void Save_removed_optional_many_to_one_dependents_with_alternate_ Assert.True(context.ChangeTracker.HasChanges()); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -510,12 +506,11 @@ public virtual void Save_removed_optional_many_to_one_dependents_with_alternate_ Assert.Null(removed1.ParentId); Assert.Null(removed2.ParentId); Assert.Null(removed2c.ParentId); - }, - context => + }, async context => { if ((changeMechanism & ChangeMechanism.Fk) == 0) { - var loadedRoot = LoadOptionalAkGraph(context); + var loadedRoot = await LoadOptionalAkGraphAsync(context); AssertKeys(root, loadedRoot); AssertNavigations(loadedRoot); @@ -539,7 +534,7 @@ public virtual void Save_removed_optional_many_to_one_dependents_with_alternate_ [InlineData((int)ChangeMechanism.Principal, null)] [InlineData((int)ChangeMechanism.Dependent, null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent), null)] - public virtual void Save_removed_required_many_to_one_dependents_with_alternate_key( + public virtual Task Save_removed_required_many_to_one_dependents_with_alternate_key( ChangeMechanism changeMechanism, CascadeTiming? deleteOrphansTiming) { @@ -548,12 +543,12 @@ public virtual void Save_removed_required_many_to_one_dependents_with_alternate_ RequiredComposite2 removed2c = null; RequiredAk1 removed1 = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - root = LoadRequiredAkGraph(context); + root = await LoadRequiredAkGraphAsync(context); var firstChild = root.RequiredChildrenAk.OrderByDescending(c => c.Id).First(); var childCollection = firstChild.Children; @@ -585,12 +580,20 @@ public virtual void Save_removed_required_many_to_one_dependents_with_alternate_ || deleteOrphansTiming == CascadeTiming.Never) { var testCode = deleteOrphansTiming == CascadeTiming.Immediate - ? () => context.ChangeTracker.DetectChanges() + ? () => + { + context.ChangeTracker.DetectChanges(); + return Task.CompletedTask; + } : deleteOrphansTiming == null - ? () => context.ChangeTracker.CascadeChanges() - : (Action)(() => context.SaveChanges()); + ? () => + { + context.ChangeTracker.CascadeChanges(); + return Task.CompletedTask; + } + : (Func)(() => context.SaveChangesAsync()); - var message = Assert.Throws(testCode).Message; + var message = (await Assert.ThrowsAsync(testCode)).Message; Assert.True( message @@ -609,7 +612,7 @@ public virtual void Save_removed_required_many_to_one_dependents_with_alternate_ context.ChangeTracker.CascadeChanges(); } - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -621,14 +624,13 @@ public virtual void Save_removed_required_many_to_one_dependents_with_alternate_ Assert.Null(removed2.Parent); Assert.Null(removed2c.Parent); } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction && !Fixture.NoStoreCascades && deleteOrphansTiming != CascadeTiming.Never) { - var loadedRoot = LoadRequiredAkGraph(context); + var loadedRoot = await LoadRequiredAkGraphAsync(context); AssertKeys(root, loadedRoot); AssertNavigations(loadedRoot); @@ -655,20 +657,20 @@ public virtual void Save_removed_required_many_to_one_dependents_with_alternate_ [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] [InlineData(null, null)] - public virtual void Optional_many_to_one_dependents_with_alternate_key_are_orphaned( + public virtual Task Optional_many_to_one_dependents_with_alternate_key_are_orphaned( CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) { var removedId = 0; List orphanedIds = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming ?? CascadeTiming.Never; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - var root = LoadOptionalAkGraph(context); + var root = await LoadOptionalAkGraphAsync(context); Assert.Equal(2, root.OptionalChildrenAk.Count()); @@ -698,11 +700,11 @@ public virtual void Optional_many_to_one_dependents_with_alternate_key_are_orpha if (Fixture.ForceClientNoAction) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -718,12 +720,11 @@ public virtual void Optional_many_to_one_dependents_with_alternate_key_are_orpha Assert.Same(root, removed.Parent); Assert.Equal(2, removed.Children.Count()); } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction) { - var root = LoadOptionalAkGraph(context); + var root = await LoadOptionalAkGraphAsync(context); Assert.Single(root.OptionalChildrenAk); Assert.DoesNotContain(removedId, root.OptionalChildrenAk.Select(e => e.Id)); @@ -745,7 +746,7 @@ public virtual void Optional_many_to_one_dependents_with_alternate_key_are_orpha [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] [InlineData(null, null)] - public virtual void Required_many_to_one_dependents_with_alternate_key_are_cascade_deleted( + public virtual Task Required_many_to_one_dependents_with_alternate_key_are_cascade_deleted( CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) { @@ -753,13 +754,13 @@ public virtual void Required_many_to_one_dependents_with_alternate_key_are_casca List orphanedIds = null; List orphanedIdCs = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming ?? CascadeTiming.Never; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - var root = LoadRequiredAkGraph(context); + var root = await LoadRequiredAkGraphAsync(context); Assert.Equal(2, root.RequiredChildrenAk.Count()); @@ -799,15 +800,15 @@ public virtual void Required_many_to_one_dependents_with_alternate_key_are_casca if (Fixture.ForceClientNoAction) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else if (cascadeDeleteTiming == CascadeTiming.Never) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -824,13 +825,12 @@ public virtual void Required_many_to_one_dependents_with_alternate_key_are_casca Assert.Same(root, removed.Parent); Assert.Equal(2, removed.Children.Count()); } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction && cascadeDeleteTiming != CascadeTiming.Never) { - var root = LoadRequiredAkGraph(context); + var root = await LoadRequiredAkGraphAsync(context); Assert.Single(root.RequiredChildrenAk); Assert.DoesNotContain(removedId, root.RequiredChildrenAk.Select(e => e.Id)); @@ -853,7 +853,7 @@ public virtual void Required_many_to_one_dependents_with_alternate_key_are_casca [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] [InlineData(null, null)] - public virtual void Required_many_to_one_dependents_with_alternate_key_are_cascade_deleted_in_store( + public virtual Task Required_many_to_one_dependents_with_alternate_key_are_cascade_deleted_in_store( CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) { @@ -861,10 +861,10 @@ public virtual void Required_many_to_one_dependents_with_alternate_key_are_casca List orphanedIds = null; List orphanedIdCs = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var removed = LoadRequiredAkGraph(context).RequiredChildrenAk.First(); + var removed = (await LoadRequiredAkGraphAsync(context)).RequiredChildrenAk.First(); removedId = removed.Id; orphanedIds = removed.Children.Select(e => e.Id).ToList(); @@ -872,13 +872,12 @@ public virtual void Required_many_to_one_dependents_with_alternate_key_are_casca Assert.Equal(2, orphanedIds.Count); Assert.Equal(2, orphanedIdCs.Count); - }, - context => + }, async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming ?? CascadeTiming.Never; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - var root = context.Set().Include(e => e.RequiredChildrenAk).Single(IsTheRoot); + var root = await context.Set().Include(e => e.RequiredChildrenAk).SingleAsync(IsTheRoot); context.Set().Load(); var removed = root.RequiredChildrenAk.Single(e => e.Id == removedId); @@ -895,11 +894,11 @@ public virtual void Required_many_to_one_dependents_with_alternate_key_are_casca if (Fixture.ForceClientNoAction || Fixture.NoStoreCascades) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -915,13 +914,12 @@ public virtual void Required_many_to_one_dependents_with_alternate_key_are_casca Assert.Same(root, removed.Parent); Assert.Empty(removed.Children); // Never loaded } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction && !Fixture.NoStoreCascades) { - var root = LoadRequiredAkGraph(context); + var root = await LoadRequiredAkGraphAsync(context); Assert.Single(root.RequiredChildrenAk); Assert.DoesNotContain(removedId, root.RequiredChildrenAk.Select(e => e.Id)); @@ -944,7 +942,7 @@ public virtual void Required_many_to_one_dependents_with_alternate_key_are_casca [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] [InlineData(null, null)] - public virtual void Optional_many_to_one_dependents_with_alternate_key_are_orphaned_in_store( + public virtual Task Optional_many_to_one_dependents_with_alternate_key_are_orphaned_in_store( CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) { @@ -952,10 +950,10 @@ public virtual void Optional_many_to_one_dependents_with_alternate_key_are_orpha List orphanedIds = null; List orphanedIdCs = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var removed = LoadOptionalAkGraph(context).OptionalChildrenAk.OrderBy(c => c.Id).First(); + var removed = (await LoadOptionalAkGraphAsync(context)).OptionalChildrenAk.OrderBy(c => c.Id).First(); removedId = removed.Id; orphanedIds = removed.Children.Select(e => e.Id).ToList(); @@ -963,20 +961,19 @@ public virtual void Optional_many_to_one_dependents_with_alternate_key_are_orpha Assert.Equal(2, orphanedIds.Count); Assert.Equal(2, orphanedIdCs.Count); - }, - context => + }, async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming ?? CascadeTiming.Never; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - var root = context.Set().Include(e => e.OptionalChildrenAk).Single(IsTheRoot); + var root = await context.Set().Include(e => e.OptionalChildrenAk).SingleAsync(IsTheRoot); context.Entry(root).Collection(e => e.OptionalChildrenAk).Load(); var removed = root.OptionalChildrenAk.First(e => e.Id == removedId); context.Remove(removed); - foreach (var toOrphan in context.Set().Where(e => orphanedIdCs.Contains(e.Id)).ToList()) + foreach (var toOrphan in await context.Set().Where(e => orphanedIdCs.Contains(e.Id)).ToListAsync()) { toOrphan.ParentId = null; } @@ -990,11 +987,11 @@ public virtual void Optional_many_to_one_dependents_with_alternate_key_are_orpha if (Fixture.ForceClientNoAction) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -1005,34 +1002,33 @@ public virtual void Optional_many_to_one_dependents_with_alternate_key_are_orpha Assert.Empty(context.Set().Where(e => e.Id == removedId)); - var orphaned = context.Set().Where(e => orphanedIds.Contains(e.Id)).ToList(); + var orphaned = await context.Set().Where(e => orphanedIds.Contains(e.Id)).ToListAsync(); Assert.Equal(orphanedIds.Count, orphaned.Count); Assert.True(orphaned.All(e => e.ParentId == null)); - var orphanedC = context.Set().Where(e => orphanedIdCs.Contains(e.Id)).ToList(); + var orphanedC = await context.Set().Where(e => orphanedIdCs.Contains(e.Id)).ToListAsync(); Assert.Equal(orphanedIdCs.Count, orphanedC.Count); Assert.True(orphanedC.All(e => e.ParentId == null)); Assert.Same(root, removed.Parent); Assert.Empty(removed.Children); // Never loaded } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction) { - var root = LoadOptionalAkGraph(context); + var root = await LoadOptionalAkGraphAsync(context); Assert.Single(root.OptionalChildrenAk); Assert.DoesNotContain(removedId, root.OptionalChildrenAk.Select(e => e.Id)); Assert.Empty(context.Set().Where(e => e.Id == removedId)); - var orphaned = context.Set().Where(e => orphanedIds.Contains(e.Id)).ToList(); + var orphaned = await context.Set().Where(e => orphanedIds.Contains(e.Id)).ToListAsync(); Assert.Equal(orphanedIds.Count, orphaned.Count); Assert.True(orphaned.All(e => e.ParentId == null)); - var orphanedC = context.Set().Where(e => orphanedIdCs.Contains(e.Id)).ToList(); + var orphanedC = await context.Set().Where(e => orphanedIdCs.Contains(e.Id)).ToListAsync(); Assert.Equal(orphanedIdCs.Count, orphanedC.Count); Assert.True(orphanedC.All(e => e.ParentId == null)); } @@ -1050,7 +1046,7 @@ public virtual void Optional_many_to_one_dependents_with_alternate_key_are_orpha [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] [InlineData(null, null)] - public virtual void Optional_many_to_one_dependents_with_alternate_key_are_orphaned_starting_detached( + public virtual Task Optional_many_to_one_dependents_with_alternate_key_are_orphaned_starting_detached( CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) { @@ -1059,14 +1055,13 @@ public virtual void Optional_many_to_one_dependents_with_alternate_key_are_orpha List orphanedIdCs = null; Root root = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - root = LoadOptionalAkGraph(context); + root = await LoadOptionalAkGraphAsync(context); Assert.Equal(2, root.OptionalChildrenAk.Count()); - }, - context => + }, async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming ?? CascadeTiming.Never; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; @@ -1106,11 +1101,11 @@ public virtual void Optional_many_to_one_dependents_with_alternate_key_are_orpha if (Fixture.ForceClientNoAction) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -1121,12 +1116,11 @@ public virtual void Optional_many_to_one_dependents_with_alternate_key_are_orpha Assert.Same(root, removed.Parent); Assert.Equal(2, removed.Children.Count()); } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction) { - root = LoadOptionalAkGraph(context); + root = await LoadOptionalAkGraphAsync(context); Assert.Single(root.OptionalChildrenAk); Assert.DoesNotContain(removedId, root.OptionalChildrenAk.Select(e => e.Id)); @@ -1149,7 +1143,7 @@ public virtual void Optional_many_to_one_dependents_with_alternate_key_are_orpha [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] [InlineData(null, null)] - public virtual void Required_many_to_one_dependents_with_alternate_key_are_cascade_deleted_starting_detached( + public virtual Task Required_many_to_one_dependents_with_alternate_key_are_cascade_deleted_starting_detached( CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) { @@ -1158,14 +1152,13 @@ public virtual void Required_many_to_one_dependents_with_alternate_key_are_casca List orphanedIdCs = null; Root root = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - root = LoadRequiredAkGraph(context); + root = await LoadRequiredAkGraphAsync(context); Assert.Equal(2, root.RequiredChildrenAk.Count()); - }, - context => + }, async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming ?? CascadeTiming.Never; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; @@ -1204,15 +1197,15 @@ public virtual void Required_many_to_one_dependents_with_alternate_key_are_casca if (Fixture.ForceClientNoAction) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else if (cascadeDeleteTiming == CascadeTiming.Never) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -1223,13 +1216,12 @@ public virtual void Required_many_to_one_dependents_with_alternate_key_are_casca Assert.Same(root, removed.Parent); Assert.Equal(2, removed.Children.Count()); } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction && cascadeDeleteTiming != CascadeTiming.Never) { - root = LoadRequiredAkGraph(context); + root = await LoadRequiredAkGraphAsync(context); Assert.Single(root.RequiredChildrenAk); Assert.DoesNotContain(removedId, root.RequiredChildrenAk.Select(e => e.Id)); @@ -1252,7 +1244,7 @@ public virtual void Required_many_to_one_dependents_with_alternate_key_are_casca [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] [InlineData(null, null)] - public virtual void Required_many_to_one_dependents_with_alternate_key_are_cascade_detached_when_Added( + public virtual Task Required_many_to_one_dependents_with_alternate_key_are_cascade_detached_when_Added( CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) { @@ -1260,13 +1252,13 @@ public virtual void Required_many_to_one_dependents_with_alternate_key_are_casca List orphanedIds = null; List orphanedIdCs = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming ?? CascadeTiming.Never; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - var root = LoadRequiredAkGraph(context); + var root = await LoadRequiredAkGraphAsync(context); Assert.Equal(2, root.RequiredChildrenAk.Count()); @@ -1331,15 +1323,15 @@ public virtual void Required_many_to_one_dependents_with_alternate_key_are_casca if (Fixture.ForceClientNoAction) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else if (cascadeDeleteTiming == CascadeTiming.Never) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -1352,13 +1344,12 @@ public virtual void Required_many_to_one_dependents_with_alternate_key_are_casca Assert.Same(root, removed.Parent); Assert.Equal(3, removed.Children.Count()); } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction && cascadeDeleteTiming != CascadeTiming.Never) { - var root = LoadRequiredAkGraph(context); + var root = await LoadRequiredAkGraphAsync(context); Assert.Single(root.RequiredChildrenAk); Assert.DoesNotContain(removedId, root.RequiredChildrenAk.Select(e => e.Id)); diff --git a/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBaseOneToOne.cs b/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBaseOneToOne.cs index cbbfb0dc0be..7b3d7b72d49 100644 --- a/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBaseOneToOne.cs +++ b/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBaseOneToOne.cs @@ -17,14 +17,14 @@ public abstract partial class GraphUpdatesTestBase [InlineData(CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never)] [InlineData(null)] - public virtual void Optional_one_to_one_relationships_are_one_to_one( + public virtual Task Optional_one_to_one_relationships_are_one_to_one( CascadeTiming? deleteOrphansTiming) - => ExecuteWithStrategyInTransaction( - context => + => ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - var root = context.Set().Single(IsTheRoot); + var root = await context.Set().SingleAsync(IsTheRoot); Assert.False(context.ChangeTracker.HasChanges()); @@ -32,7 +32,7 @@ public virtual void Optional_one_to_one_relationships_are_one_to_one( Assert.True(context.ChangeTracker.HasChanges()); - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); }); [ConditionalTheory] @@ -94,7 +94,7 @@ public virtual void Optional_one_to_one_relationships_are_one_to_one( [InlineData((int)(ChangeMechanism.Fk | ChangeMechanism.Dependent), true, null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), false, null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), true, null)] - public virtual void Save_changed_optional_one_to_one( + public virtual Task Save_changed_optional_one_to_one( ChangeMechanism changeMechanism, bool useExistingEntities, CascadeTiming? deleteOrphansTiming) @@ -114,20 +114,19 @@ public virtual void Save_changed_optional_one_to_one( OptionalSingle2Derived old2d = null; OptionalSingle2MoreDerived old2dd = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { if (useExistingEntities) { context.AddRange(new1, new1d, new1dd, new2, new2d, new2dd); - context.SaveChanges(); + await context.SaveChangesAsync(); } - }, - context => + }, async context => { context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - root = LoadOptionalGraph(context); + root = await LoadOptionalGraphAsync(context); old1 = root.OptionalSingle; old1d = root.OptionalSingleDerived; @@ -138,12 +137,12 @@ public virtual void Save_changed_optional_one_to_one( if (useExistingEntities) { - new1 = context.Set().Single(e => e.Id == new1.Id); - new1d = (OptionalSingle1Derived)context.Set().Single(e => e.Id == new1d.Id); - new1dd = (OptionalSingle1MoreDerived)context.Set().Single(e => e.Id == new1dd.Id); - new2 = context.Set().Single(e => e.Id == new2.Id); - new2d = (OptionalSingle2Derived)context.Set().Single(e => e.Id == new2d.Id); - new2dd = (OptionalSingle2MoreDerived)context.Set().Single(e => e.Id == new2dd.Id); + new1 = await context.Set().SingleAsync(e => e.Id == new1.Id); + new1d = (OptionalSingle1Derived)await context.Set().SingleAsync(e => e.Id == new1d.Id); + new1dd = (OptionalSingle1MoreDerived)await context.Set().SingleAsync(e => e.Id == new1dd.Id); + new2 = await context.Set().SingleAsync(e => e.Id == new2.Id); + new2d = (OptionalSingle2Derived)await context.Set().SingleAsync(e => e.Id == new2d.Id); + new2dd = (OptionalSingle2MoreDerived)await context.Set().SingleAsync(e => e.Id == new2dd.Id); } else { @@ -173,7 +172,7 @@ public virtual void Save_changed_optional_one_to_one( Assert.True(context.ChangeTracker.HasChanges()); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -204,20 +203,19 @@ public virtual void Save_changed_optional_one_to_one( Assert.Equal(old1dd.Id, old2dd.BackId); entries = context.ChangeTracker.Entries().ToList(); - }, - context => + }, async context => { - var loadedRoot = LoadOptionalGraph(context); + var loadedRoot = await LoadOptionalGraphAsync(context); AssertKeys(root, loadedRoot); AssertNavigations(loadedRoot); - var loaded1 = context.Set().Single(e => e.Id == old1.Id); - var loaded1d = context.Set().Single(e => e.Id == old1d.Id); - var loaded1dd = context.Set().Single(e => e.Id == old1dd.Id); - var loaded2 = context.Set().Single(e => e.Id == old2.Id); - var loaded2d = context.Set().Single(e => e.Id == old2d.Id); - var loaded2dd = context.Set().Single(e => e.Id == old2dd.Id); + var loaded1 = await context.Set().SingleAsync(e => e.Id == old1.Id); + var loaded1d = await context.Set().SingleAsync(e => e.Id == old1d.Id); + var loaded1dd = await context.Set().SingleAsync(e => e.Id == old1dd.Id); + var loaded2 = await context.Set().SingleAsync(e => e.Id == old2.Id); + var loaded2d = await context.Set().SingleAsync(e => e.Id == old2d.Id); + var loaded2dd = await context.Set().SingleAsync(e => e.Id == old2dd.Id); AssertEntries(entries, context.ChangeTracker.Entries().ToList()); @@ -265,19 +263,19 @@ public virtual void Save_changed_optional_one_to_one( [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Fk), null)] [InlineData((int)(ChangeMechanism.Fk | ChangeMechanism.Dependent), null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), null)] - public virtual void Sever_optional_one_to_one( + public virtual Task Sever_optional_one_to_one( ChangeMechanism changeMechanism, CascadeTiming? deleteOrphansTiming) { Root root = null; OptionalSingle1 old1 = null; OptionalSingle2 old2 = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - root = LoadOptionalGraph(context); + root = await LoadOptionalGraphAsync(context); old1 = root.OptionalSingle; old2 = root.OptionalSingle.Single; @@ -301,7 +299,7 @@ public virtual void Sever_optional_one_to_one( Assert.False(context.Entry(old1).Reference(e => e.Root).IsLoaded); Assert.True(context.ChangeTracker.HasChanges()); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -309,18 +307,17 @@ public virtual void Sever_optional_one_to_one( Assert.Same(old1, old2.Back); Assert.Null(old1.RootId); Assert.Equal(old1.Id, old2.BackId); - }, - context => + }, async context => { if ((changeMechanism & ChangeMechanism.Fk) == 0) { - var loadedRoot = LoadOptionalGraph(context); + var loadedRoot = await LoadOptionalGraphAsync(context); AssertKeys(root, loadedRoot); AssertPossiblyNullNavigations(loadedRoot); - var loaded1 = context.Set().Single(e => e.Id == old1.Id); - var loaded2 = context.Set().Single(e => e.Id == old2.Id); + var loaded1 = await context.Set().SingleAsync(e => e.Id == old1.Id); + var loaded2 = await context.Set().SingleAsync(e => e.Id == old2.Id); Assert.Null(loaded1.Root); Assert.Same(loaded1, loaded2.Back); @@ -389,7 +386,7 @@ public virtual void Sever_optional_one_to_one( [InlineData((int)(ChangeMechanism.Fk | ChangeMechanism.Dependent), true, null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), false, null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), true, null)] - public virtual void Reparent_optional_one_to_one( + public virtual Task Reparent_optional_one_to_one( ChangeMechanism changeMechanism, bool useExistingRoot, CascadeTiming? deleteOrphansTiming) @@ -399,20 +396,19 @@ public virtual void Reparent_optional_one_to_one( OptionalSingle1 old1 = null; OptionalSingle2 old2 = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { if (useExistingRoot) { context.AddRange(newRoot); - context.SaveChanges(); + await context.SaveChangesAsync(); } - }, - context => + }, async context => { context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - root = LoadOptionalGraph(context); + root = await LoadOptionalGraphAsync(context); context.Entry(newRoot).State = useExistingRoot ? EntityState.Unchanged : EntityState.Added; @@ -436,7 +432,7 @@ public virtual void Reparent_optional_one_to_one( Assert.True(context.ChangeTracker.HasChanges()); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -446,17 +442,16 @@ public virtual void Reparent_optional_one_to_one( Assert.Same(old1, old2.Back); Assert.Equal(newRoot.Id, old1.RootId); Assert.Equal(old1.Id, old2.BackId); - }, - context => + }, async context => { - var loadedRoot = LoadOptionalGraph(context); + var loadedRoot = await LoadOptionalGraphAsync(context); AssertKeys(root, loadedRoot); AssertPossiblyNullNavigations(loadedRoot); - newRoot = context.Set().Single(e => e.Id == newRoot.Id); - var loaded1 = context.Set().Single(e => e.Id == old1.Id); - var loaded2 = context.Set().Single(e => e.Id == old2.Id); + newRoot = await context.Set().SingleAsync(e => e.Id == newRoot.Id); + var loaded1 = await context.Set().SingleAsync(e => e.Id == old1.Id); + var loaded2 = await context.Set().SingleAsync(e => e.Id == old2.Id); Assert.Same(newRoot, loaded1.Root); Assert.Same(loaded1, loaded2.Back); @@ -476,20 +471,20 @@ public virtual void Reparent_optional_one_to_one( [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] [InlineData(null, null)] - public virtual void Optional_one_to_one_are_orphaned( + public virtual Task Optional_one_to_one_are_orphaned( CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) { var removedId = 0; var orphanedId = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming ?? CascadeTiming.Never; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - var root = LoadOptionalGraph(context); + var root = await LoadOptionalGraphAsync(context); var removed = root.OptionalSingle; @@ -513,11 +508,11 @@ public virtual void Optional_one_to_one_are_orphaned( if (Fixture.ForceClientNoAction) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -532,12 +527,11 @@ public virtual void Optional_one_to_one_are_orphaned( Assert.Same(root, removed.Root); Assert.Same(orphaned, removed.Single); } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction) { - var root = LoadOptionalGraph(context); + var root = await LoadOptionalGraphAsync(context); Assert.Null(root.OptionalSingle); @@ -558,19 +552,19 @@ public virtual void Optional_one_to_one_are_orphaned( [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] [InlineData(null, null)] - public virtual void Optional_one_to_one_leaf_can_be_deleted( + public virtual Task Optional_one_to_one_leaf_can_be_deleted( CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) { var removedId = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming ?? CascadeTiming.Never; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - var root = LoadOptionalGraph(context); + var root = await LoadOptionalGraphAsync(context); var parent = root.OptionalSingle; var removed = parent.Single; @@ -586,7 +580,7 @@ public virtual void Optional_one_to_one_leaf_can_be_deleted( context.ChangeTracker.CascadeChanges(); } - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -595,10 +589,9 @@ public virtual void Optional_one_to_one_leaf_can_be_deleted( Assert.Null(parent.Single); Assert.Empty(context.Set().Where(e => e.Id == removedId)); Assert.Same(parent, removed.Back); - }, - context => + }, async context => { - var root = LoadOptionalGraph(context); + var root = await LoadOptionalGraphAsync(context); var parent = root.OptionalSingle; Assert.Null(parent.Single); @@ -617,27 +610,26 @@ public virtual void Optional_one_to_one_leaf_can_be_deleted( [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] [InlineData(null, null)] - public virtual void Optional_one_to_one_are_orphaned_in_store( + public virtual Task Optional_one_to_one_are_orphaned_in_store( CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) { var removedId = 0; var orphanedId = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var removed = LoadOptionalGraph(context).OptionalSingle; + var removed = (await LoadOptionalGraphAsync(context)).OptionalSingle; removedId = removed.Id; orphanedId = removed.Single.Id; - }, - context => + }, async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming ?? CascadeTiming.Never; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - var root = context.Set().Include(e => e.OptionalSingle).Single(IsTheRoot); + var root = await context.Set().Include(e => e.OptionalSingle).SingleAsync(IsTheRoot); var removed = root.OptionalSingle; var orphaned = removed.Single; @@ -653,11 +645,11 @@ public virtual void Optional_one_to_one_are_orphaned_in_store( if (Fixture.ForceClientNoAction) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -666,22 +658,21 @@ public virtual void Optional_one_to_one_are_orphaned_in_store( Assert.Null(root.OptionalSingle); Assert.Empty(context.Set().Where(e => e.Id == removedId)); - Assert.Null(context.Set().Single(e => e.Id == orphanedId).BackId); + Assert.Null((await context.Set().SingleAsync(e => e.Id == orphanedId)).BackId); Assert.Same(root, removed.Root); Assert.Same(orphaned, removed.Single); } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction) { - var root = LoadOptionalGraph(context); + var root = await LoadOptionalGraphAsync(context); Assert.Null(root.OptionalSingle); Assert.Empty(context.Set().Where(e => e.Id == removedId)); - Assert.Null(context.Set().Single(e => e.Id == orphanedId).BackId); + Assert.Null((await context.Set().SingleAsync(e => e.Id == orphanedId)).BackId); } }); } @@ -697,7 +688,7 @@ public virtual void Optional_one_to_one_are_orphaned_in_store( [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] [InlineData(null, null)] - public virtual void Optional_one_to_one_are_orphaned_starting_detached( + public virtual Task Optional_one_to_one_are_orphaned_starting_detached( CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) { @@ -705,9 +696,8 @@ public virtual void Optional_one_to_one_are_orphaned_starting_detached( var orphanedId = 0; Root root = null; - ExecuteWithStrategyInTransaction( - context => root = LoadOptionalGraph(context), - context => + return ExecuteWithStrategyInTransactionAsync( + async context => root = await LoadOptionalGraphAsync(context), async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming ?? CascadeTiming.Never; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; @@ -740,11 +730,11 @@ public virtual void Optional_one_to_one_are_orphaned_starting_detached( if (Fixture.ForceClientNoAction) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -754,12 +744,11 @@ public virtual void Optional_one_to_one_are_orphaned_starting_detached( Assert.Same(root, removed.Root); Assert.Same(orphaned, removed.Single); } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction) { - root = LoadOptionalGraph(context); + root = await LoadOptionalGraphAsync(context); Assert.Null(root.OptionalSingle); @@ -774,14 +763,14 @@ public virtual void Optional_one_to_one_are_orphaned_starting_detached( [InlineData(CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never)] [InlineData(null)] - public virtual void Required_one_to_one_relationships_are_one_to_one( + public virtual Task Required_one_to_one_relationships_are_one_to_one( CascadeTiming? deleteOrphansTiming) - => ExecuteWithStrategyInTransaction( - context => + => ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - var root = context.Set().Single(IsTheRoot); + var root = await context.Set().SingleAsync(IsTheRoot); Assert.False(context.ChangeTracker.HasChanges()); @@ -789,7 +778,7 @@ public virtual void Required_one_to_one_relationships_are_one_to_one( Assert.True(context.ChangeTracker.HasChanges()); - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); }); [ConditionalTheory] @@ -821,7 +810,7 @@ public virtual void Required_one_to_one_relationships_are_one_to_one( [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Fk), null)] [InlineData((int)(ChangeMechanism.Fk | ChangeMechanism.Dependent), null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), null)] - public virtual void Save_required_one_to_one_changed_by_reference( + public virtual async Task Save_required_one_to_one_changed_by_reference( ChangeMechanism changeMechanism, CascadeTiming? deleteOrphansTiming) { @@ -835,10 +824,10 @@ public virtual void Save_required_one_to_one_changed_by_reference( IReadOnlyList entries = null; RequiredSingle1 old1 = null; RequiredSingle2 old2 = null; - ExecuteWithStrategyInTransaction( - context => + await ExecuteWithStrategyInTransactionAsync( + async context => { - oldRoot = LoadRequiredGraph(context); + oldRoot = await LoadRequiredGraphAsync(context); old1 = oldRoot.RequiredSingle; old2 = oldRoot.RequiredSingle.Single; @@ -847,30 +836,29 @@ public virtual void Save_required_one_to_one_changed_by_reference( var new2 = new RequiredSingle2(); var new1 = new RequiredSingle1 { Single = new2 }; - ExecuteWithStrategyInTransaction( - context => + await ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - var root = LoadRequiredGraph(context); + var root = await LoadRequiredGraphAsync(context); root.RequiredSingle = null; if (Fixture.ForceClientNoAction) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction && !Fixture.NoStoreCascades) { - var root = LoadRequiredGraph(context); + var root = await LoadRequiredGraphAsync(context); if ((changeMechanism & ChangeMechanism.Principal) != 0) { @@ -893,7 +881,7 @@ public virtual void Save_required_one_to_one_changed_by_reference( Assert.True(context.ChangeTracker.HasChanges()); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -908,13 +896,12 @@ public virtual void Save_required_one_to_one_changed_by_reference( entries = context.ChangeTracker.Entries().ToList(); } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction && !Fixture.NoStoreCascades) { - var loadedRoot = LoadRequiredGraph(context); + var loadedRoot = await LoadRequiredGraphAsync(context); AssertEntries(entries, context.ChangeTracker.Entries().ToList()); AssertKeys(oldRoot, loadedRoot); @@ -982,7 +969,7 @@ public virtual void Save_required_one_to_one_changed_by_reference( [InlineData((int)(ChangeMechanism.Fk | ChangeMechanism.Dependent), true, null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), false, null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), true, null)] - public virtual void Save_required_non_PK_one_to_one_changed_by_reference( + public virtual Task Save_required_non_PK_one_to_one_changed_by_reference( ChangeMechanism changeMechanism, bool useExistingEntities, CascadeTiming? deleteOrphansTiming) @@ -1013,20 +1000,19 @@ public virtual void Save_required_non_PK_one_to_one_changed_by_reference( RequiredNonPkSingle2Derived old2d = null; RequiredNonPkSingle2MoreDerived old2dd = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { if (useExistingEntities) { context.AddRange(newRoot, new1, new1d, new1dd, new2, new2d, new2dd); - context.SaveChanges(); + await context.SaveChangesAsync(); } - }, - context => + }, async context => { context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - root = LoadRequiredNonPkGraph(context); + root = await LoadRequiredNonPkGraphAsync(context); old1 = root.RequiredNonPkSingle; old1d = root.RequiredNonPkSingleDerived; @@ -1040,12 +1026,12 @@ public virtual void Save_required_non_PK_one_to_one_changed_by_reference( if (useExistingEntities) { - new1 = context.Set().Single(e => e.Id == new1.Id); - new1d = (RequiredNonPkSingle1Derived)context.Set().Single(e => e.Id == new1d.Id); - new1dd = (RequiredNonPkSingle1MoreDerived)context.Set().Single(e => e.Id == new1dd.Id); - new2 = context.Set().Single(e => e.Id == new2.Id); - new2d = (RequiredNonPkSingle2Derived)context.Set().Single(e => e.Id == new2d.Id); - new2dd = (RequiredNonPkSingle2MoreDerived)context.Set().Single(e => e.Id == new2dd.Id); + new1 = await context.Set().SingleAsync(e => e.Id == new1.Id); + new1d = (RequiredNonPkSingle1Derived)await context.Set().SingleAsync(e => e.Id == new1d.Id); + new1dd = (RequiredNonPkSingle1MoreDerived)await context.Set().SingleAsync(e => e.Id == new1dd.Id); + new2 = await context.Set().SingleAsync(e => e.Id == new2.Id); + new2d = (RequiredNonPkSingle2Derived)await context.Set().SingleAsync(e => e.Id == new2d.Id); + new2dd = (RequiredNonPkSingle2MoreDerived)await context.Set().SingleAsync(e => e.Id == new2dd.Id); new1d.RootId = old1d.RootId; new1dd.RootId = old1dd.RootId; @@ -1084,12 +1070,20 @@ public virtual void Save_required_non_PK_one_to_one_changed_by_reference( || deleteOrphansTiming == CascadeTiming.Never) { var testCode = deleteOrphansTiming == CascadeTiming.Immediate - ? () => context.ChangeTracker.DetectChanges() + ? () => + { + context.ChangeTracker.DetectChanges(); + return Task.CompletedTask; + } : deleteOrphansTiming == null - ? () => context.ChangeTracker.CascadeChanges() - : (Action)(() => context.SaveChanges()); + ? () => + { + context.ChangeTracker.CascadeChanges(); + return Task.CompletedTask; + } + : (Func)(async () => await context.SaveChangesAsync()); - var message = Assert.Throws(testCode).Message; + var message = (await Assert.ThrowsAsync(testCode)).Message; Assert.Equal( message, @@ -1105,7 +1099,7 @@ public virtual void Save_required_non_PK_one_to_one_changed_by_reference( context.ChangeTracker.CascadeChanges(); } - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -1134,14 +1128,13 @@ public virtual void Save_required_non_PK_one_to_one_changed_by_reference( entries = context.ChangeTracker.Entries().ToList(); } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction && !Fixture.NoStoreCascades && deleteOrphansTiming != CascadeTiming.Never) { - var loadedRoot = LoadRequiredNonPkGraph(context); + var loadedRoot = await LoadRequiredNonPkGraphAsync(context); AssertEntries(entries, context.ChangeTracker.Entries().ToList()); AssertKeys(root, loadedRoot); @@ -1170,19 +1163,19 @@ public virtual void Save_required_non_PK_one_to_one_changed_by_reference( [InlineData((int)ChangeMechanism.Principal, null)] [InlineData((int)ChangeMechanism.Dependent, null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent), null)] - public virtual void Sever_required_one_to_one( + public virtual Task Sever_required_one_to_one( ChangeMechanism changeMechanism, CascadeTiming? deleteOrphansTiming) { Root root = null; RequiredSingle1 old1 = null; RequiredSingle2 old2 = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - root = LoadRequiredGraph(context); + root = await LoadRequiredGraphAsync(context); old1 = root.RequiredSingle; old2 = root.RequiredSingle.Single; @@ -1208,7 +1201,7 @@ public virtual void Sever_required_one_to_one( if (Fixture.ForceClientNoAction) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { @@ -1216,7 +1209,7 @@ public virtual void Sever_required_one_to_one( Assert.False(context.Entry(old1).Reference(e => e.Root).IsLoaded); Assert.True(context.ChangeTracker.HasChanges()); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -1229,13 +1222,12 @@ public virtual void Sever_required_one_to_one( Assert.Equal(old1.Id, old2.Id); } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction && !Fixture.NoStoreCascades) { - var loadedRoot = LoadRequiredGraph(context); + var loadedRoot = await LoadRequiredGraphAsync(context); AssertKeys(root, loadedRoot); AssertPossiblyNullNavigations(loadedRoot); @@ -1267,19 +1259,19 @@ public virtual void Sever_required_one_to_one( [InlineData((int)ChangeMechanism.Principal, null)] [InlineData((int)ChangeMechanism.Dependent, null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent), null)] - public virtual void Sever_required_non_PK_one_to_one( + public virtual Task Sever_required_non_PK_one_to_one( ChangeMechanism changeMechanism, CascadeTiming? deleteOrphansTiming) { Root root = null; RequiredNonPkSingle1 old1 = null; RequiredNonPkSingle2 old2 = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - root = LoadRequiredNonPkGraph(context); + root = await LoadRequiredNonPkGraphAsync(context); old1 = root.RequiredNonPkSingle; old2 = root.RequiredNonPkSingle.Single; @@ -1303,12 +1295,20 @@ public virtual void Sever_required_non_PK_one_to_one( || deleteOrphansTiming == CascadeTiming.Never) { var testCode = deleteOrphansTiming == CascadeTiming.Immediate - ? () => context.ChangeTracker.DetectChanges() + ? () => + { + context.ChangeTracker.DetectChanges(); + return Task.CompletedTask; + } : deleteOrphansTiming == null - ? () => context.ChangeTracker.CascadeChanges() - : (Action)(() => context.SaveChanges()); + ? () => + { + context.ChangeTracker.CascadeChanges(); + return Task.CompletedTask; + } + : (Func)(async () => await context.SaveChangesAsync()); - var message = Assert.Throws(testCode).Message; + var message = (await Assert.ThrowsAsync(testCode)).Message; Assert.Equal( message, @@ -1326,7 +1326,7 @@ public virtual void Sever_required_non_PK_one_to_one( context.ChangeTracker.CascadeChanges(); } - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -1334,14 +1334,13 @@ public virtual void Sever_required_non_PK_one_to_one( Assert.Null(old2.Back); Assert.Equal(old1.Id, old2.BackId); } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction && !Fixture.NoStoreCascades && deleteOrphansTiming != CascadeTiming.Never) { - var loadedRoot = LoadRequiredNonPkGraph(context); + var loadedRoot = await LoadRequiredNonPkGraphAsync(context); AssertKeys(root, loadedRoot); AssertPossiblyNullNavigations(loadedRoot); @@ -1411,27 +1410,26 @@ public virtual void Sever_required_non_PK_one_to_one( [InlineData((int)(ChangeMechanism.Fk | ChangeMechanism.Dependent), true, null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), false, null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), true, null)] - public virtual void Reparent_required_one_to_one( + public virtual Task Reparent_required_one_to_one( ChangeMechanism changeMechanism, bool useExistingRoot, CascadeTiming? deleteOrphansTiming) { var newRoot = new Root(); - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { if (useExistingRoot) { context.AddRange(newRoot); - context.SaveChanges(); + await context.SaveChangesAsync(); } - }, - context => + }, async context => { context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - var root = LoadRequiredGraph(context); + var root = await LoadRequiredGraphAsync(context); Assert.False(context.ChangeTracker.HasChanges()); @@ -1439,8 +1437,8 @@ public virtual void Reparent_required_one_to_one( Assert.Equal( CoreStrings.KeyReadOnly("Id", typeof(RequiredSingle1).Name), - Assert.Throws( - () => + (await Assert.ThrowsAsync( + async () => { if ((changeMechanism & ChangeMechanism.Principal) != 0) { @@ -1459,8 +1457,8 @@ public virtual void Reparent_required_one_to_one( newRoot.RequiredSingle = root.RequiredSingle; - context.SaveChanges(); - }).Message); + await context.SaveChangesAsync(); + })).Message); }); } @@ -1523,7 +1521,7 @@ public virtual void Reparent_required_one_to_one( [InlineData((int)(ChangeMechanism.Fk | ChangeMechanism.Dependent), true, null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), false, null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), true, null)] - public virtual void Reparent_required_non_PK_one_to_one( + public virtual Task Reparent_required_non_PK_one_to_one( ChangeMechanism changeMechanism, bool useExistingRoot, CascadeTiming? deleteOrphansTiming) @@ -1533,20 +1531,19 @@ public virtual void Reparent_required_non_PK_one_to_one( RequiredNonPkSingle1 old1 = null; RequiredNonPkSingle2 old2 = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { if (useExistingRoot) { context.AddRange(newRoot); - context.SaveChanges(); + await context.SaveChangesAsync(); } - }, - context => + }, async context => { context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - root = LoadRequiredNonPkGraph(context); + root = await LoadRequiredNonPkGraphAsync(context); context.Entry(newRoot).State = useExistingRoot ? EntityState.Unchanged : EntityState.Added; @@ -1570,7 +1567,7 @@ public virtual void Reparent_required_non_PK_one_to_one( Assert.True(context.ChangeTracker.HasChanges()); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -1580,17 +1577,16 @@ public virtual void Reparent_required_non_PK_one_to_one( Assert.Same(old1, old2.Back); Assert.Equal(newRoot.Id, old1.RootId); Assert.Equal(old1.Id, old2.BackId); - }, - context => + }, async context => { - var loadedRoot = LoadRequiredNonPkGraph(context); + var loadedRoot = await LoadRequiredNonPkGraphAsync(context); AssertKeys(root, loadedRoot); AssertPossiblyNullNavigations(loadedRoot); - newRoot = context.Set().Single(e => e.Id == newRoot.Id); - var loaded1 = context.Set().Single(e => e.Id == old1.Id); - var loaded2 = context.Set().Single(e => e.Id == old2.Id); + newRoot = await context.Set().SingleAsync(e => e.Id == newRoot.Id); + var loaded1 = await context.Set().SingleAsync(e => e.Id == old1.Id); + var loaded2 = await context.Set().SingleAsync(e => e.Id == old2.Id); Assert.Same(newRoot, loaded1.Root); Assert.Same(loaded1, loaded2.Back); @@ -1610,20 +1606,20 @@ public virtual void Reparent_required_non_PK_one_to_one( [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] [InlineData(null, null)] - public virtual void Required_one_to_one_are_cascade_deleted( + public virtual Task Required_one_to_one_are_cascade_deleted( CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) { var removedId = 0; var orphanedId = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming ?? CascadeTiming.Never; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - var root = LoadRequiredGraph(context); + var root = await LoadRequiredGraphAsync(context); var removed = root.RequiredSingle; @@ -1647,15 +1643,15 @@ public virtual void Required_one_to_one_are_cascade_deleted( if (Fixture.ForceClientNoAction) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else if (cascadeDeleteTiming == CascadeTiming.Never) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -1667,13 +1663,12 @@ public virtual void Required_one_to_one_are_cascade_deleted( Assert.Same(root, removed.Root); Assert.Same(orphaned, removed.Single); } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction && cascadeDeleteTiming != CascadeTiming.Never) { - var root = LoadRequiredGraph(context); + var root = await LoadRequiredGraphAsync(context); Assert.Null(root.RequiredSingle); @@ -1702,19 +1697,19 @@ public virtual void Required_one_to_one_are_cascade_deleted( [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] [InlineData(null, null)] - public virtual void Required_one_to_one_leaf_can_be_deleted( + public virtual Task Required_one_to_one_leaf_can_be_deleted( CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) { var removedId = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming ?? CascadeTiming.Never; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - var root = LoadRequiredGraph(context); + var root = await LoadRequiredGraphAsync(context); var parent = root.RequiredSingle; var removed = parent.Single; @@ -1730,7 +1725,7 @@ public virtual void Required_one_to_one_leaf_can_be_deleted( context.ChangeTracker.CascadeChanges(); } - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -1738,10 +1733,9 @@ public virtual void Required_one_to_one_leaf_can_be_deleted( Assert.Null(parent.Single); Assert.Same(parent, removed.Back); - }, - context => + }, async context => { - var root = LoadRequiredGraph(context); + var root = await LoadRequiredGraphAsync(context); var parent = root.RequiredSingle; Assert.Null(parent.Single); @@ -1765,20 +1759,20 @@ public virtual void Required_one_to_one_leaf_can_be_deleted( [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] [InlineData(null, null)] - public virtual void Required_non_PK_one_to_one_are_cascade_deleted( + public virtual Task Required_non_PK_one_to_one_are_cascade_deleted( CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) { var removedId = 0; var orphanedId = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming ?? CascadeTiming.Never; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - var root = LoadRequiredNonPkGraph(context); + var root = await LoadRequiredNonPkGraphAsync(context); var removed = root.RequiredNonPkSingle; @@ -1802,15 +1796,15 @@ public virtual void Required_non_PK_one_to_one_are_cascade_deleted( if (Fixture.ForceClientNoAction) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else if (cascadeDeleteTiming == CascadeTiming.Never) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -1825,13 +1819,12 @@ public virtual void Required_non_PK_one_to_one_are_cascade_deleted( Assert.Same(root, removed.Root); Assert.Same(orphaned, removed.Single); } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction && cascadeDeleteTiming != CascadeTiming.Never) { - var root = LoadRequiredNonPkGraph(context); + var root = await LoadRequiredNonPkGraphAsync(context); Assert.Null(root.RequiredNonPkSingle); @@ -1852,19 +1845,19 @@ public virtual void Required_non_PK_one_to_one_are_cascade_deleted( [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] [InlineData(null, null)] - public virtual void Required_non_PK_one_to_one_leaf_can_be_deleted( + public virtual Task Required_non_PK_one_to_one_leaf_can_be_deleted( CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) { var removedId = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming ?? CascadeTiming.Never; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - var root = LoadRequiredNonPkGraph(context); + var root = await LoadRequiredNonPkGraphAsync(context); var parent = root.RequiredNonPkSingle; var removed = parent.Single; @@ -1880,7 +1873,7 @@ public virtual void Required_non_PK_one_to_one_leaf_can_be_deleted( context.ChangeTracker.CascadeChanges(); } - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -1888,10 +1881,9 @@ public virtual void Required_non_PK_one_to_one_leaf_can_be_deleted( Assert.Null(parent.Single); Assert.Same(parent, removed.Back); - }, - context => + }, async context => { - var root = LoadRequiredNonPkGraph(context); + var root = await LoadRequiredNonPkGraphAsync(context); var parent = root.RequiredNonPkSingle; Assert.Null(parent.Single); @@ -1910,27 +1902,26 @@ public virtual void Required_non_PK_one_to_one_leaf_can_be_deleted( [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] [InlineData(null, null)] - public virtual void Required_one_to_one_are_cascade_deleted_in_store( + public virtual Task Required_one_to_one_are_cascade_deleted_in_store( CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) { var removedId = 0; var orphanedId = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var removed = LoadRequiredGraph(context).RequiredSingle; + var removed = (await LoadRequiredGraphAsync(context)).RequiredSingle; removedId = removed.Id; orphanedId = removed.Single.Id; - }, - context => + }, async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming ?? CascadeTiming.Never; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - var root = context.Set().Include(e => e.RequiredSingle).Single(IsTheRoot); + var root = await context.Set().Include(e => e.RequiredSingle).SingleAsync(IsTheRoot); var removed = root.RequiredSingle; var orphaned = removed.Single; @@ -1947,11 +1938,11 @@ public virtual void Required_one_to_one_are_cascade_deleted_in_store( if (Fixture.ForceClientNoAction || Fixture.NoStoreCascades) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -1962,13 +1953,12 @@ public virtual void Required_one_to_one_are_cascade_deleted_in_store( Assert.Same(root, removed.Root); Assert.Same(orphaned, removed.Single); } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction && !Fixture.NoStoreCascades) { - var root = LoadRequiredGraph(context); + var root = await LoadRequiredGraphAsync(context); Assert.Null(root.RequiredSingle); @@ -1989,27 +1979,26 @@ public virtual void Required_one_to_one_are_cascade_deleted_in_store( [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] [InlineData(null, null)] - public virtual void Required_non_PK_one_to_one_are_cascade_deleted_in_store( + public virtual Task Required_non_PK_one_to_one_are_cascade_deleted_in_store( CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) { var removedId = 0; var orphanedId = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var removed = LoadRequiredNonPkGraph(context).RequiredNonPkSingle; + var removed = (await LoadRequiredNonPkGraphAsync(context)).RequiredNonPkSingle; removedId = removed.Id; orphanedId = removed.Single.Id; - }, - context => + }, async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming ?? CascadeTiming.Never; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - var root = context.Set().Include(e => e.RequiredNonPkSingle).Single(IsTheRoot); + var root = await context.Set().Include(e => e.RequiredNonPkSingle).SingleAsync(IsTheRoot); var removed = root.RequiredNonPkSingle; var orphaned = removed.Single; @@ -2026,11 +2015,11 @@ public virtual void Required_non_PK_one_to_one_are_cascade_deleted_in_store( if (Fixture.ForceClientNoAction || Fixture.NoStoreCascades) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -2044,13 +2033,12 @@ public virtual void Required_non_PK_one_to_one_are_cascade_deleted_in_store( Assert.Same(root, removed.Root); Assert.Same(orphaned, removed.Single); } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction && !Fixture.NoStoreCascades) { - var root = LoadRequiredNonPkGraph(context); + var root = await LoadRequiredNonPkGraphAsync(context); Assert.Null(root.RequiredNonPkSingle); @@ -2071,7 +2059,7 @@ public virtual void Required_non_PK_one_to_one_are_cascade_deleted_in_store( [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] [InlineData(null, null)] - public virtual void Required_one_to_one_are_cascade_deleted_starting_detached( + public virtual Task Required_one_to_one_are_cascade_deleted_starting_detached( CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) { @@ -2079,9 +2067,8 @@ public virtual void Required_one_to_one_are_cascade_deleted_starting_detached( var orphanedId = 0; Root root = null; - ExecuteWithStrategyInTransaction( - context => root = LoadRequiredGraph(context), - context => + return ExecuteWithStrategyInTransactionAsync( + async context => root = await LoadRequiredGraphAsync(context), async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming ?? CascadeTiming.Never; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; @@ -2114,15 +2101,15 @@ public virtual void Required_one_to_one_are_cascade_deleted_starting_detached( if (Fixture.ForceClientNoAction) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else if (cascadeDeleteTiming == CascadeTiming.Never) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -2132,8 +2119,7 @@ public virtual void Required_one_to_one_are_cascade_deleted_starting_detached( Assert.Same(root, removed.Root); Assert.Same(orphaned, removed.Single); } - }, - context => root = LoadRequiredGraph(context), + }, async context => root = await LoadRequiredGraphAsync(context), context => { if (!Fixture.ForceClientNoAction @@ -2152,6 +2138,8 @@ public virtual void Required_one_to_one_are_cascade_deleted_starting_detached( Assert.False(context.Set().Select(r => r.RequiredSingle).Any(r => r.Single != null)); } + + return Task.CompletedTask; }); } @@ -2166,7 +2154,7 @@ public virtual void Required_one_to_one_are_cascade_deleted_starting_detached( [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] [InlineData(null, null)] - public virtual void Required_non_PK_one_to_one_are_cascade_deleted_starting_detached( + public virtual Task Required_non_PK_one_to_one_are_cascade_deleted_starting_detached( CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) { @@ -2174,9 +2162,8 @@ public virtual void Required_non_PK_one_to_one_are_cascade_deleted_starting_deta var orphanedId = 0; Root root = null; - ExecuteWithStrategyInTransaction( - context => root = LoadRequiredNonPkGraph(context), - context => + return ExecuteWithStrategyInTransactionAsync( + async context => root = await LoadRequiredNonPkGraphAsync(context), async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming ?? CascadeTiming.Never; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; @@ -2209,15 +2196,15 @@ public virtual void Required_non_PK_one_to_one_are_cascade_deleted_starting_deta if (Fixture.ForceClientNoAction) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else if (cascadeDeleteTiming == CascadeTiming.Never) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -2227,13 +2214,12 @@ public virtual void Required_non_PK_one_to_one_are_cascade_deleted_starting_deta Assert.Same(root, removed.Root); Assert.Same(orphaned, removed.Single); } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction && cascadeDeleteTiming != CascadeTiming.Never) { - root = LoadRequiredNonPkGraph(context); + root = await LoadRequiredNonPkGraphAsync(context); Assert.Null(root.RequiredNonPkSingle); @@ -2254,20 +2240,20 @@ public virtual void Required_non_PK_one_to_one_are_cascade_deleted_starting_deta [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] [InlineData(null, null)] - public virtual void Required_one_to_one_are_cascade_detached_when_Added( + public virtual Task Required_one_to_one_are_cascade_detached_when_Added( CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) { var removedId = 0; var orphanedId = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming ?? CascadeTiming.Never; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - var root = LoadRequiredGraph(context); + var root = await LoadRequiredGraphAsync(context); var removed = root.RequiredSingle; @@ -2276,7 +2262,7 @@ public virtual void Required_one_to_one_are_cascade_detached_when_Added( // Since we're pretending this isn't in the database, make it really not in the database context.Entry(orphaned).State = EntityState.Deleted; - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.Equal(EntityState.Detached, context.Entry(orphaned).State); @@ -2309,15 +2295,15 @@ public virtual void Required_one_to_one_are_cascade_detached_when_Added( if (Fixture.ForceClientNoAction) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else if (cascadeDeleteTiming == CascadeTiming.Never) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -2327,13 +2313,12 @@ public virtual void Required_one_to_one_are_cascade_detached_when_Added( Assert.Same(root, removed.Root); Assert.Same(orphaned, removed.Single); } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction && cascadeDeleteTiming != CascadeTiming.Never) { - var root = LoadRequiredGraph(context); + var root = await LoadRequiredGraphAsync(context); Assert.Null(root.RequiredSingle); @@ -2362,20 +2347,20 @@ public virtual void Required_one_to_one_are_cascade_detached_when_Added( [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] [InlineData(null, null)] - public virtual void Required_non_PK_one_to_one_are_cascade_detached_when_Added( + public virtual Task Required_non_PK_one_to_one_are_cascade_detached_when_Added( CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) { var removedId = 0; var orphanedId = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming ?? CascadeTiming.Never; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - var root = LoadRequiredNonPkGraph(context); + var root = await LoadRequiredNonPkGraphAsync(context); var removed = root.RequiredNonPkSingle; @@ -2384,7 +2369,7 @@ public virtual void Required_non_PK_one_to_one_are_cascade_detached_when_Added( // Since we're pretending this isn't in the database, make it really not in the database context.Entry(orphaned).State = EntityState.Deleted; - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.Equal(EntityState.Detached, context.Entry(orphaned).State); @@ -2418,15 +2403,15 @@ public virtual void Required_non_PK_one_to_one_are_cascade_detached_when_Added( if (Fixture.ForceClientNoAction) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else if (cascadeDeleteTiming == CascadeTiming.Never) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -2436,13 +2421,12 @@ public virtual void Required_non_PK_one_to_one_are_cascade_detached_when_Added( Assert.Same(root, removed.Root); Assert.Same(orphaned, removed.Single); } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction && cascadeDeleteTiming != CascadeTiming.Never) { - var root = LoadRequiredNonPkGraph(context); + var root = await LoadRequiredNonPkGraphAsync(context); Assert.Null(root.RequiredNonPkSingle); diff --git a/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBaseOneToOneAk.cs b/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBaseOneToOneAk.cs index 4ae6f138083..d4dcd4159fe 100644 --- a/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBaseOneToOneAk.cs +++ b/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBaseOneToOneAk.cs @@ -17,14 +17,14 @@ public abstract partial class GraphUpdatesTestBase [InlineData(CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never)] [InlineData(null)] - public virtual void Optional_one_to_one_with_AK_relationships_are_one_to_one( + public virtual Task Optional_one_to_one_with_AK_relationships_are_one_to_one( CascadeTiming? deleteOrphansTiming) - => ExecuteWithStrategyInTransaction( - context => + => ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - var root = context.Set().Single(IsTheRoot); + var root = await context.Set().SingleAsync(IsTheRoot); Assert.False(context.ChangeTracker.HasChanges()); @@ -32,7 +32,7 @@ public virtual void Optional_one_to_one_with_AK_relationships_are_one_to_one( Assert.True(context.ChangeTracker.HasChanges()); - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(async () => await context.SaveChangesAsync()); }); [ConditionalTheory] @@ -94,7 +94,7 @@ public virtual void Optional_one_to_one_with_AK_relationships_are_one_to_one( [InlineData((int)(ChangeMechanism.Fk | ChangeMechanism.Dependent), true, null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), false, null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), true, null)] - public virtual void Save_changed_optional_one_to_one_with_alternate_key( + public virtual Task Save_changed_optional_one_to_one_with_alternate_key( ChangeMechanism changeMechanism, bool useExistingEntities, CascadeTiming? deleteOrphansTiming) @@ -121,20 +121,19 @@ public virtual void Save_changed_optional_one_to_one_with_alternate_key( OptionalSingleAk2Derived old2d = null; OptionalSingleAk2MoreDerived old2dd = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { if (useExistingEntities) { context.AddRange(new1, new1d, new1dd, new2, new2d, new2dd, new2c); - context.SaveChanges(); + await context.SaveChangesAsync(); } - }, - context => + }, async context => { context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - root = LoadOptionalAkGraph(context); + root = await LoadOptionalAkGraphAsync(context); old1 = root.OptionalSingleAk; old1d = root.OptionalSingleAkDerived; @@ -146,13 +145,13 @@ public virtual void Save_changed_optional_one_to_one_with_alternate_key( if (useExistingEntities) { - new1 = context.Set().Single(e => e.Id == new1.Id); - new1d = (OptionalSingleAk1Derived)context.Set().Single(e => e.Id == new1d.Id); - new1dd = (OptionalSingleAk1MoreDerived)context.Set().Single(e => e.Id == new1dd.Id); - new2 = context.Set().Single(e => e.Id == new2.Id); - new2c = context.Set().Single(e => e.Id == new2c.Id); - new2d = (OptionalSingleAk2Derived)context.Set().Single(e => e.Id == new2d.Id); - new2dd = (OptionalSingleAk2MoreDerived)context.Set().Single(e => e.Id == new2dd.Id); + new1 = await context.Set().SingleAsync(e => e.Id == new1.Id); + new1d = (OptionalSingleAk1Derived)await context.Set().SingleAsync(e => e.Id == new1d.Id); + new1dd = (OptionalSingleAk1MoreDerived)await context.Set().SingleAsync(e => e.Id == new1dd.Id); + new2 = await context.Set().SingleAsync(e => e.Id == new2.Id); + new2c = await context.Set().SingleAsync(e => e.Id == new2c.Id); + new2d = (OptionalSingleAk2Derived)await context.Set().SingleAsync(e => e.Id == new2d.Id); + new2dd = (OptionalSingleAk2MoreDerived)await context.Set().SingleAsync(e => e.Id == new2dd.Id); } else { @@ -182,7 +181,7 @@ public virtual void Save_changed_optional_one_to_one_with_alternate_key( Assert.True(context.ChangeTracker.HasChanges()); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -219,21 +218,20 @@ public virtual void Save_changed_optional_one_to_one_with_alternate_key( Assert.Equal(old1dd.AlternateId, old2dd.BackId); entries = context.ChangeTracker.Entries().ToList(); - }, - context => + }, async context => { - var loadedRoot = LoadOptionalAkGraph(context); + var loadedRoot = await LoadOptionalAkGraphAsync(context); AssertKeys(root, loadedRoot); AssertNavigations(loadedRoot); - var loaded1 = context.Set().Single(e => e.Id == old1.Id); - var loaded1d = context.Set().Single(e => e.Id == old1d.Id); - var loaded1dd = context.Set().Single(e => e.Id == old1dd.Id); - var loaded2 = context.Set().Single(e => e.Id == old2.Id); - var loaded2d = context.Set().Single(e => e.Id == old2d.Id); - var loaded2dd = context.Set().Single(e => e.Id == old2dd.Id); - var loaded2c = context.Set().Single(e => e.Id == old2c.Id); + var loaded1 = await context.Set().SingleAsync(e => e.Id == old1.Id); + var loaded1d = await context.Set().SingleAsync(e => e.Id == old1d.Id); + var loaded1dd = await context.Set().SingleAsync(e => e.Id == old1dd.Id); + var loaded2 = await context.Set().SingleAsync(e => e.Id == old2.Id); + var loaded2d = await context.Set().SingleAsync(e => e.Id == old2d.Id); + var loaded2dd = await context.Set().SingleAsync(e => e.Id == old2dd.Id); + var loaded2c = await context.Set().SingleAsync(e => e.Id == old2c.Id); AssertEntries(entries, context.ChangeTracker.Entries().ToList()); @@ -256,7 +254,7 @@ public virtual void Save_changed_optional_one_to_one_with_alternate_key( } [ConditionalFact] - public virtual void Save_changed_optional_one_to_one_with_alternate_key_in_store() + public virtual Task Save_changed_optional_one_to_one_with_alternate_key_in_store() { var new2 = new OptionalSingleAk2 { AlternateId = Guid.NewGuid() }; var new2d = new OptionalSingleAk2Derived { AlternateId = Guid.NewGuid() }; @@ -280,10 +278,10 @@ public virtual void Save_changed_optional_one_to_one_with_alternate_key_in_store OptionalSingleAk2Derived old2d = null; OptionalSingleAk2MoreDerived old2dd = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - root = LoadOptionalAkGraph(context); + root = await LoadOptionalAkGraphAsync(context); old1 = root.OptionalSingleAk; old1d = root.OptionalSingleAkDerived; @@ -296,7 +294,7 @@ public virtual void Save_changed_optional_one_to_one_with_alternate_key_in_store using (var context2 = CreateContext()) { UseTransaction(context2.Database, context.Database.CurrentTransaction); - var root2 = LoadOptionalAkGraph(context2); + var root2 = await LoadOptionalAkGraphAsync(context2); context2.AddRange(new1, new1d, new1dd, new2, new2d, new2dd, new2c); root2.OptionalSingleAk = new1; @@ -305,18 +303,18 @@ public virtual void Save_changed_optional_one_to_one_with_alternate_key_in_store Assert.True(context2.ChangeTracker.HasChanges()); - context2.SaveChanges(); + await context2.SaveChangesAsync(); Assert.False(context2.ChangeTracker.HasChanges()); } - new1 = context.Set().Single(e => e.Id == new1.Id); - new1d = (OptionalSingleAk1Derived)context.Set().Single(e => e.Id == new1d.Id); - new1dd = (OptionalSingleAk1MoreDerived)context.Set().Single(e => e.Id == new1dd.Id); - new2 = context.Set().Single(e => e.Id == new2.Id); - new2c = context.Set().Single(e => e.Id == new2c.Id); - new2d = (OptionalSingleAk2Derived)context.Set().Single(e => e.Id == new2d.Id); - new2dd = (OptionalSingleAk2MoreDerived)context.Set().Single(e => e.Id == new2dd.Id); + new1 = await context.Set().SingleAsync(e => e.Id == new1.Id); + new1d = (OptionalSingleAk1Derived)await context.Set().SingleAsync(e => e.Id == new1d.Id); + new1dd = (OptionalSingleAk1MoreDerived)await context.Set().SingleAsync(e => e.Id == new1dd.Id); + new2 = await context.Set().SingleAsync(e => e.Id == new2.Id); + new2c = await context.Set().SingleAsync(e => e.Id == new2c.Id); + new2d = (OptionalSingleAk2Derived)await context.Set().SingleAsync(e => e.Id == new2d.Id); + new2dd = (OptionalSingleAk2MoreDerived)await context.Set().SingleAsync(e => e.Id == new2dd.Id); Assert.Equal(root.AlternateId, new1.RootId); Assert.Equal(root.AlternateId, new1d.DerivedRootId); @@ -352,7 +350,7 @@ public virtual void Save_changed_optional_one_to_one_with_alternate_key_in_store Assert.True(context.ChangeTracker.HasChanges()); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -389,21 +387,20 @@ public virtual void Save_changed_optional_one_to_one_with_alternate_key_in_store Assert.Equal(old1dd.AlternateId, old2dd.BackId); entries = context.ChangeTracker.Entries().ToList(); - }, - context => + }, async context => { - var loadedRoot = LoadOptionalAkGraph(context); + var loadedRoot = await LoadOptionalAkGraphAsync(context); AssertKeys(root, loadedRoot); AssertNavigations(loadedRoot); - var loaded1 = context.Set().Single(e => e.Id == old1.Id); - var loaded1d = context.Set().Single(e => e.Id == old1d.Id); - var loaded1dd = context.Set().Single(e => e.Id == old1dd.Id); - var loaded2 = context.Set().Single(e => e.Id == old2.Id); - var loaded2d = context.Set().Single(e => e.Id == old2d.Id); - var loaded2dd = context.Set().Single(e => e.Id == old2dd.Id); - var loaded2c = context.Set().Single(e => e.Id == old2c.Id); + var loaded1 = await context.Set().SingleAsync(e => e.Id == old1.Id); + var loaded1d = await context.Set().SingleAsync(e => e.Id == old1d.Id); + var loaded1dd = await context.Set().SingleAsync(e => e.Id == old1dd.Id); + var loaded2 = await context.Set().SingleAsync(e => e.Id == old2.Id); + var loaded2d = await context.Set().SingleAsync(e => e.Id == old2d.Id); + var loaded2dd = await context.Set().SingleAsync(e => e.Id == old2dd.Id); + var loaded2c = await context.Set().SingleAsync(e => e.Id == old2c.Id); AssertEntries(entries, context.ChangeTracker.Entries().ToList()); @@ -454,7 +451,7 @@ public virtual void Save_changed_optional_one_to_one_with_alternate_key_in_store [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Fk), null)] [InlineData((int)(ChangeMechanism.Fk | ChangeMechanism.Dependent), null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), null)] - public virtual void Sever_optional_one_to_one_with_alternate_key( + public virtual Task Sever_optional_one_to_one_with_alternate_key( ChangeMechanism changeMechanism, CascadeTiming? deleteOrphansTiming) { @@ -462,12 +459,12 @@ public virtual void Sever_optional_one_to_one_with_alternate_key( OptionalSingleAk1 old1 = null; OptionalSingleAk2 old2 = null; OptionalSingleComposite2 old2c = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - root = LoadOptionalAkGraph(context); + root = await LoadOptionalAkGraphAsync(context); old1 = root.OptionalSingleAk; old2 = root.OptionalSingleAk.Single; @@ -492,7 +489,7 @@ public virtual void Sever_optional_one_to_one_with_alternate_key( Assert.False(context.Entry(old1).Reference(e => e.Root).IsLoaded); Assert.True(context.ChangeTracker.HasChanges()); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -503,19 +500,18 @@ public virtual void Sever_optional_one_to_one_with_alternate_key( Assert.Equal(old1.AlternateId, old2.BackId); Assert.Equal(old1.Id, old2c.BackId); Assert.Equal(old1.AlternateId, old2c.ParentAlternateId); - }, - context => + }, async context => { if ((changeMechanism & ChangeMechanism.Fk) == 0) { - var loadedRoot = LoadOptionalAkGraph(context); + var loadedRoot = await LoadOptionalAkGraphAsync(context); AssertKeys(root, loadedRoot); AssertPossiblyNullNavigations(loadedRoot); - var loaded1 = context.Set().Single(e => e.Id == old1.Id); - var loaded2 = context.Set().Single(e => e.Id == old2.Id); - var loaded2c = context.Set().Single(e => e.Id == old2c.Id); + var loaded1 = await context.Set().SingleAsync(e => e.Id == old1.Id); + var loaded2 = await context.Set().SingleAsync(e => e.Id == old2.Id); + var loaded2c = await context.Set().SingleAsync(e => e.Id == old2c.Id); Assert.Null(loaded1.Root); Assert.Same(loaded1, loaded2.Back); @@ -587,7 +583,7 @@ public virtual void Sever_optional_one_to_one_with_alternate_key( [InlineData((int)(ChangeMechanism.Fk | ChangeMechanism.Dependent), true, null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), false, null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), true, null)] - public virtual void Reparent_optional_one_to_one_with_alternate_key( + public virtual Task Reparent_optional_one_to_one_with_alternate_key( ChangeMechanism changeMechanism, bool useExistingRoot, CascadeTiming? deleteOrphansTiming) @@ -598,20 +594,19 @@ public virtual void Reparent_optional_one_to_one_with_alternate_key( OptionalSingleAk2 old2 = null; OptionalSingleComposite2 old2c = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { if (useExistingRoot) { context.Add(newRoot); - context.SaveChanges(); + await context.SaveChangesAsync(); } - }, - context => + }, async context => { context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - root = LoadOptionalAkGraph(context); + root = await LoadOptionalAkGraphAsync(context); context.Entry(newRoot).State = useExistingRoot ? EntityState.Unchanged : EntityState.Added; @@ -636,7 +631,7 @@ public virtual void Reparent_optional_one_to_one_with_alternate_key( Assert.True(context.ChangeTracker.HasChanges()); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -649,18 +644,17 @@ public virtual void Reparent_optional_one_to_one_with_alternate_key( Assert.Equal(old1.AlternateId, old2.BackId); Assert.Equal(old1.Id, old2c.BackId); Assert.Equal(old1.AlternateId, old2c.ParentAlternateId); - }, - context => + }, async context => { - var loadedRoot = LoadOptionalAkGraph(context); + var loadedRoot = await LoadOptionalAkGraphAsync(context); AssertKeys(root, loadedRoot); AssertPossiblyNullNavigations(loadedRoot); - newRoot = context.Set().Single(e => e.Id == newRoot.Id); - var loaded1 = context.Set().Single(e => e.Id == old1.Id); - var loaded2 = context.Set().Single(e => e.Id == old2.Id); - var loaded2c = context.Set().Single(e => e.Id == old2c.Id); + newRoot = await context.Set().SingleAsync(e => e.Id == newRoot.Id); + var loaded1 = await context.Set().SingleAsync(e => e.Id == old1.Id); + var loaded2 = await context.Set().SingleAsync(e => e.Id == old2.Id); + var loaded2c = await context.Set().SingleAsync(e => e.Id == old2c.Id); Assert.Same(newRoot, loaded1.Root); Assert.Same(loaded1, loaded2.Back); @@ -683,7 +677,7 @@ public virtual void Reparent_optional_one_to_one_with_alternate_key( [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] [InlineData(null, null)] - public virtual void Optional_one_to_one_with_alternate_key_are_orphaned( + public virtual Task Optional_one_to_one_with_alternate_key_are_orphaned( CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) { @@ -691,13 +685,13 @@ public virtual void Optional_one_to_one_with_alternate_key_are_orphaned( var orphanedId = 0; var orphanedIdC = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming ?? CascadeTiming.Never; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - var root = LoadOptionalAkGraph(context); + var root = await LoadOptionalAkGraphAsync(context); var removed = root.OptionalSingleAk; @@ -732,11 +726,11 @@ public virtual void Optional_one_to_one_with_alternate_key_are_orphaned( if (Fixture.ForceClientNoAction) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -753,12 +747,11 @@ public virtual void Optional_one_to_one_with_alternate_key_are_orphaned( Assert.Same(root, removed.Root); Assert.Same(orphaned, removed.Single); } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction) { - var root = LoadOptionalAkGraph(context); + var root = await LoadOptionalAkGraphAsync(context); Assert.Null(root.OptionalSingleAk); @@ -780,7 +773,7 @@ public virtual void Optional_one_to_one_with_alternate_key_are_orphaned( [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] [InlineData(null, null)] - public virtual void Optional_one_to_one_with_alternate_key_are_orphaned_in_store( + public virtual Task Optional_one_to_one_with_alternate_key_are_orphaned_in_store( CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) { @@ -788,21 +781,20 @@ public virtual void Optional_one_to_one_with_alternate_key_are_orphaned_in_store var orphanedId = 0; var orphanedIdC = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var removed = LoadOptionalAkGraph(context).OptionalSingleAk; + var removed = (await LoadOptionalAkGraphAsync(context)).OptionalSingleAk; removedId = removed.Id; orphanedId = removed.Single.Id; orphanedIdC = removed.SingleComposite.Id; - }, - context => + }, async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming ?? CascadeTiming.Never; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - var root = context.Set().Include(e => e.OptionalSingleAk).Single(IsTheRoot); + var root = await context.Set().Include(e => e.OptionalSingleAk).SingleAsync(IsTheRoot); var removed = root.OptionalSingleAk; var orphaned = removed.Single; @@ -811,7 +803,7 @@ public virtual void Optional_one_to_one_with_alternate_key_are_orphaned_in_store // Cannot have SET NULL action in the store because one of the FK columns // is not nullable, so need to do this on the EF side. - context.Set().Single(e => e.Id == orphanedIdC).BackId = null; + (await context.Set().SingleAsync(e => e.Id == orphanedIdC)).BackId = null; Assert.True(context.ChangeTracker.HasChanges()); @@ -822,11 +814,11 @@ public virtual void Optional_one_to_one_with_alternate_key_are_orphaned_in_store if (Fixture.ForceClientNoAction) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -834,25 +826,24 @@ public virtual void Optional_one_to_one_with_alternate_key_are_orphaned_in_store Assert.Null(root.OptionalSingleAk); - Assert.Empty(context.Set().Where(e => e.Id == removedId)); - Assert.Null(context.Set().Single(e => e.Id == orphanedId).BackId); - Assert.Null(context.Set().Single(e => e.Id == orphanedIdC).BackId); + Assert.Empty(await context.Set().Where(e => e.Id == removedId).ToListAsync()); + Assert.Null((await context.Set().SingleAsync(e => e.Id == orphanedId)).BackId); + Assert.Null((await context.Set().SingleAsync(e => e.Id == orphanedIdC)).BackId); Assert.Same(root, removed.Root); Assert.Same(orphaned, removed.Single); } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction) { - var root = LoadOptionalAkGraph(context); + var root = await LoadOptionalAkGraphAsync(context); Assert.Null(root.OptionalSingleAk); - Assert.Empty(context.Set().Where(e => e.Id == removedId)); - Assert.Null(context.Set().Single(e => e.Id == orphanedId).BackId); - Assert.Null(context.Set().Single(e => e.Id == orphanedIdC).BackId); + Assert.Empty(await context.Set().Where(e => e.Id == removedId).ToListAsync()); + Assert.Null((await context.Set().SingleAsync(e => e.Id == orphanedId)).BackId); + Assert.Null((await context.Set().SingleAsync(e => e.Id == orphanedIdC)).BackId); } }); } @@ -868,7 +859,7 @@ public virtual void Optional_one_to_one_with_alternate_key_are_orphaned_in_store [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] [InlineData(null, null)] - public virtual void Optional_one_to_one_with_alternate_key_are_orphaned_starting_detached( + public virtual Task Optional_one_to_one_with_alternate_key_are_orphaned_starting_detached( CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) { @@ -877,9 +868,8 @@ public virtual void Optional_one_to_one_with_alternate_key_are_orphaned_starting var orphanedIdC = 0; Root root = null; - ExecuteWithStrategyInTransaction( - context => root = LoadOptionalAkGraph(context), - context => + return ExecuteWithStrategyInTransactionAsync( + async context => root = await LoadOptionalAkGraphAsync(context), async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming ?? CascadeTiming.Never; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; @@ -916,11 +906,11 @@ public virtual void Optional_one_to_one_with_alternate_key_are_orphaned_starting if (Fixture.ForceClientNoAction) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(async () => await context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -931,12 +921,11 @@ public virtual void Optional_one_to_one_with_alternate_key_are_orphaned_starting Assert.Same(root, removed.Root); Assert.Same(orphaned, removed.Single); } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction) { - root = LoadOptionalAkGraph(context); + root = await LoadOptionalAkGraphAsync(context); Assert.Null(root.OptionalSingleAk); @@ -952,14 +941,14 @@ public virtual void Optional_one_to_one_with_alternate_key_are_orphaned_starting [InlineData(CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never)] [InlineData(null)] - public virtual void Required_one_to_one_with_AK_relationships_are_one_to_one( + public virtual Task Required_one_to_one_with_AK_relationships_are_one_to_one( CascadeTiming? deleteOrphansTiming) - => ExecuteWithStrategyInTransaction( - context => + => ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - var root = context.Set().Single(IsTheRoot); + var root = await context.Set().SingleAsync(IsTheRoot); Assert.False(context.ChangeTracker.HasChanges()); @@ -967,7 +956,7 @@ public virtual void Required_one_to_one_with_AK_relationships_are_one_to_one( Assert.True(context.ChangeTracker.HasChanges()); - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); }); [ConditionalTheory] @@ -995,7 +984,7 @@ public virtual void Required_one_to_one_with_AK_relationships_are_one_to_one( [InlineData((int)ChangeMechanism.Dependent, true, null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent), false, null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent), true, null)] - public virtual void Save_required_one_to_one_changed_by_reference_with_alternate_key( + public virtual Task Save_required_one_to_one_changed_by_reference_with_alternate_key( ChangeMechanism changeMechanism, bool useExistingEntities, CascadeTiming? deleteOrphansTiming) @@ -1015,20 +1004,19 @@ public virtual void Save_required_one_to_one_changed_by_reference_with_alternate RequiredSingleAk2 old2 = null; RequiredSingleComposite2 old2c = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { if (useExistingEntities) { context.AddRange(newRoot, new1, new2, new2c); - context.SaveChanges(); + await context.SaveChangesAsync(); } - }, - context => + }, async context => { context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - root = LoadRequiredAkGraph(context); + root = await LoadRequiredAkGraphAsync(context); old1 = root.RequiredSingleAk; old2 = root.RequiredSingleAk.Single; @@ -1036,11 +1024,11 @@ public virtual void Save_required_one_to_one_changed_by_reference_with_alternate if (useExistingEntities) { - newRoot = context.Set() + newRoot = await context.Set() .Include(e => e.RequiredSingleAk).ThenInclude(e => e.Single) .Include(e => e.RequiredSingleAk).ThenInclude(e => e.SingleComposite) .OrderBy(e => e.Id) - .Single(e => e.Id == newRoot.Id); + .SingleAsync(e => e.Id == newRoot.Id); new1 = newRoot.RequiredSingleAk; new2 = new1.Single; @@ -1070,12 +1058,20 @@ public virtual void Save_required_one_to_one_changed_by_reference_with_alternate || deleteOrphansTiming == CascadeTiming.Never) { var testCode = deleteOrphansTiming == CascadeTiming.Immediate - ? () => context.ChangeTracker.DetectChanges() + ? () => + { + context.ChangeTracker.DetectChanges(); + return Task.CompletedTask; + } : deleteOrphansTiming == null - ? () => context.ChangeTracker.CascadeChanges() - : (Action)(() => context.SaveChanges()); + ? () => + { + context.ChangeTracker.CascadeChanges(); + return Task.CompletedTask; + } + : (Func)(() => context.SaveChangesAsync()); - var message = Assert.Throws(testCode).Message; + var message = (await Assert.ThrowsAsync(testCode)).Message; Assert.Equal( message, @@ -1091,7 +1087,7 @@ public virtual void Save_required_one_to_one_changed_by_reference_with_alternate context.ChangeTracker.CascadeChanges(); } - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -1124,14 +1120,13 @@ public virtual void Save_required_one_to_one_changed_by_reference_with_alternate context.Entry(newRoot).State = EntityState.Detached; entries = context.ChangeTracker.Entries().ToList(); } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction && !Fixture.NoStoreCascades && deleteOrphansTiming != CascadeTiming.Never) { - var loadedRoot = LoadRequiredAkGraph(context); + var loadedRoot = await LoadRequiredAkGraphAsync(context); AssertEntries(entries, context.ChangeTracker.Entries().ToList()); AssertKeys(root, loadedRoot); @@ -1220,7 +1215,7 @@ public virtual void Save_required_one_to_one_changed_by_reference_with_alternate [InlineData((int)(ChangeMechanism.Fk | ChangeMechanism.Dependent), true, null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), false, null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), true, null)] - public virtual void Save_required_non_PK_one_to_one_changed_by_reference_with_alternate_key( + public virtual Task Save_required_non_PK_one_to_one_changed_by_reference_with_alternate_key( ChangeMechanism changeMechanism, bool useExistingEntities, CascadeTiming? deleteOrphansTiming) @@ -1258,20 +1253,19 @@ public virtual void Save_required_non_PK_one_to_one_changed_by_reference_with_al RequiredNonPkSingleAk2Derived old2d = null; RequiredNonPkSingleAk2MoreDerived old2dd = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { if (useExistingEntities) { context.AddRange(newRoot, new1, new1d, new1dd, new2, new2d, new2dd); - context.SaveChanges(); + await context.SaveChangesAsync(); } - }, - context => + }, async context => { context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - root = LoadRequiredNonPkAkGraph(context); + root = await LoadRequiredNonPkAkGraphAsync(context); old1 = root.RequiredNonPkSingleAk; old1d = root.RequiredNonPkSingleAkDerived; @@ -1285,14 +1279,14 @@ public virtual void Save_required_non_PK_one_to_one_changed_by_reference_with_al if (useExistingEntities) { - new1 = context.Set().Single(e => e.Id == new1.Id); - new1d = (RequiredNonPkSingleAk1Derived)context.Set().Single(e => e.Id == new1d.Id); - new1dd = (RequiredNonPkSingleAk1MoreDerived)context.Set() - .Single(e => e.Id == new1dd.Id); - new2 = context.Set().Single(e => e.Id == new2.Id); - new2d = (RequiredNonPkSingleAk2Derived)context.Set().Single(e => e.Id == new2d.Id); - new2dd = (RequiredNonPkSingleAk2MoreDerived)context.Set() - .Single(e => e.Id == new2dd.Id); + new1 = await context.Set().SingleAsync(e => e.Id == new1.Id); + new1d = (RequiredNonPkSingleAk1Derived)await context.Set().SingleAsync(e => e.Id == new1d.Id); + new1dd = (RequiredNonPkSingleAk1MoreDerived)await context.Set() + .SingleAsync(e => e.Id == new1dd.Id); + new2 = await context.Set().SingleAsync(e => e.Id == new2.Id); + new2d = (RequiredNonPkSingleAk2Derived)await context.Set().SingleAsync(e => e.Id == new2d.Id); + new2dd = (RequiredNonPkSingleAk2MoreDerived)await context.Set() + .SingleAsync(e => e.Id == new2dd.Id); new1d.RootId = old1d.RootId; new1dd.RootId = old1dd.RootId; @@ -1331,12 +1325,20 @@ public virtual void Save_required_non_PK_one_to_one_changed_by_reference_with_al || deleteOrphansTiming == CascadeTiming.Never) { var testCode = deleteOrphansTiming == CascadeTiming.Immediate - ? () => context.ChangeTracker.DetectChanges() + ? () => + { + context.ChangeTracker.DetectChanges(); + return Task.CompletedTask; + } : deleteOrphansTiming == null - ? () => context.ChangeTracker.CascadeChanges() - : (Action)(() => context.SaveChanges()); + ? () => + { + context.ChangeTracker.CascadeChanges(); + return Task.CompletedTask; + } + : (Func)(() => context.SaveChangesAsync()); - var message = Assert.Throws(testCode).Message; + var message = (await Assert.ThrowsAsync(testCode)).Message; Assert.Equal( message, @@ -1352,7 +1354,7 @@ public virtual void Save_required_non_PK_one_to_one_changed_by_reference_with_al context.ChangeTracker.CascadeChanges(); } - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -1381,14 +1383,13 @@ public virtual void Save_required_non_PK_one_to_one_changed_by_reference_with_al entries = context.ChangeTracker.Entries().ToList(); } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction && !Fixture.NoStoreCascades && deleteOrphansTiming != CascadeTiming.Never) { - var loadedRoot = LoadRequiredNonPkAkGraph(context); + var loadedRoot = await LoadRequiredNonPkAkGraphAsync(context); AssertEntries(entries, context.ChangeTracker.Entries().ToList()); AssertKeys(root, loadedRoot); @@ -1417,7 +1418,7 @@ public virtual void Save_required_non_PK_one_to_one_changed_by_reference_with_al [InlineData((int)ChangeMechanism.Principal, null)] [InlineData((int)ChangeMechanism.Dependent, null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent), null)] - public virtual void Sever_required_one_to_one_with_alternate_key( + public virtual Task Sever_required_one_to_one_with_alternate_key( ChangeMechanism changeMechanism, CascadeTiming? deleteOrphansTiming) { @@ -1425,12 +1426,12 @@ public virtual void Sever_required_one_to_one_with_alternate_key( RequiredSingleAk1 old1 = null; RequiredSingleAk2 old2 = null; RequiredSingleComposite2 old2c = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - root = LoadRequiredAkGraph(context); + root = await LoadRequiredAkGraphAsync(context); old1 = root.RequiredSingleAk; old2 = root.RequiredSingleAk.Single; @@ -1455,12 +1456,20 @@ public virtual void Sever_required_one_to_one_with_alternate_key( || deleteOrphansTiming == CascadeTiming.Never) { var testCode = deleteOrphansTiming == CascadeTiming.Immediate - ? () => context.ChangeTracker.DetectChanges() + ? () => + { + context.ChangeTracker.DetectChanges(); + return Task.CompletedTask; + } : deleteOrphansTiming == null - ? () => context.ChangeTracker.CascadeChanges() - : (Action)(() => context.SaveChanges()); + ? () => + { + context.ChangeTracker.CascadeChanges(); + return Task.CompletedTask; + } + : (Func)(() => context.SaveChangesAsync()); - var message = Assert.Throws(testCode).Message; + var message = (await Assert.ThrowsAsync(testCode)).Message; Assert.Equal( message, @@ -1478,7 +1487,7 @@ public virtual void Sever_required_one_to_one_with_alternate_key( context.ChangeTracker.CascadeChanges(); } - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -1494,14 +1503,13 @@ public virtual void Sever_required_one_to_one_with_alternate_key( Assert.Equal(old1.Id, old2c.BackId); Assert.Equal(old1.AlternateId, old2c.BackAlternateId); } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction && !Fixture.NoStoreCascades && deleteOrphansTiming != CascadeTiming.Never) { - var loadedRoot = LoadRequiredAkGraph(context); + var loadedRoot = await LoadRequiredAkGraphAsync(context); AssertKeys(root, loadedRoot); AssertPossiblyNullNavigations(loadedRoot); @@ -1543,19 +1551,19 @@ public virtual void Sever_required_one_to_one_with_alternate_key( [InlineData((int)ChangeMechanism.Principal, null)] [InlineData((int)ChangeMechanism.Dependent, null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent), null)] - public virtual void Sever_required_non_PK_one_to_one_with_alternate_key( + public virtual Task Sever_required_non_PK_one_to_one_with_alternate_key( ChangeMechanism changeMechanism, CascadeTiming? deleteOrphansTiming) { Root root = null; RequiredNonPkSingleAk1 old1 = null; RequiredNonPkSingleAk2 old2 = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - root = LoadRequiredNonPkAkGraph(context); + root = await LoadRequiredNonPkAkGraphAsync(context); old1 = root.RequiredNonPkSingleAk; old2 = root.RequiredNonPkSingleAk.Single; @@ -1579,12 +1587,20 @@ public virtual void Sever_required_non_PK_one_to_one_with_alternate_key( || deleteOrphansTiming == CascadeTiming.Never) { var testCode = deleteOrphansTiming == CascadeTiming.Immediate - ? () => context.ChangeTracker.DetectChanges() + ? () => + { + context.ChangeTracker.DetectChanges(); + return Task.CompletedTask; + } : deleteOrphansTiming == null - ? () => context.ChangeTracker.CascadeChanges() - : (Action)(() => context.SaveChanges()); + ? () => + { + context.ChangeTracker.CascadeChanges(); + return Task.CompletedTask; + } + : (Func)(() => context.SaveChangesAsync()); - var message = Assert.Throws(testCode).Message; + var message = (await Assert.ThrowsAsync(testCode)).Message; Assert.Equal( message, @@ -1604,7 +1620,7 @@ public virtual void Sever_required_non_PK_one_to_one_with_alternate_key( context.ChangeTracker.CascadeChanges(); } - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -1612,14 +1628,13 @@ public virtual void Sever_required_non_PK_one_to_one_with_alternate_key( Assert.Null(old2.Back); Assert.Equal(old1.AlternateId, old2.BackId); } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction && !Fixture.NoStoreCascades && deleteOrphansTiming != CascadeTiming.Never) { - var loadedRoot = LoadRequiredNonPkAkGraph(context); + var loadedRoot = await LoadRequiredNonPkAkGraphAsync(context); AssertKeys(root, loadedRoot); AssertPossiblyNullNavigations(loadedRoot); @@ -1689,7 +1704,7 @@ public virtual void Sever_required_non_PK_one_to_one_with_alternate_key( [InlineData((int)(ChangeMechanism.Fk | ChangeMechanism.Dependent), true, null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), false, null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), true, null)] - public virtual void Reparent_required_one_to_one_with_alternate_key( + public virtual Task Reparent_required_one_to_one_with_alternate_key( ChangeMechanism changeMechanism, bool useExistingRoot, CascadeTiming? deleteOrphansTiming) @@ -1700,20 +1715,19 @@ public virtual void Reparent_required_one_to_one_with_alternate_key( RequiredSingleAk2 old2 = null; RequiredSingleComposite2 old2c = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { if (useExistingRoot) { context.Add(newRoot); - context.SaveChanges(); + await context.SaveChangesAsync(); } - }, - context => + }, async context => { context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - root = LoadRequiredAkGraph(context); + root = await LoadRequiredAkGraphAsync(context); context.Entry(newRoot).State = useExistingRoot ? EntityState.Unchanged : EntityState.Added; @@ -1738,7 +1752,7 @@ public virtual void Reparent_required_one_to_one_with_alternate_key( Assert.True(context.ChangeTracker.HasChanges()); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -1751,18 +1765,17 @@ public virtual void Reparent_required_one_to_one_with_alternate_key( Assert.Equal(old1.AlternateId, old2.BackId); Assert.Equal(old1.Id, old2c.BackId); Assert.Equal(old1.AlternateId, old2c.BackAlternateId); - }, - context => + }, async context => { - var loadedRoot = LoadRequiredAkGraph(context); + var loadedRoot = await LoadRequiredAkGraphAsync(context); AssertKeys(root, loadedRoot); AssertPossiblyNullNavigations(loadedRoot); - newRoot = context.Set() + newRoot = await context.Set() .Include(r => r.RequiredSingleAk.Single) .Include(r => r.RequiredSingleAk.SingleComposite) - .Single(e => e.Id == newRoot.Id); + .SingleAsync(e => e.Id == newRoot.Id); var loaded1 = newRoot.RequiredSingleAk; var loaded2 = loaded1.Single; @@ -1841,7 +1854,7 @@ public virtual void Reparent_required_one_to_one_with_alternate_key( [InlineData((int)(ChangeMechanism.Fk | ChangeMechanism.Dependent), true, null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), false, null)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), true, null)] - public virtual void Reparent_required_non_PK_one_to_one_with_alternate_key( + public virtual Task Reparent_required_non_PK_one_to_one_with_alternate_key( ChangeMechanism changeMechanism, bool useExistingRoot, CascadeTiming? deleteOrphansTiming) @@ -1851,20 +1864,19 @@ public virtual void Reparent_required_non_PK_one_to_one_with_alternate_key( RequiredNonPkSingleAk1 old1 = null; RequiredNonPkSingleAk2 old2 = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { if (useExistingRoot) { context.Add(newRoot); - context.SaveChanges(); + await context.SaveChangesAsync(); } - }, - context => + }, async context => { context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - root = LoadRequiredNonPkAkGraph(context); + root = await LoadRequiredNonPkAkGraphAsync(context); context.Entry(newRoot).State = useExistingRoot ? EntityState.Unchanged : EntityState.Added; @@ -1888,7 +1900,7 @@ public virtual void Reparent_required_non_PK_one_to_one_with_alternate_key( Assert.True(context.ChangeTracker.HasChanges()); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -1898,17 +1910,16 @@ public virtual void Reparent_required_non_PK_one_to_one_with_alternate_key( Assert.Same(old1, old2.Back); Assert.Equal(newRoot.AlternateId, old1.RootId); Assert.Equal(old1.AlternateId, old2.BackId); - }, - context => + }, async context => { - var loadedRoot = LoadRequiredNonPkAkGraph(context); + var loadedRoot = await LoadRequiredNonPkAkGraphAsync(context); AssertKeys(root, loadedRoot); AssertPossiblyNullNavigations(loadedRoot); - newRoot = context.Set().Single(e => e.Id == newRoot.Id); - var loaded1 = context.Set().Single(e => e.Id == old1.Id); - var loaded2 = context.Set().Single(e => e.Id == old2.Id); + newRoot = await context.Set().SingleAsync(e => e.Id == newRoot.Id); + var loaded1 = await context.Set().SingleAsync(e => e.Id == old1.Id); + var loaded2 = await context.Set().SingleAsync(e => e.Id == old2.Id); Assert.Same(newRoot, loaded1.Root); Assert.Same(loaded1, loaded2.Back); @@ -1928,7 +1939,7 @@ public virtual void Reparent_required_non_PK_one_to_one_with_alternate_key( [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] [InlineData(null, null)] - public virtual void Required_one_to_one_with_alternate_key_are_cascade_deleted( + public virtual Task Required_one_to_one_with_alternate_key_are_cascade_deleted( CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) { @@ -1936,13 +1947,13 @@ public virtual void Required_one_to_one_with_alternate_key_are_cascade_deleted( var orphanedId = 0; var orphanedIdC = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming ?? CascadeTiming.Never; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - var root = LoadRequiredAkGraph(context); + var root = await LoadRequiredAkGraphAsync(context); var removed = root.RequiredSingleAk; @@ -1977,15 +1988,15 @@ public virtual void Required_one_to_one_with_alternate_key_are_cascade_deleted( if (Fixture.ForceClientNoAction) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else if (cascadeDeleteTiming == CascadeTiming.Never) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -1998,13 +2009,12 @@ public virtual void Required_one_to_one_with_alternate_key_are_cascade_deleted( Assert.Same(root, removed.Root); Assert.Same(orphaned, removed.Single); } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction && cascadeDeleteTiming != CascadeTiming.Never) { - var root = LoadRequiredAkGraph(context); + var root = await LoadRequiredAkGraphAsync(context); Assert.Null(root.RequiredSingleAk); @@ -2039,20 +2049,20 @@ public virtual void Required_one_to_one_with_alternate_key_are_cascade_deleted( [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] [InlineData(null, null)] - public virtual void Required_non_PK_one_to_one_with_alternate_key_are_cascade_deleted( + public virtual Task Required_non_PK_one_to_one_with_alternate_key_are_cascade_deleted( CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) { var removedId = 0; var orphanedId = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming ?? CascadeTiming.Never; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - var root = LoadRequiredNonPkAkGraph(context); + var root = await LoadRequiredNonPkAkGraphAsync(context); var removed = root.RequiredNonPkSingleAk; @@ -2076,15 +2086,15 @@ public virtual void Required_non_PK_one_to_one_with_alternate_key_are_cascade_de if (Fixture.ForceClientNoAction) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else if (cascadeDeleteTiming == CascadeTiming.Never) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -2099,13 +2109,12 @@ public virtual void Required_non_PK_one_to_one_with_alternate_key_are_cascade_de Assert.Same(root, removed.Root); Assert.Same(orphaned, removed.Single); } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction && cascadeDeleteTiming != CascadeTiming.Never) { - var root = LoadRequiredNonPkAkGraph(context); + var root = await LoadRequiredNonPkAkGraphAsync(context); Assert.Null(root.RequiredNonPkSingleAk); @@ -2126,7 +2135,7 @@ public virtual void Required_non_PK_one_to_one_with_alternate_key_are_cascade_de [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] [InlineData(null, null)] - public virtual void Required_one_to_one_with_alternate_key_are_cascade_deleted_in_store( + public virtual Task Required_one_to_one_with_alternate_key_are_cascade_deleted_in_store( CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) { @@ -2134,21 +2143,20 @@ public virtual void Required_one_to_one_with_alternate_key_are_cascade_deleted_i var orphanedId = 0; var orphanedIdC = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var removed = LoadRequiredAkGraph(context).RequiredSingleAk; + var removed = (await LoadRequiredAkGraphAsync(context)).RequiredSingleAk; removedId = removed.Id; orphanedId = removed.Single.Id; orphanedIdC = removed.SingleComposite.Id; - }, - context => + }, async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming ?? CascadeTiming.Never; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - var root = context.Set().Include(e => e.RequiredSingleAk).Single(IsTheRoot); + var root = await context.Set().Include(e => e.RequiredSingleAk).SingleAsync(IsTheRoot); var removed = root.RequiredSingleAk; var orphaned = removed.Single; @@ -2165,11 +2173,11 @@ public virtual void Required_one_to_one_with_alternate_key_are_cascade_deleted_i if (Fixture.ForceClientNoAction || Fixture.NoStoreCascades) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -2180,13 +2188,12 @@ public virtual void Required_one_to_one_with_alternate_key_are_cascade_deleted_i Assert.Same(root, removed.Root); Assert.Same(orphaned, removed.Single); } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction && !Fixture.NoStoreCascades) { - var root = LoadRequiredAkGraph(context); + var root = await LoadRequiredAkGraphAsync(context); Assert.Null(root.RequiredSingleAk); @@ -2208,27 +2215,26 @@ public virtual void Required_one_to_one_with_alternate_key_are_cascade_deleted_i [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] [InlineData(null, null)] - public virtual void Required_non_PK_one_to_one_with_alternate_key_are_cascade_deleted_in_store( + public virtual Task Required_non_PK_one_to_one_with_alternate_key_are_cascade_deleted_in_store( CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) { var removedId = 0; var orphanedId = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var removed = LoadRequiredNonPkAkGraph(context).RequiredNonPkSingleAk; + var removed = (await LoadRequiredNonPkAkGraphAsync(context)).RequiredNonPkSingleAk; removedId = removed.Id; orphanedId = removed.Single.Id; - }, - context => + }, async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming ?? CascadeTiming.Never; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - var root = context.Set().Include(e => e.RequiredNonPkSingleAk).Single(IsTheRoot); + var root = await context.Set().Include(e => e.RequiredNonPkSingleAk).SingleAsync(IsTheRoot); var removed = root.RequiredNonPkSingleAk; var orphaned = removed.Single; @@ -2245,11 +2251,11 @@ public virtual void Required_non_PK_one_to_one_with_alternate_key_are_cascade_de if (Fixture.ForceClientNoAction || Fixture.NoStoreCascades) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -2263,13 +2269,12 @@ public virtual void Required_non_PK_one_to_one_with_alternate_key_are_cascade_de Assert.Same(root, removed.Root); Assert.Same(orphaned, removed.Single); } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction && !Fixture.NoStoreCascades) { - var root = LoadRequiredNonPkAkGraph(context); + var root = await LoadRequiredNonPkAkGraphAsync(context); Assert.Null(root.RequiredNonPkSingleAk); @@ -2290,7 +2295,7 @@ public virtual void Required_non_PK_one_to_one_with_alternate_key_are_cascade_de [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] [InlineData(null, null)] - public virtual void Required_one_to_one_with_alternate_key_are_cascade_deleted_starting_detached( + public virtual Task Required_one_to_one_with_alternate_key_are_cascade_deleted_starting_detached( CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) { @@ -2299,9 +2304,8 @@ public virtual void Required_one_to_one_with_alternate_key_are_cascade_deleted_s var orphanedIdC = 0; Root root = null; - ExecuteWithStrategyInTransaction( - context => root = LoadRequiredAkGraph(context), - context => + return ExecuteWithStrategyInTransactionAsync( + async context => root = await LoadRequiredAkGraphAsync(context), async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming ?? CascadeTiming.Never; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; @@ -2338,15 +2342,15 @@ public virtual void Required_one_to_one_with_alternate_key_are_cascade_deleted_s if (Fixture.ForceClientNoAction) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else if (cascadeDeleteTiming == CascadeTiming.Never) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -2357,13 +2361,12 @@ public virtual void Required_one_to_one_with_alternate_key_are_cascade_deleted_s Assert.Same(root, removed.Root); Assert.Same(orphaned, removed.Single); } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction && cascadeDeleteTiming != CascadeTiming.Never) { - root = LoadRequiredAkGraph(context); + root = await LoadRequiredAkGraphAsync(context); Assert.Null(root.RequiredSingleAk); @@ -2398,7 +2401,7 @@ public virtual void Required_one_to_one_with_alternate_key_are_cascade_deleted_s [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] [InlineData(null, null)] - public virtual void Required_non_PK_one_to_one_with_alternate_key_are_cascade_deleted_starting_detached( + public virtual Task Required_non_PK_one_to_one_with_alternate_key_are_cascade_deleted_starting_detached( CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) { @@ -2406,9 +2409,8 @@ public virtual void Required_non_PK_one_to_one_with_alternate_key_are_cascade_de var orphanedId = 0; Root root = null; - ExecuteWithStrategyInTransaction( - context => root = LoadRequiredNonPkAkGraph(context), - context => + return ExecuteWithStrategyInTransactionAsync( + async context => root = await LoadRequiredNonPkAkGraphAsync(context), async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming ?? CascadeTiming.Never; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; @@ -2441,15 +2443,15 @@ public virtual void Required_non_PK_one_to_one_with_alternate_key_are_cascade_de if (Fixture.ForceClientNoAction) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else if (cascadeDeleteTiming == CascadeTiming.Never) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -2459,13 +2461,12 @@ public virtual void Required_non_PK_one_to_one_with_alternate_key_are_cascade_de Assert.Same(root, removed.Root); Assert.Same(orphaned, removed.Single); } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction && cascadeDeleteTiming != CascadeTiming.Never) { - root = LoadRequiredNonPkAkGraph(context); + root = await LoadRequiredNonPkAkGraphAsync(context); Assert.Null(root.RequiredNonPkSingleAk); @@ -2486,7 +2487,7 @@ public virtual void Required_non_PK_one_to_one_with_alternate_key_are_cascade_de [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] [InlineData(null, null)] - public virtual void Required_one_to_one_with_alternate_key_are_cascade_detached_when_Added( + public virtual Task Required_one_to_one_with_alternate_key_are_cascade_detached_when_Added( CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) { @@ -2494,13 +2495,13 @@ public virtual void Required_one_to_one_with_alternate_key_are_cascade_detached_ var orphanedId = 0; var orphanedIdC = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming ?? CascadeTiming.Never; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - var root = LoadRequiredAkGraph(context); + var root = await LoadRequiredAkGraphAsync(context); var removed = root.RequiredSingleAk; removedId = removed.Id; @@ -2511,7 +2512,7 @@ public virtual void Required_one_to_one_with_alternate_key_are_cascade_detached_ // Since we're pretending these aren't in the database, make them really not in the database context.Entry(orphaned).State = EntityState.Deleted; context.Entry(orphanedC).State = EntityState.Deleted; - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.Equal(EntityState.Detached, context.Entry(orphaned).State); Assert.Equal(EntityState.Detached, context.Entry(orphanedC).State); @@ -2552,15 +2553,15 @@ public virtual void Required_one_to_one_with_alternate_key_are_cascade_detached_ if (Fixture.ForceClientNoAction) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else if (cascadeDeleteTiming == CascadeTiming.Never) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -2571,13 +2572,12 @@ public virtual void Required_one_to_one_with_alternate_key_are_cascade_detached_ Assert.Same(root, removed.Root); Assert.Same(orphaned, removed.Single); } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction && cascadeDeleteTiming != CascadeTiming.Never) { - var root = LoadRequiredAkGraph(context); + var root = await LoadRequiredAkGraphAsync(context); Assert.Null(root.RequiredSingleAk); @@ -2612,20 +2612,20 @@ public virtual void Required_one_to_one_with_alternate_key_are_cascade_detached_ [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] [InlineData(null, null)] - public virtual void Required_non_PK_one_to_one_with_alternate_key_are_cascade_detached_when_Added( + public virtual Task Required_non_PK_one_to_one_with_alternate_key_are_cascade_detached_when_Added( CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) { var removedId = 0; var orphanedId = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming ?? CascadeTiming.Never; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming ?? CascadeTiming.Never; - var root = LoadRequiredNonPkAkGraph(context); + var root = await LoadRequiredNonPkAkGraphAsync(context); var removed = root.RequiredNonPkSingleAk; @@ -2634,7 +2634,7 @@ public virtual void Required_non_PK_one_to_one_with_alternate_key_are_cascade_de // Since we're pretending this isn't in the database, make it really not in the database context.Entry(orphaned).State = EntityState.Deleted; - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.Equal(EntityState.Detached, context.Entry(orphaned).State); @@ -2668,15 +2668,15 @@ public virtual void Required_non_PK_one_to_one_with_alternate_key_are_cascade_de if (Fixture.ForceClientNoAction) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else if (cascadeDeleteTiming == CascadeTiming.Never) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -2686,13 +2686,12 @@ public virtual void Required_non_PK_one_to_one_with_alternate_key_are_cascade_de Assert.Same(root, removed.Root); Assert.Same(orphaned, removed.Single); } - }, - context => + }, async context => { if (!Fixture.ForceClientNoAction && cascadeDeleteTiming != CascadeTiming.Never) { - var root = LoadRequiredNonPkAkGraph(context); + var root = await LoadRequiredNonPkAkGraphAsync(context); Assert.Null(root.RequiredNonPkSingleAk); diff --git a/test/EFCore.Specification.Tests/GraphUpdates/ProxyGraphUpdatesFixtureBase.cs b/test/EFCore.Specification.Tests/GraphUpdates/ProxyGraphUpdatesFixtureBase.cs index aac52dafc1c..cca977384ea 100644 --- a/test/EFCore.Specification.Tests/GraphUpdates/ProxyGraphUpdatesFixtureBase.cs +++ b/test/EFCore.Specification.Tests/GraphUpdates/ProxyGraphUpdatesFixtureBase.cs @@ -630,7 +630,7 @@ protected virtual object CreateFullGraph(DbContext context) }; }); - protected override void Seed(DbContext context) + protected override Task SeedAsync(DbContext context) { var tracker = new KeyValueEntityTracker(); @@ -650,7 +650,7 @@ protected override void Seed(DbContext context) dependent.Parent = parent; context.Add(dependent); - context.SaveChanges(); + return context.SaveChangesAsync(); } public class KeyValueEntityTracker @@ -681,12 +681,12 @@ public enum ChangeMechanism protected Expression> IsTheRoot => r => r.AlternateId == Fixture.RootAK; - protected Root LoadRoot(DbContext context) - => context.Set().Single(IsTheRoot); + protected Task LoadRootAsync(DbContext context) + => context.Set().SingleAsync(IsTheRoot); - protected Root LoadRequiredGraph(DbContext context) + protected Task LoadRequiredGraphAsync(DbContext context) => QueryRequiredGraph(context) - .Single(IsTheRoot); + .SingleAsync(IsTheRoot); protected IOrderedQueryable QueryRequiredGraph(DbContext context) => context.Set() @@ -694,9 +694,9 @@ protected IOrderedQueryable QueryRequiredGraph(DbContext context) .Include(e => e.RequiredSingle).ThenInclude(e => e.Single) .OrderBy(e => e.Id); - protected Root LoadOptionalGraph(DbContext context) + protected Task LoadOptionalGraphAsync(DbContext context) => QueryOptionalGraph(context) - .Single(IsTheRoot); + .SingleAsync(IsTheRoot); protected IOrderedQueryable QueryOptionalGraph(DbContext context) => context.Set() @@ -707,9 +707,9 @@ protected IOrderedQueryable QueryOptionalGraph(DbContext context) .Include(e => e.OptionalSingleMoreDerived).ThenInclude(e => e.Single) .OrderBy(e => e.Id); - protected Root LoadRequiredNonPkGraph(DbContext context) + protected Task LoadRequiredNonPkGraphAsync(DbContext context) => QueryRequiredNonPkGraph(context) - .Single(IsTheRoot); + .SingleAsync(IsTheRoot); protected IOrderedQueryable QueryRequiredNonPkGraph(DbContext context) => context.Set() @@ -721,9 +721,9 @@ protected IOrderedQueryable QueryRequiredNonPkGraph(DbContext context) .Include(e => e.RequiredNonPkSingleMoreDerived).ThenInclude(e => e.DerivedRoot) .OrderBy(e => e.Id); - protected Root LoadRequiredAkGraph(DbContext context) + protected Task LoadRequiredAkGraphAsync(DbContext context) => QueryRequiredAkGraph(context) - .Single(IsTheRoot); + .SingleAsync(IsTheRoot); protected IOrderedQueryable QueryRequiredAkGraph(DbContext context) => context.Set() @@ -733,9 +733,9 @@ protected IOrderedQueryable QueryRequiredAkGraph(DbContext context) .Include(e => e.RequiredSingleAk).ThenInclude(e => e.SingleComposite) .OrderBy(e => e.Id); - protected Root LoadOptionalAkGraph(DbContext context) + protected Task LoadOptionalAkGraphAsync(DbContext context) => QueryOptionalAkGraph(context) - .Single(IsTheRoot); + .SingleAsync(IsTheRoot); protected IOrderedQueryable QueryOptionalAkGraph(DbContext context) => context.Set() @@ -747,9 +747,9 @@ protected IOrderedQueryable QueryOptionalAkGraph(DbContext context) .Include(e => e.OptionalSingleAkMoreDerived).ThenInclude(e => e.Single) .OrderBy(e => e.Id); - protected Root LoadRequiredNonPkAkGraph(DbContext context) + protected Task LoadRequiredNonPkAkGraphAsync(DbContext context) => QueryRequiredNonPkAkGraph(context) - .Single(IsTheRoot); + .SingleAsync(IsTheRoot); protected IOrderedQueryable QueryRequiredNonPkAkGraph(DbContext context) => context.Set() @@ -761,9 +761,9 @@ protected IOrderedQueryable QueryRequiredNonPkAkGraph(DbContext context) .Include(e => e.RequiredNonPkSingleAkMoreDerived).ThenInclude(e => e.DerivedRoot) .OrderBy(e => e.Id); - protected Root LoadOptionalOneToManyGraph(DbContext context) + protected Task LoadOptionalOneToManyGraphAsync(DbContext context) => QueryOptionalOneToManyGraph(context) - .Single(IsTheRoot); + .SingleAsync(IsTheRoot); protected IOrderedQueryable QueryOptionalOneToManyGraph(DbContext context) => context.Set() @@ -773,9 +773,9 @@ protected IOrderedQueryable QueryOptionalOneToManyGraph(DbContext context) .Include(e => e.OptionalChildrenAk).ThenInclude(e => e.CompositeChildren) .OrderBy(e => e.Id); - protected Root LoadRequiredCompositeGraph(DbContext context) + protected Task LoadRequiredCompositeGraphAsync(DbContext context) => QueryRequiredCompositeGraph(context) - .Single(IsTheRoot); + .SingleAsync(IsTheRoot); protected IOrderedQueryable QueryRequiredCompositeGraph(DbContext context) => context.Set() @@ -2028,12 +2028,12 @@ public record RecordPerson : RecordBase protected DbContext CreateContext() => Fixture.CreateContext(); - protected virtual void ExecuteWithStrategyInTransaction( - Action testOperation, - Action nestedTestOperation1 = null, - Action nestedTestOperation2 = null, - Action nestedTestOperation3 = null) - => TestHelpers.ExecuteWithStrategyInTransaction( + protected virtual Task ExecuteWithStrategyInTransactionAsync( + Func testOperation, + Func nestedTestOperation1 = null, + Func nestedTestOperation2 = null, + Func nestedTestOperation3 = null) + => TestHelpers.ExecuteWithStrategyInTransactionAsync( CreateContext, UseTransaction, testOperation, nestedTestOperation1, nestedTestOperation2, nestedTestOperation3); diff --git a/test/EFCore.Specification.Tests/GraphUpdates/ProxyGraphUpdatesTestBaseMiscellaneous.cs b/test/EFCore.Specification.Tests/GraphUpdates/ProxyGraphUpdatesTestBaseMiscellaneous.cs index f311a69c1bd..d690524494a 100644 --- a/test/EFCore.Specification.Tests/GraphUpdates/ProxyGraphUpdatesTestBaseMiscellaneous.cs +++ b/test/EFCore.Specification.Tests/GraphUpdates/ProxyGraphUpdatesTestBaseMiscellaneous.cs @@ -11,8 +11,8 @@ public abstract partial class ProxyGraphUpdatesTestBase where TFixture : ProxyGraphUpdatesTestBase.ProxyGraphUpdatesFixtureBase, new() { [ConditionalFact] - public virtual void Save_two_entity_cycle_with_lazy_loading() - => ExecuteWithStrategyInTransaction( + public virtual Task Save_two_entity_cycle_with_lazy_loading() + => ExecuteWithStrategyInTransactionAsync( context => { context.AddRange( @@ -30,6 +30,7 @@ public virtual void Save_two_entity_cycle_with_lazy_loading() })); context.SaveChanges(); + return Task.CompletedTask; }, context => { @@ -56,11 +57,13 @@ public virtual void Save_two_entity_cycle_with_lazy_loading() var message = Assert.Throws(() => context.SaveChanges()).Message; Assert.StartsWith(CoreStrings.CircularDependency("").Substring(0, 30), message); } + + return Task.CompletedTask; }); [ConditionalFact] - public virtual void Can_use_record_proxies_with_base_types_to_load_reference() - => ExecuteWithStrategyInTransaction( + public virtual Task Can_use_record_proxies_with_base_types_to_load_reference() + => ExecuteWithStrategyInTransactionAsync( context => { context.AddRange( @@ -71,6 +74,7 @@ public virtual void Can_use_record_proxies_with_base_types_to_load_reference() })); context.SaveChanges(); + return Task.CompletedTask; }, context => { @@ -82,11 +86,12 @@ public virtual void Can_use_record_proxies_with_base_types_to_load_reference() Assert.Equal(car.Owner.Id, car.OwnerId); Assert.Same(car, car.Owner.Vehicles.Single()); + return Task.CompletedTask; }); [ConditionalFact] - public virtual void Can_use_record_proxies_with_base_types_to_load_collection() - => ExecuteWithStrategyInTransaction( + public virtual Task Can_use_record_proxies_with_base_types_to_load_collection() + => ExecuteWithStrategyInTransactionAsync( context => { context.AddRange( @@ -97,6 +102,7 @@ public virtual void Can_use_record_proxies_with_base_types_to_load_collection() })); context.SaveChanges(); + return Task.CompletedTask; }, context => { @@ -108,11 +114,12 @@ public virtual void Can_use_record_proxies_with_base_types_to_load_collection() Assert.Equal(owner.Id, owner.Vehicles.Single().Id); Assert.Same(owner, owner.Vehicles.Single().Owner); + return Task.CompletedTask; }); [ConditionalFact] - public virtual void Avoid_nulling_shared_FK_property_when_deleting() - => ExecuteWithStrategyInTransaction( + public virtual Task Avoid_nulling_shared_FK_property_when_deleting() + => ExecuteWithStrategyInTransactionAsync( context => { var root = context @@ -168,6 +175,7 @@ public virtual void Avoid_nulling_shared_FK_property_when_deleting() Assert.Equal(root.Id, dependent.RootId); Assert.Equal(root.Id, parent.RootId); Assert.Null(parent.DependantId); + return Task.CompletedTask; }, context => { @@ -187,13 +195,14 @@ public virtual void Avoid_nulling_shared_FK_property_when_deleting() Assert.Equal(root.Id, parent.RootId); Assert.Null(parent.DependantId); + return Task.CompletedTask; }); [ConditionalTheory] [InlineData(false)] [InlineData(true)] - public virtual void Avoid_nulling_shared_FK_property_when_nulling_navigation(bool nullPrincipal) - => ExecuteWithStrategyInTransaction( + public virtual Task Avoid_nulling_shared_FK_property_when_nulling_navigation(bool nullPrincipal) + => ExecuteWithStrategyInTransactionAsync( context => { var root = context @@ -252,6 +261,7 @@ public virtual void Avoid_nulling_shared_FK_property_when_nulling_navigation(boo Assert.Equal(root.Id, dependent.RootId); Assert.Equal(root.Id, parent.RootId); Assert.Null(parent.DependantId); + return Task.CompletedTask; }, context => { @@ -274,14 +284,15 @@ public virtual void Avoid_nulling_shared_FK_property_when_nulling_navigation(boo Assert.Equal(root.Id, dependent.RootId); Assert.Equal(root.Id, parent.RootId); Assert.Null(parent.DependantId); + return Task.CompletedTask; }); [ConditionalFact] - public virtual void No_fixup_to_Deleted_entities() + public virtual async Task No_fixup_to_Deleted_entities() { using var context = CreateContext(); - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { context.Entry(root).Collection(e => e.OptionalChildren).Load(); @@ -307,8 +318,8 @@ public virtual void No_fixup_to_Deleted_entities() } [ConditionalFact] - public virtual void Sometimes_not_calling_DetectChanges_when_required_does_not_throw_for_null_ref() - => ExecuteWithStrategyInTransaction( + public virtual Task Sometimes_not_calling_DetectChanges_when_required_does_not_throw_for_null_ref() + => ExecuteWithStrategyInTransactionAsync( context => { var dependent = context.Set().Single(); @@ -328,6 +339,7 @@ public virtual void Sometimes_not_calling_DetectChanges_when_required_does_not_t Assert.Null(dependent.BadCustomerId); Assert.Null(dependent.BadCustomer); Assert.Empty(principal.BadOrders); + return Task.CompletedTask; }, context => { @@ -337,14 +349,15 @@ public virtual void Sometimes_not_calling_DetectChanges_when_required_does_not_t Assert.Null(dependent.BadCustomerId); Assert.Null(dependent.BadCustomer); Assert.Empty(principal.BadOrders); + return Task.CompletedTask; }); [ConditionalFact] - public void Can_attach_full_required_graph_of_duplicates() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Can_attach_full_required_graph_of_duplicates() + => ExecuteWithStrategyInTransactionAsync( + async context => { - var trackedRoot = LoadRequiredGraph(context); + var trackedRoot = await LoadRequiredGraphAsync(context); var entries = context.ChangeTracker.Entries().ToList(); context.Attach(QueryRequiredGraph(context).AsNoTracking().Single(IsTheRoot)); @@ -355,11 +368,11 @@ public void Can_attach_full_required_graph_of_duplicates() }); [ConditionalFact] - public void Can_attach_full_optional_graph_of_duplicates() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Can_attach_full_optional_graph_of_duplicates() + => ExecuteWithStrategyInTransactionAsync( + async context => { - var trackedRoot = LoadOptionalGraph(context); + var trackedRoot = await LoadOptionalGraphAsync(context); var entries = context.ChangeTracker.Entries().ToList(); context.Attach(QueryOptionalGraph(context).AsNoTracking().Single(IsTheRoot)); @@ -370,11 +383,11 @@ public void Can_attach_full_optional_graph_of_duplicates() }); [ConditionalFact] - public void Can_attach_full_required_non_PK_graph_of_duplicates() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Can_attach_full_required_non_PK_graph_of_duplicates() + => ExecuteWithStrategyInTransactionAsync( + async context => { - var trackedRoot = LoadRequiredNonPkGraph(context); + var trackedRoot = await LoadRequiredNonPkGraphAsync(context); var entries = context.ChangeTracker.Entries().ToList(); context.Attach(QueryRequiredNonPkGraph(context).AsNoTracking().Single(IsTheRoot)); @@ -385,11 +398,11 @@ public void Can_attach_full_required_non_PK_graph_of_duplicates() }); [ConditionalFact] - public void Can_attach_full_required_AK_graph_of_duplicates() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Can_attach_full_required_AK_graph_of_duplicates() + => ExecuteWithStrategyInTransactionAsync( + async context => { - var trackedRoot = LoadRequiredAkGraph(context); + var trackedRoot = await LoadRequiredAkGraphAsync(context); var entries = context.ChangeTracker.Entries().ToList(); context.Attach(QueryRequiredAkGraph(context).AsNoTracking().Single(IsTheRoot)); @@ -400,11 +413,11 @@ public void Can_attach_full_required_AK_graph_of_duplicates() }); [ConditionalFact] - public void Can_attach_full_optional_AK_graph_of_duplicates() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Can_attach_full_optional_AK_graph_of_duplicates() + => ExecuteWithStrategyInTransactionAsync( + async context => { - var trackedRoot = LoadOptionalAkGraph(context); + var trackedRoot = await LoadOptionalAkGraphAsync(context); var entries = context.ChangeTracker.Entries().ToList(); context.Attach(QueryOptionalAkGraph(context).AsNoTracking().Single(IsTheRoot)); @@ -415,11 +428,11 @@ public void Can_attach_full_optional_AK_graph_of_duplicates() }); [ConditionalFact] - public void Can_attach_full_required_non_PK_AK_graph_of_duplicates() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Can_attach_full_required_non_PK_AK_graph_of_duplicates() + => ExecuteWithStrategyInTransactionAsync( + async context => { - var trackedRoot = LoadRequiredNonPkAkGraph(context); + var trackedRoot = await LoadRequiredNonPkAkGraphAsync(context); var entries = context.ChangeTracker.Entries().ToList(); context.Attach(QueryRequiredNonPkAkGraph(context).AsNoTracking().Single(IsTheRoot)); @@ -430,11 +443,11 @@ public void Can_attach_full_required_non_PK_AK_graph_of_duplicates() }); [ConditionalFact] - public void Can_attach_full_required_one_to_many_graph_of_duplicates() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Can_attach_full_required_one_to_many_graph_of_duplicates() + => ExecuteWithStrategyInTransactionAsync( + async context => { - var trackedRoot = LoadOptionalOneToManyGraph(context); + var trackedRoot = await LoadOptionalOneToManyGraphAsync(context); var entries = context.ChangeTracker.Entries().ToList(); context.Attach(QueryOptionalOneToManyGraph(context).AsNoTracking().Single(IsTheRoot)); @@ -445,11 +458,11 @@ public void Can_attach_full_required_one_to_many_graph_of_duplicates() }); [ConditionalFact] - public void Can_attach_full_required_composite_graph_of_duplicates() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Can_attach_full_required_composite_graph_of_duplicates() + => ExecuteWithStrategyInTransactionAsync( + async context => { - var trackedRoot = LoadRequiredCompositeGraph(context); + var trackedRoot = await LoadRequiredCompositeGraphAsync(context); var entries = context.ChangeTracker.Entries().ToList(); context.Attach(QueryRequiredCompositeGraph(context).AsNoTracking().Single(IsTheRoot)); diff --git a/test/EFCore.Specification.Tests/GraphUpdates/ProxyGraphUpdatesTestBaseOneToMany.cs b/test/EFCore.Specification.Tests/GraphUpdates/ProxyGraphUpdatesTestBaseOneToMany.cs index a424b080cd9..7d8d701c842 100644 --- a/test/EFCore.Specification.Tests/GraphUpdates/ProxyGraphUpdatesTestBaseOneToMany.cs +++ b/test/EFCore.Specification.Tests/GraphUpdates/ProxyGraphUpdatesTestBaseOneToMany.cs @@ -27,7 +27,7 @@ public abstract partial class ProxyGraphUpdatesTestBase : IClassFixtur [InlineData((int)(ChangeMechanism.Fk | ChangeMechanism.Dependent), true)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), false)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), true)] - public virtual void Save_optional_many_to_one_dependents(ChangeMechanism changeMechanism, bool useExistingEntities) + public virtual Task Save_optional_many_to_one_dependents(ChangeMechanism changeMechanism, bool useExistingEntities) { Optional1 new1 = null; Optional1Derived new1d = null; @@ -37,7 +37,7 @@ public virtual void Save_optional_many_to_one_dependents(ChangeMechanism changeM Optional2Derived new2d = null; Optional2MoreDerived new2dd = null; - ExecuteWithStrategyInTransaction( + return ExecuteWithStrategyInTransactionAsync( context => { new1 = context.CreateProxy(); @@ -53,10 +53,11 @@ public virtual void Save_optional_many_to_one_dependents(ChangeMechanism changeM context.AddRange(new1, new1d, new1dd, new2a, new2d, new2dd, new2b); context.SaveChanges(); } - }, - context => + + return Task.CompletedTask; + }, async context => { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -160,7 +161,7 @@ public virtual void Save_optional_many_to_one_dependents(ChangeMechanism changeM [InlineData((int)(ChangeMechanism.Fk | ChangeMechanism.Dependent), true)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), false)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), true)] - public virtual void Save_required_many_to_one_dependents(ChangeMechanism changeMechanism, bool useExistingEntities) + public virtual Task Save_required_many_to_one_dependents(ChangeMechanism changeMechanism, bool useExistingEntities) { Root newRoot; Required1 new1 = null; @@ -171,7 +172,7 @@ public virtual void Save_required_many_to_one_dependents(ChangeMechanism changeM Required2Derived new2d = null; Required2MoreDerived new2dd = null; - ExecuteWithStrategyInTransaction( + return ExecuteWithStrategyInTransactionAsync( context => { newRoot = context.CreateProxy(); @@ -188,10 +189,11 @@ public virtual void Save_required_many_to_one_dependents(ChangeMechanism changeM context.AddRange(newRoot, new1, new1d, new1dd, new2a, new2d, new2dd, new2b); context.SaveChanges(); } - }, - context => + + return Task.CompletedTask; + }, async context => { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -292,13 +294,13 @@ public virtual void Save_required_many_to_one_dependents(ChangeMechanism changeM [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Fk))] [InlineData((int)(ChangeMechanism.Fk | ChangeMechanism.Dependent))] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk))] - public virtual void Save_removed_optional_many_to_one_dependents(ChangeMechanism changeMechanism) + public virtual Task Save_removed_optional_many_to_one_dependents(ChangeMechanism changeMechanism) { Root root; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - root = LoadRoot(context); + root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -341,12 +343,11 @@ public virtual void Save_removed_optional_many_to_one_dependents(ChangeMechanism Assert.Null(removed2.Parent); Assert.Null(removed1.ParentId); Assert.Null(removed2.ParentId); - }, - context => + }, async context => { if ((changeMechanism & ChangeMechanism.Fk) == 0) { - var loadedRoot = LoadRoot(context); + var loadedRoot = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -368,16 +369,16 @@ public virtual void Save_removed_optional_many_to_one_dependents(ChangeMechanism [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Fk))] [InlineData((int)(ChangeMechanism.Fk | ChangeMechanism.Dependent))] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk))] - public virtual void Save_removed_required_many_to_one_dependents(ChangeMechanism changeMechanism) + public virtual Task Save_removed_required_many_to_one_dependents(ChangeMechanism changeMechanism) { var removed1Id = 0; var removed2Id = 0; List removed1ChildrenIds = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -416,10 +417,9 @@ public virtual void Save_removed_required_many_to_one_dependents(ChangeMechanism context.SaveChanges(); Assert.False(context.ChangeTracker.HasChanges()); - }, - context => + }, async context => { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -450,7 +450,7 @@ public virtual void Save_removed_required_many_to_one_dependents(ChangeMechanism [InlineData((int)(ChangeMechanism.Fk | ChangeMechanism.Dependent), true)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), false)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), true)] - public virtual void Reparent_to_different_one_to_many(ChangeMechanism changeMechanism, bool useExistingParent) + public virtual Task Reparent_to_different_one_to_many(ChangeMechanism changeMechanism, bool useExistingParent) { var compositeCount = 0; OptionalAk1 oldParent = null; @@ -458,7 +458,7 @@ public virtual void Reparent_to_different_one_to_many(ChangeMechanism changeMech OptionalComposite2 oldComposite2 = null; Optional1 newParent = null; - ExecuteWithStrategyInTransaction( + return ExecuteWithStrategyInTransactionAsync( context => { if (!useExistingParent) @@ -469,10 +469,11 @@ public virtual void Reparent_to_different_one_to_many(ChangeMechanism changeMech context.Set().Add(newParent); context.SaveChanges(); } - }, - context => + + return Task.CompletedTask; + }, async context => { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); compositeCount = context.Set().Count(); @@ -544,12 +545,11 @@ public virtual void Reparent_to_different_one_to_many(ChangeMechanism changeMech Assert.Null(oldComposite1.ParentId); Assert.Equal(compositeCount, context.Set().Count()); - }, - context => + }, async context => { if ((changeMechanism & ChangeMechanism.Fk) == 0) { - var loadedRoot = LoadRoot(context); + var loadedRoot = await LoadRootAsync(context); oldParent = context.Set().Single(e => e.Id == oldParent.Id); newParent = context.Set().Single(e => e.Id == newParent.Id); @@ -589,7 +589,7 @@ public virtual void Reparent_to_different_one_to_many(ChangeMechanism changeMech [InlineData((int)(ChangeMechanism.Fk | ChangeMechanism.Dependent), true)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), false)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), true)] - public virtual void Reparent_one_to_many_overlapping(ChangeMechanism changeMechanism, bool useExistingParent) + public virtual Task Reparent_one_to_many_overlapping(ChangeMechanism changeMechanism, bool useExistingParent) { Root root = null; var childCount = 0; @@ -598,7 +598,7 @@ public virtual void Reparent_one_to_many_overlapping(ChangeMechanism changeMecha OptionalOverlapping2 oldChild2 = null; RequiredComposite1 newParent = null; - ExecuteWithStrategyInTransaction( + return ExecuteWithStrategyInTransactionAsync( context => { if (!useExistingParent) @@ -618,10 +618,11 @@ public virtual void Reparent_one_to_many_overlapping(ChangeMechanism changeMecha context.Set().Add(newParent); context.SaveChanges(); } - }, - context => + + return Task.CompletedTask; + }, async context => { - root = LoadRoot(context); + root = await LoadRootAsync(context); childCount = context.Set().Count(); @@ -695,10 +696,9 @@ public virtual void Reparent_one_to_many_overlapping(ChangeMechanism changeMecha Assert.Same(root, oldChild1.Root); Assert.Equal(childCount, context.Set().Count()); - }, - context => + }, async context => { - var loadedRoot = LoadRoot(context); + var loadedRoot = await LoadRootAsync(context); oldParent = context.Set().Single(e => e.Id == oldParent.Id); newParent = context.Set().Single(e => e.Id == newParent.Id); @@ -738,20 +738,20 @@ public virtual void Reparent_one_to_many_overlapping(ChangeMechanism changeMecha [InlineData(CascadeTiming.Never, CascadeTiming.OnSaveChanges)] [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] - public virtual void Required_many_to_one_dependents_are_cascade_deleted( + public virtual Task Required_many_to_one_dependents_are_cascade_deleted( CascadeTiming cascadeDeleteTiming, CascadeTiming deleteOrphansTiming) { var removedId = 0; List orphanedIds = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming; - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -799,12 +799,11 @@ public virtual void Required_many_to_one_dependents_are_cascade_deleted( Assert.Same(root, removed.Parent); Assert.Equal(2, removed.Children.Count()); } - }, - context => + }, async context => { if (cascadeDeleteTiming != CascadeTiming.Never) { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -830,20 +829,20 @@ public virtual void Required_many_to_one_dependents_are_cascade_deleted( [InlineData(CascadeTiming.Never, CascadeTiming.OnSaveChanges)] [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] - public virtual void Optional_many_to_one_dependents_are_orphaned( + public virtual Task Optional_many_to_one_dependents_are_orphaned( CascadeTiming cascadeDeleteTiming, CascadeTiming deleteOrphansTiming) { var removedId = 0; List orphanedIds = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming; - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -905,10 +904,9 @@ public virtual void Optional_many_to_one_dependents_are_orphaned( Assert.Same(root, removed.Parent); Assert.Equal(2, removed.Children.Count()); - }, - context => + }, async context => { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -934,10 +932,10 @@ public virtual void Optional_many_to_one_dependents_are_orphaned( [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] [InlineData(null, null)] - public virtual void Optional_many_to_one_dependents_are_orphaned_with_Added_graph( + public virtual Task Optional_many_to_one_dependents_are_orphaned_with_Added_graph( CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) // Issue #29318 - => ExecuteWithStrategyInTransaction( + => ExecuteWithStrategyInTransactionAsync( context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming ?? CascadeTiming.Never; @@ -980,6 +978,7 @@ public virtual void Optional_many_to_one_dependents_are_orphaned_with_Added_grap Assert.Empty(root.OptionalChildren); Assert.Same(root, removed.Parent); Assert.Equal(2, removed.Children.Count()); + return Task.CompletedTask; }); [ConditionalTheory] @@ -992,17 +991,17 @@ public virtual void Optional_many_to_one_dependents_are_orphaned_with_Added_grap [InlineData(CascadeTiming.Never, CascadeTiming.OnSaveChanges)] [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] - public virtual void Required_many_to_one_dependents_are_cascade_deleted_in_store( + public virtual Task Required_many_to_one_dependents_are_cascade_deleted_in_store( CascadeTiming cascadeDeleteTiming, CascadeTiming deleteOrphansTiming) { var removedId = 0; List orphanedIds = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1050,10 +1049,10 @@ public virtual void Required_many_to_one_dependents_are_cascade_deleted_in_store Assert.Same(root, removed.Parent); Assert.Empty(removed.Children); - }, - context => + return Task.CompletedTask; + }, async context => { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1078,17 +1077,17 @@ public virtual void Required_many_to_one_dependents_are_cascade_deleted_in_store [InlineData(CascadeTiming.Never, CascadeTiming.OnSaveChanges)] [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] - public virtual void Optional_many_to_one_dependents_are_orphaned_in_store( + public virtual Task Optional_many_to_one_dependents_are_orphaned_in_store( CascadeTiming cascadeDeleteTiming, CascadeTiming deleteOrphansTiming) { var removedId = 0; List orphanedIds = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1139,10 +1138,10 @@ public virtual void Optional_many_to_one_dependents_are_orphaned_in_store( Assert.Same(root, removed.Parent); Assert.Empty(removed.Children); // Never loaded - }, - context => + return Task.CompletedTask; + }, async context => { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1170,7 +1169,7 @@ public virtual void Optional_many_to_one_dependents_are_orphaned_in_store( [InlineData(CascadeTiming.Never, CascadeTiming.OnSaveChanges)] [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] - public virtual void Required_many_to_one_dependents_are_cascade_deleted_starting_detached( + public virtual Task Required_many_to_one_dependents_are_cascade_deleted_starting_detached( CascadeTiming cascadeDeleteTiming, CascadeTiming deleteOrphansTiming) { @@ -1180,10 +1179,10 @@ public virtual void Required_many_to_one_dependents_are_cascade_deleted_starting Required1 removed = null; List cascadeRemoved = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - root = LoadRoot(context); + root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1239,12 +1238,13 @@ public virtual void Required_many_to_one_dependents_are_cascade_deleted_starting Assert.Same(root, removed.Parent); Assert.Equal(2, removed.Children.Count()); } - }, - context => + + return Task.CompletedTask; + }, async context => { if (cascadeDeleteTiming != CascadeTiming.Never) { - root = LoadRoot(context); + root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1270,7 +1270,7 @@ public virtual void Required_many_to_one_dependents_are_cascade_deleted_starting [InlineData(CascadeTiming.Never, CascadeTiming.OnSaveChanges)] [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] - public virtual void Optional_many_to_one_dependents_are_orphaned_starting_detached( + public virtual Task Optional_many_to_one_dependents_are_orphaned_starting_detached( CascadeTiming cascadeDeleteTiming, CascadeTiming deleteOrphansTiming) { @@ -1280,10 +1280,10 @@ public virtual void Optional_many_to_one_dependents_are_orphaned_starting_detach Optional1 removed = null; List orphaned = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - root = LoadRoot(context); + root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1347,10 +1347,10 @@ public virtual void Optional_many_to_one_dependents_are_orphaned_starting_detach Assert.Same(root, removed.Parent); Assert.Equal(2, removed.Children.Count()); - }, - context => + return Task.CompletedTask; + }, async context => { - root = LoadRoot(context); + root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1375,20 +1375,20 @@ public virtual void Optional_many_to_one_dependents_are_orphaned_starting_detach [InlineData(CascadeTiming.Never, CascadeTiming.OnSaveChanges)] [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] - public virtual void Required_many_to_one_dependents_are_cascade_detached_when_Added( + public virtual Task Required_many_to_one_dependents_are_cascade_detached_when_Added( CascadeTiming cascadeDeleteTiming, CascadeTiming deleteOrphansTiming) { var removedId = 0; List orphanedIds = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming; - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1458,12 +1458,11 @@ public virtual void Required_many_to_one_dependents_are_cascade_detached_when_Ad Assert.Same(root, removed.Parent); Assert.Equal(3, removed.Children.Count()); } - }, - context => + }, async context => { if (cascadeDeleteTiming != CascadeTiming.Never) { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { diff --git a/test/EFCore.Specification.Tests/GraphUpdates/ProxyGraphUpdatesTestBaseOneToManyAk.cs b/test/EFCore.Specification.Tests/GraphUpdates/ProxyGraphUpdatesTestBaseOneToManyAk.cs index 55ebd772897..9529afe4740 100644 --- a/test/EFCore.Specification.Tests/GraphUpdates/ProxyGraphUpdatesTestBaseOneToManyAk.cs +++ b/test/EFCore.Specification.Tests/GraphUpdates/ProxyGraphUpdatesTestBaseOneToManyAk.cs @@ -27,7 +27,7 @@ public abstract partial class ProxyGraphUpdatesTestBase : IClassFixtur [InlineData((int)(ChangeMechanism.Fk | ChangeMechanism.Dependent), true)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), false)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), true)] - public virtual void Save_optional_many_to_one_dependents_with_alternate_key( + public virtual Task Save_optional_many_to_one_dependents_with_alternate_key( ChangeMechanism changeMechanism, bool useExistingEntities) { @@ -41,7 +41,7 @@ public virtual void Save_optional_many_to_one_dependents_with_alternate_key( OptionalAk2Derived new2d = null; OptionalAk2MoreDerived new2dd = null; - ExecuteWithStrategyInTransaction( + return ExecuteWithStrategyInTransactionAsync( context => { new1 = context.CreateProxy(e => e.AlternateId = Guid.NewGuid()); @@ -59,10 +59,11 @@ public virtual void Save_optional_many_to_one_dependents_with_alternate_key( context.AddRange(new1, new1d, new1dd, new2a, new2d, new2dd, new2b, new2ca, new2cb); context.SaveChanges(); } - }, - context => + + return Task.CompletedTask; + }, async context => { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -184,7 +185,7 @@ public virtual void Save_optional_many_to_one_dependents_with_alternate_key( [InlineData((int)(ChangeMechanism.Fk | ChangeMechanism.Dependent), true)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), false)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), true)] - public virtual void Save_required_many_to_one_dependents_with_alternate_key( + public virtual Task Save_required_many_to_one_dependents_with_alternate_key( ChangeMechanism changeMechanism, bool useExistingEntities) { @@ -199,7 +200,7 @@ public virtual void Save_required_many_to_one_dependents_with_alternate_key( RequiredAk2Derived new2d = null; RequiredAk2MoreDerived new2dd = null; - ExecuteWithStrategyInTransaction( + return ExecuteWithStrategyInTransactionAsync( context => { newRoot = context.CreateProxy(e => e.AlternateId = Guid.NewGuid()); @@ -253,10 +254,11 @@ public virtual void Save_required_many_to_one_dependents_with_alternate_key( context.AddRange(newRoot, new1, new1d, new1dd, new2a, new2d, new2dd, new2b, new2ca, new2cb); context.SaveChanges(); } - }, - context => + + return Task.CompletedTask; + }, async context => { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -375,13 +377,13 @@ public virtual void Save_required_many_to_one_dependents_with_alternate_key( [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Fk))] [InlineData((int)(ChangeMechanism.Fk | ChangeMechanism.Dependent))] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk))] - public virtual void Save_removed_optional_many_to_one_dependents_with_alternate_key(ChangeMechanism changeMechanism) + public virtual Task Save_removed_optional_many_to_one_dependents_with_alternate_key(ChangeMechanism changeMechanism) { Root root; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - root = LoadRoot(context); + root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -434,12 +436,11 @@ public virtual void Save_removed_optional_many_to_one_dependents_with_alternate_ Assert.Null(removed1.ParentId); Assert.Null(removed2.ParentId); Assert.Null(removed2c.ParentId); - }, - context => + }, async context => { if ((changeMechanism & ChangeMechanism.Fk) == 0) { - var loadedRoot = LoadRoot(context); + var loadedRoot = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -457,17 +458,17 @@ public virtual void Save_removed_optional_many_to_one_dependents_with_alternate_ [InlineData((int)ChangeMechanism.Principal)] [InlineData((int)ChangeMechanism.Dependent)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent))] - public virtual void Save_removed_required_many_to_one_dependents_with_alternate_key(ChangeMechanism changeMechanism) + public virtual Task Save_removed_required_many_to_one_dependents_with_alternate_key(ChangeMechanism changeMechanism) { Root root = null; RequiredAk2 removed2 = null; RequiredComposite2 removed2c = null; RequiredAk1 removed1 = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - root = LoadRoot(context); + root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -514,10 +515,9 @@ public virtual void Save_removed_required_many_to_one_dependents_with_alternate_ Assert.Null(removed1.Parent); Assert.Null(removed2.Parent); Assert.Null(removed2c.Parent); - }, - context => + }, async context => { - var loadedRoot = LoadRoot(context); + var loadedRoot = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -546,20 +546,20 @@ public virtual void Save_removed_required_many_to_one_dependents_with_alternate_ [InlineData(CascadeTiming.Never, CascadeTiming.OnSaveChanges)] [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] - public virtual void Optional_many_to_one_dependents_with_alternate_key_are_orphaned( + public virtual Task Optional_many_to_one_dependents_with_alternate_key_are_orphaned( CascadeTiming cascadeDeleteTiming, CascadeTiming deleteOrphansTiming) { var removedId = 0; List orphanedIds = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming; - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -601,10 +601,9 @@ public virtual void Optional_many_to_one_dependents_with_alternate_key_are_orpha Assert.Same(root, removed.Parent); Assert.Equal(2, removed.Children.Count()); - }, - context => + }, async context => { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -629,7 +628,7 @@ public virtual void Optional_many_to_one_dependents_with_alternate_key_are_orpha [InlineData(CascadeTiming.Never, CascadeTiming.OnSaveChanges)] [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] - public virtual void Required_many_to_one_dependents_with_alternate_key_are_cascade_deleted( + public virtual Task Required_many_to_one_dependents_with_alternate_key_are_cascade_deleted( CascadeTiming cascadeDeleteTiming, CascadeTiming deleteOrphansTiming) { @@ -637,13 +636,13 @@ public virtual void Required_many_to_one_dependents_with_alternate_key_are_casca List orphanedIds = null; List orphanedIdCs = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming; - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -696,12 +695,11 @@ public virtual void Required_many_to_one_dependents_with_alternate_key_are_casca Assert.Same(root, removed.Parent); Assert.Equal(2, removed.Children.Count()); } - }, - context => + }, async context => { if (cascadeDeleteTiming != CascadeTiming.Never) { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -728,7 +726,7 @@ public virtual void Required_many_to_one_dependents_with_alternate_key_are_casca [InlineData(CascadeTiming.Never, CascadeTiming.OnSaveChanges)] [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] - public virtual void Required_many_to_one_dependents_with_alternate_key_are_cascade_deleted_in_store( + public virtual Task Required_many_to_one_dependents_with_alternate_key_are_cascade_deleted_in_store( CascadeTiming cascadeDeleteTiming, CascadeTiming deleteOrphansTiming) { @@ -736,10 +734,10 @@ public virtual void Required_many_to_one_dependents_with_alternate_key_are_casca List orphanedIds = null; List orphanedIdCs = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -789,10 +787,10 @@ public virtual void Required_many_to_one_dependents_with_alternate_key_are_casca Assert.Same(root, removed.Parent); Assert.Empty(removed.Children); // Never loaded - }, - context => + return Task.CompletedTask; + }, async context => { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -818,7 +816,7 @@ public virtual void Required_many_to_one_dependents_with_alternate_key_are_casca [InlineData(CascadeTiming.Never, CascadeTiming.OnSaveChanges)] [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] - public virtual void Optional_many_to_one_dependents_with_alternate_key_are_orphaned_in_store( + public virtual Task Optional_many_to_one_dependents_with_alternate_key_are_orphaned_in_store( CascadeTiming cascadeDeleteTiming, CascadeTiming deleteOrphansTiming) { @@ -826,10 +824,10 @@ public virtual void Optional_many_to_one_dependents_with_alternate_key_are_orpha List orphanedIds = null; List orphanedIdCs = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -890,10 +888,10 @@ public virtual void Optional_many_to_one_dependents_with_alternate_key_are_orpha Assert.Same(root, removed.Parent); Assert.Empty(removed.Children); // Never loaded - }, - context => + return Task.CompletedTask; + }, async context => { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -925,7 +923,7 @@ public virtual void Optional_many_to_one_dependents_with_alternate_key_are_orpha [InlineData(CascadeTiming.Never, CascadeTiming.OnSaveChanges)] [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] - public virtual void Optional_many_to_one_dependents_with_alternate_key_are_orphaned_starting_detached( + public virtual Task Optional_many_to_one_dependents_with_alternate_key_are_orphaned_starting_detached( CascadeTiming cascadeDeleteTiming, CascadeTiming deleteOrphansTiming) { @@ -937,10 +935,10 @@ public virtual void Optional_many_to_one_dependents_with_alternate_key_are_orpha List orphaned = null; List orphanedC = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - root = LoadRoot(context); + root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -995,10 +993,10 @@ public virtual void Optional_many_to_one_dependents_with_alternate_key_are_orpha Assert.Same(root, removed.Parent); Assert.Equal(2, removed.Children.Count()); - }, - context => + return Task.CompletedTask; + }, async context => { - root = LoadRoot(context); + root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1024,7 +1022,7 @@ public virtual void Optional_many_to_one_dependents_with_alternate_key_are_orpha [InlineData(CascadeTiming.Never, CascadeTiming.OnSaveChanges)] [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] - public virtual void Required_many_to_one_dependents_with_alternate_key_are_cascade_deleted_starting_detached( + public virtual Task Required_many_to_one_dependents_with_alternate_key_are_cascade_deleted_starting_detached( CascadeTiming cascadeDeleteTiming, CascadeTiming deleteOrphansTiming) { @@ -1036,10 +1034,10 @@ public virtual void Required_many_to_one_dependents_with_alternate_key_are_casca List cascadeRemoved = null; List cascadeRemovedC = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - root = LoadRoot(context); + root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1100,12 +1098,13 @@ public virtual void Required_many_to_one_dependents_with_alternate_key_are_casca Assert.Same(root, removed.Parent); Assert.Equal(2, removed.Children.Count()); } - }, - context => + + return Task.CompletedTask; + }, async context => { if (cascadeDeleteTiming != CascadeTiming.Never) { - root = LoadRoot(context); + root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1132,7 +1131,7 @@ public virtual void Required_many_to_one_dependents_with_alternate_key_are_casca [InlineData(CascadeTiming.Never, CascadeTiming.OnSaveChanges)] [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] - public virtual void Required_many_to_one_dependents_with_alternate_key_are_cascade_detached_when_Added( + public virtual Task Required_many_to_one_dependents_with_alternate_key_are_cascade_detached_when_Added( CascadeTiming cascadeDeleteTiming, CascadeTiming deleteOrphansTiming) { @@ -1140,13 +1139,13 @@ public virtual void Required_many_to_one_dependents_with_alternate_key_are_casca List orphanedIds = null; List orphanedIdCs = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming; - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1229,12 +1228,11 @@ public virtual void Required_many_to_one_dependents_with_alternate_key_are_casca Assert.Same(root, removed.Parent); Assert.Equal(3, removed.Children.Count()); } - }, - context => + }, async context => { if (cascadeDeleteTiming != CascadeTiming.Never) { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { diff --git a/test/EFCore.Specification.Tests/GraphUpdates/ProxyGraphUpdatesTestBaseOneToOne.cs b/test/EFCore.Specification.Tests/GraphUpdates/ProxyGraphUpdatesTestBaseOneToOne.cs index bb84bbe4b94..9d0e3af3e95 100644 --- a/test/EFCore.Specification.Tests/GraphUpdates/ProxyGraphUpdatesTestBaseOneToOne.cs +++ b/test/EFCore.Specification.Tests/GraphUpdates/ProxyGraphUpdatesTestBaseOneToOne.cs @@ -13,8 +13,8 @@ public abstract partial class ProxyGraphUpdatesTestBase : IClassFixtur where TFixture : ProxyGraphUpdatesTestBase.ProxyGraphUpdatesFixtureBase, new() { [ConditionalFact] - public virtual void Optional_one_to_one_relationships_are_one_to_one() - => ExecuteWithStrategyInTransaction( + public virtual Task Optional_one_to_one_relationships_are_one_to_one() + => ExecuteWithStrategyInTransactionAsync( context => { var root = context.Set().Single(IsTheRoot); @@ -22,11 +22,12 @@ public virtual void Optional_one_to_one_relationships_are_one_to_one() root.OptionalSingle = context.CreateProxy(); Assert.Throws(() => context.SaveChanges()); + return Task.CompletedTask; }); [ConditionalFact] - public virtual void Required_one_to_one_relationships_are_one_to_one() - => ExecuteWithStrategyInTransaction( + public virtual Task Required_one_to_one_relationships_are_one_to_one() + => ExecuteWithStrategyInTransactionAsync( context => { var root = context.Set().Single(IsTheRoot); @@ -34,11 +35,12 @@ public virtual void Required_one_to_one_relationships_are_one_to_one() root.RequiredSingle = context.CreateProxy(); Assert.Throws(() => context.SaveChanges()); + return Task.CompletedTask; }); [ConditionalFact] - public virtual void Optional_one_to_one_with_AK_relationships_are_one_to_one() - => ExecuteWithStrategyInTransaction( + public virtual Task Optional_one_to_one_with_AK_relationships_are_one_to_one() + => ExecuteWithStrategyInTransactionAsync( context => { var root = context.Set().Single(IsTheRoot); @@ -46,11 +48,12 @@ public virtual void Optional_one_to_one_with_AK_relationships_are_one_to_one() root.OptionalSingleAk = context.CreateProxy(); Assert.Throws(() => context.SaveChanges()); + return Task.CompletedTask; }); [ConditionalFact] - public virtual void Required_one_to_one_with_AK_relationships_are_one_to_one() - => ExecuteWithStrategyInTransaction( + public virtual Task Required_one_to_one_with_AK_relationships_are_one_to_one() + => ExecuteWithStrategyInTransactionAsync( context => { var root = context.Set().Single(IsTheRoot); @@ -58,6 +61,7 @@ public virtual void Required_one_to_one_with_AK_relationships_are_one_to_one() root.RequiredSingleAk = context.CreateProxy(); Assert.Throws(() => context.SaveChanges()); + return Task.CompletedTask; }); [ConditionalTheory] @@ -75,7 +79,7 @@ public virtual void Required_one_to_one_with_AK_relationships_are_one_to_one() [InlineData((int)(ChangeMechanism.Fk | ChangeMechanism.Dependent), true)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), false)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), true)] - public virtual void Save_changed_optional_one_to_one(ChangeMechanism changeMechanism, bool useExistingEntities) + public virtual Task Save_changed_optional_one_to_one(ChangeMechanism changeMechanism, bool useExistingEntities) { OptionalSingle2 new2 = null; OptionalSingle2Derived new2d = null; @@ -90,7 +94,7 @@ public virtual void Save_changed_optional_one_to_one(ChangeMechanism changeMecha OptionalSingle2Derived old2d = null; OptionalSingle2MoreDerived old2dd = null; - ExecuteWithStrategyInTransaction( + return ExecuteWithStrategyInTransactionAsync( context => { new2 = context.CreateProxy(); @@ -105,10 +109,11 @@ public virtual void Save_changed_optional_one_to_one(ChangeMechanism changeMecha context.AddRange(new1, new1d, new1dd, new2, new2d, new2dd); context.SaveChanges(); } - }, - context => + + return Task.CompletedTask; + }, async context => { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -198,10 +203,9 @@ public virtual void Save_changed_optional_one_to_one(ChangeMechanism changeMecha Assert.Equal(old1.Id, old2.BackId); Assert.Equal(old1d.Id, old2d.BackId); Assert.Equal(old1dd.Id, old2dd.BackId); - }, - context => + }, async context => { - LoadRoot(context); + await LoadRootAsync(context); var loaded1 = context.Set().Single(e => e.Id == old1.Id); var loaded1d = context.Set().Single(e => e.Id == old1d.Id); @@ -233,17 +237,17 @@ public virtual void Save_changed_optional_one_to_one(ChangeMechanism changeMecha [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Fk))] [InlineData((int)(ChangeMechanism.Fk | ChangeMechanism.Dependent))] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk))] - public virtual void Save_required_one_to_one_changed_by_reference(ChangeMechanism changeMechanism) + public virtual async Task Save_required_one_to_one_changed_by_reference(ChangeMechanism changeMechanism) { RequiredSingle1 old1 = null; RequiredSingle2 old2 = null; Root oldRoot; RequiredSingle2 new2 = null; RequiredSingle1 new1 = null; - ExecuteWithStrategyInTransaction( - context => + await ExecuteWithStrategyInTransactionAsync( + async context => { - oldRoot = LoadRoot(context); + oldRoot = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -267,7 +271,7 @@ public virtual void Save_required_one_to_one_changed_by_reference(ChangeMechanis new1 = context.CreateProxy(e => e.Single = new2); }); - ExecuteWithStrategyInTransaction( + await ExecuteWithStrategyInTransactionAsync( context => { var root = context.Set().Include(e => e.RequiredSingle.Single).Single(IsTheRoot); @@ -308,6 +312,7 @@ public virtual void Save_required_one_to_one_changed_by_reference(ChangeMechanis Assert.NotNull(old1.Root); Assert.Same(old1, old2.Back); Assert.Equal(old1.Id, old2.Id); + return Task.CompletedTask; }); } @@ -326,7 +331,7 @@ public virtual void Save_required_one_to_one_changed_by_reference(ChangeMechanis [InlineData((int)(ChangeMechanism.Fk | ChangeMechanism.Dependent), true)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), false)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), true)] - public virtual void Save_required_non_PK_one_to_one_changed_by_reference(ChangeMechanism changeMechanism, bool useExistingEntities) + public virtual Task Save_required_non_PK_one_to_one_changed_by_reference(ChangeMechanism changeMechanism, bool useExistingEntities) { RequiredNonPkSingle2 new2 = null; RequiredNonPkSingle2Derived new2d = null; @@ -342,7 +347,7 @@ public virtual void Save_required_non_PK_one_to_one_changed_by_reference(ChangeM RequiredNonPkSingle2Derived old2d = null; RequiredNonPkSingle2MoreDerived old2dd = null; - ExecuteWithStrategyInTransaction( + return ExecuteWithStrategyInTransactionAsync( context => { new2 = context.CreateProxy(); @@ -375,10 +380,11 @@ public virtual void Save_required_non_PK_one_to_one_changed_by_reference(ChangeM context.AddRange(newRoot, new1, new1d, new1dd, new2, new2d, new2dd); context.SaveChanges(); } - }, - context => + + return Task.CompletedTask; + }, async context => { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -478,10 +484,9 @@ public virtual void Save_required_non_PK_one_to_one_changed_by_reference(ChangeM Assert.Equal(old1.Id, old2.BackId); Assert.Equal(old1d.Id, old2d.BackId); Assert.Equal(old1dd.Id, old2dd.BackId); - }, - context => + }, async context => { - var loadedRoot = LoadRoot(context); + var loadedRoot = await LoadRootAsync(context); Assert.False(context.Set().Any(e => e.Id == old1.Id)); Assert.False(context.Set().Any(e => e.Id == old1d.Id)); @@ -500,15 +505,15 @@ public virtual void Save_required_non_PK_one_to_one_changed_by_reference(ChangeM [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Fk))] [InlineData((int)(ChangeMechanism.Fk | ChangeMechanism.Dependent))] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk))] - public virtual void Sever_optional_one_to_one(ChangeMechanism changeMechanism) + public virtual Task Sever_optional_one_to_one(ChangeMechanism changeMechanism) { Root root; OptionalSingle1 old1 = null; OptionalSingle2 old2 = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - root = LoadRoot(context); + root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -551,12 +556,11 @@ public virtual void Sever_optional_one_to_one(ChangeMechanism changeMechanism) Assert.Same(old1, old2.Back); Assert.Null(old1.RootId); Assert.Equal(old1.Id, old2.BackId); - }, - context => + }, async context => { if ((changeMechanism & ChangeMechanism.Fk) == 0) { - LoadRoot(context); + await LoadRootAsync(context); var loaded1 = context.Set().Single(e => e.Id == old1.Id); var loaded2 = context.Set().Single(e => e.Id == old2.Id); @@ -573,15 +577,15 @@ public virtual void Sever_optional_one_to_one(ChangeMechanism changeMechanism) [InlineData((int)ChangeMechanism.Dependent)] [InlineData((int)ChangeMechanism.Principal)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent))] - public virtual void Sever_required_one_to_one(ChangeMechanism changeMechanism) + public virtual Task Sever_required_one_to_one(ChangeMechanism changeMechanism) { Root root = null; RequiredSingle1 old1 = null; RequiredSingle2 old2 = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - root = LoadRoot(context); + root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -623,10 +627,9 @@ public virtual void Sever_required_one_to_one(ChangeMechanism changeMechanism) Assert.Null(old1.Root); Assert.Null(old2.Back); Assert.Equal(old1.Id, old2.Id); - }, - context => + }, async context => { - LoadRoot(context); + await LoadRootAsync(context); Assert.False(context.Set().Any(e => e.Id == old1.Id)); Assert.False(context.Set().Any(e => e.Id == old2.Id)); @@ -637,15 +640,15 @@ public virtual void Sever_required_one_to_one(ChangeMechanism changeMechanism) [InlineData((int)ChangeMechanism.Dependent)] [InlineData((int)ChangeMechanism.Principal)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent))] - public virtual void Sever_required_non_PK_one_to_one(ChangeMechanism changeMechanism) + public virtual Task Sever_required_non_PK_one_to_one(ChangeMechanism changeMechanism) { Root root; RequiredNonPkSingle1 old1 = null; RequiredNonPkSingle2 old2 = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - root = LoadRoot(context); + root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -687,10 +690,9 @@ public virtual void Sever_required_non_PK_one_to_one(ChangeMechanism changeMecha Assert.Null(old1.Root); Assert.Null(old2.Back); Assert.Equal(old1.Id, old2.BackId); - }, - context => + }, async context => { - LoadRoot(context); + await LoadRootAsync(context); Assert.False(context.Set().Any(e => e.Id == old1.Id)); Assert.False(context.Set().Any(e => e.Id == old2.Id)); @@ -712,14 +714,14 @@ public virtual void Sever_required_non_PK_one_to_one(ChangeMechanism changeMecha [InlineData((int)(ChangeMechanism.Fk | ChangeMechanism.Dependent), true)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), false)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), true)] - public virtual void Reparent_optional_one_to_one(ChangeMechanism changeMechanism, bool useExistingRoot) + public virtual Task Reparent_optional_one_to_one(ChangeMechanism changeMechanism, bool useExistingRoot) { Root newRoot = null; Root root; OptionalSingle1 old1 = null; OptionalSingle2 old2 = null; - ExecuteWithStrategyInTransaction( + return ExecuteWithStrategyInTransactionAsync( context => { newRoot = context.CreateProxy(); @@ -729,10 +731,11 @@ public virtual void Reparent_optional_one_to_one(ChangeMechanism changeMechanism context.AddRange(newRoot); context.SaveChanges(); } - }, - context => + + return Task.CompletedTask; + }, async context => { - root = LoadRoot(context); + root = await LoadRootAsync(context); context.Entry(newRoot).State = useExistingRoot ? EntityState.Unchanged : EntityState.Added; @@ -777,10 +780,9 @@ public virtual void Reparent_optional_one_to_one(ChangeMechanism changeMechanism Assert.Same(old1, old2.Back); Assert.Equal(newRoot.Id, old1.RootId); Assert.Equal(old1.Id, old2.BackId); - }, - context => + }, async context => { - var loadedRoot = LoadRoot(context); + var loadedRoot = await LoadRootAsync(context); newRoot = context.Set().Single(e => e.Id == newRoot.Id); var loaded1 = context.Set().Single(e => e.Id == old1.Id); @@ -808,11 +810,11 @@ public virtual void Reparent_optional_one_to_one(ChangeMechanism changeMechanism [InlineData((int)(ChangeMechanism.Fk | ChangeMechanism.Dependent), true)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), false)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), true)] - public virtual void Reparent_required_one_to_one(ChangeMechanism changeMechanism, bool useExistingRoot) + public virtual Task Reparent_required_one_to_one(ChangeMechanism changeMechanism, bool useExistingRoot) { Root newRoot = null; - ExecuteWithStrategyInTransaction( + return ExecuteWithStrategyInTransactionAsync( context => { newRoot = context.CreateProxy(); @@ -822,10 +824,11 @@ public virtual void Reparent_required_one_to_one(ChangeMechanism changeMechanism context.AddRange(newRoot); context.SaveChanges(); } - }, - context => + + return Task.CompletedTask; + }, async context => { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -876,14 +879,14 @@ public virtual void Reparent_required_one_to_one(ChangeMechanism changeMechanism [InlineData((int)(ChangeMechanism.Fk | ChangeMechanism.Dependent), true)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), false)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), true)] - public virtual void Reparent_required_non_PK_one_to_one(ChangeMechanism changeMechanism, bool useExistingRoot) + public virtual Task Reparent_required_non_PK_one_to_one(ChangeMechanism changeMechanism, bool useExistingRoot) { Root newRoot = null; Root root; RequiredNonPkSingle1 old1 = null; RequiredNonPkSingle2 old2 = null; - ExecuteWithStrategyInTransaction( + return ExecuteWithStrategyInTransactionAsync( context => { newRoot = context.CreateProxy(); @@ -893,10 +896,11 @@ public virtual void Reparent_required_non_PK_one_to_one(ChangeMechanism changeMe context.AddRange(newRoot); context.SaveChanges(); } - }, - context => + + return Task.CompletedTask; + }, async context => { - root = LoadRoot(context); + root = await LoadRootAsync(context); context.Entry(newRoot).State = useExistingRoot ? EntityState.Unchanged : EntityState.Added; @@ -941,10 +945,9 @@ public virtual void Reparent_required_non_PK_one_to_one(ChangeMechanism changeMe Assert.Same(old1, old2.Back); Assert.Equal(newRoot.Id, old1.RootId); Assert.Equal(old1.Id, old2.BackId); - }, - context => + }, async context => { - var loadedRoot = LoadRoot(context); + var loadedRoot = await LoadRootAsync(context); newRoot = context.Set().Single(e => e.Id == newRoot.Id); var loaded1 = context.Set().Single(e => e.Id == old1.Id); @@ -967,20 +970,20 @@ public virtual void Reparent_required_non_PK_one_to_one(ChangeMechanism changeMe [InlineData(CascadeTiming.Never, CascadeTiming.OnSaveChanges)] [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] - public virtual void Optional_one_to_one_are_orphaned( + public virtual Task Optional_one_to_one_are_orphaned( CascadeTiming cascadeDeleteTiming, CascadeTiming deleteOrphansTiming) { var removedId = 0; var orphanedId = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming; - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1016,10 +1019,9 @@ public virtual void Optional_one_to_one_are_orphaned( Assert.Same(root, removed.Root); Assert.Same(orphaned, removed.Single); - }, - context => + }, async context => { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); Assert.Null(root.OptionalSingle); @@ -1038,20 +1040,20 @@ public virtual void Optional_one_to_one_are_orphaned( [InlineData(CascadeTiming.Never, CascadeTiming.OnSaveChanges)] [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] - public virtual void Required_one_to_one_are_cascade_deleted( + public virtual Task Required_one_to_one_are_cascade_deleted( CascadeTiming cascadeDeleteTiming, CascadeTiming deleteOrphansTiming) { var removedId = 0; var orphanedId = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming; - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1094,12 +1096,11 @@ public virtual void Required_one_to_one_are_cascade_deleted( Assert.Same(root, removed.Root); Assert.Same(orphaned, removed.Single); } - }, - context => + }, async context => { if (cascadeDeleteTiming != CascadeTiming.Never) { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1124,20 +1125,20 @@ public virtual void Required_one_to_one_are_cascade_deleted( [InlineData(CascadeTiming.Never, CascadeTiming.OnSaveChanges)] [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] - public virtual void Required_non_PK_one_to_one_are_cascade_deleted( + public virtual Task Required_non_PK_one_to_one_are_cascade_deleted( CascadeTiming cascadeDeleteTiming, CascadeTiming deleteOrphansTiming) { var removedId = 0; var orphanedId = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming; - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1180,12 +1181,11 @@ public virtual void Required_non_PK_one_to_one_are_cascade_deleted( Assert.Same(root, removed.Root); Assert.Same(orphaned, removed.Single); } - }, - context => + }, async context => { if (cascadeDeleteTiming != CascadeTiming.Never) { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1210,17 +1210,17 @@ public virtual void Required_non_PK_one_to_one_are_cascade_deleted( [InlineData(CascadeTiming.Never, CascadeTiming.OnSaveChanges)] [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] - public virtual void Required_one_to_one_are_cascade_deleted_in_store( + public virtual Task Required_one_to_one_are_cascade_deleted_in_store( CascadeTiming cascadeDeleteTiming, CascadeTiming deleteOrphansTiming) { var removedId = 0; var orphanedId = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1282,12 +1282,13 @@ public virtual void Required_one_to_one_are_cascade_deleted_in_store( Assert.Same(root, removed.Root); Assert.Same(orphaned, removed.Single); } - }, - context => + + return Task.CompletedTask; + }, async context => { if (cascadeDeleteTiming != CascadeTiming.Never) { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1312,17 +1313,17 @@ public virtual void Required_one_to_one_are_cascade_deleted_in_store( [InlineData(CascadeTiming.Never, CascadeTiming.OnSaveChanges)] [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] - public virtual void Required_non_PK_one_to_one_are_cascade_deleted_in_store( + public virtual Task Required_non_PK_one_to_one_are_cascade_deleted_in_store( CascadeTiming cascadeDeleteTiming, CascadeTiming deleteOrphansTiming) { var removedId = 0; var orphanedId = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1384,12 +1385,13 @@ public virtual void Required_non_PK_one_to_one_are_cascade_deleted_in_store( Assert.Same(root, removed.Root); Assert.Same(orphaned, removed.Single); } - }, - context => + + return Task.CompletedTask; + }, async context => { if (cascadeDeleteTiming != CascadeTiming.Never) { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1414,17 +1416,17 @@ public virtual void Required_non_PK_one_to_one_are_cascade_deleted_in_store( [InlineData(CascadeTiming.Never, CascadeTiming.OnSaveChanges)] [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] - public virtual void Optional_one_to_one_are_orphaned_in_store( + public virtual Task Optional_one_to_one_are_orphaned_in_store( CascadeTiming cascadeDeleteTiming, CascadeTiming deleteOrphansTiming) { var removedId = 0; var orphanedId = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1474,10 +1476,10 @@ public virtual void Optional_one_to_one_are_orphaned_in_store( Assert.Same(root, removed.Root); Assert.Same(orphaned, removed.Single); - }, - context => + return Task.CompletedTask; + }, async context => { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1501,7 +1503,7 @@ public virtual void Optional_one_to_one_are_orphaned_in_store( [InlineData(CascadeTiming.Never, CascadeTiming.OnSaveChanges)] [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] - public virtual void Optional_one_to_one_are_orphaned_starting_detached( + public virtual Task Optional_one_to_one_are_orphaned_starting_detached( CascadeTiming cascadeDeleteTiming, CascadeTiming deleteOrphansTiming) { @@ -1511,10 +1513,10 @@ public virtual void Optional_one_to_one_are_orphaned_starting_detached( OptionalSingle1 removed = null; OptionalSingle2 orphaned = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - root = LoadRoot(context); + root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1559,10 +1561,10 @@ public virtual void Optional_one_to_one_are_orphaned_starting_detached( Assert.Same(root, removed.Root); Assert.Same(orphaned, removed.Single); - }, - context => + return Task.CompletedTask; + }, async context => { - root = LoadRoot(context); + root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1586,7 +1588,7 @@ public virtual void Optional_one_to_one_are_orphaned_starting_detached( [InlineData(CascadeTiming.Never, CascadeTiming.OnSaveChanges)] [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] - public virtual void Required_one_to_one_are_cascade_deleted_starting_detached( + public virtual Task Required_one_to_one_are_cascade_deleted_starting_detached( CascadeTiming cascadeDeleteTiming, CascadeTiming deleteOrphansTiming) { @@ -1596,10 +1598,10 @@ public virtual void Required_one_to_one_are_cascade_deleted_starting_detached( RequiredSingle1 removed = null; RequiredSingle2 orphaned = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - root = LoadRoot(context); + root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1651,12 +1653,13 @@ public virtual void Required_one_to_one_are_cascade_deleted_starting_detached( Assert.Same(root, removed.Root); Assert.Same(orphaned, removed.Single); } - }, - context => + + return Task.CompletedTask; + }, async context => { if (cascadeDeleteTiming != CascadeTiming.Never) { - root = LoadRoot(context); + root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1681,7 +1684,7 @@ public virtual void Required_one_to_one_are_cascade_deleted_starting_detached( [InlineData(CascadeTiming.Never, CascadeTiming.OnSaveChanges)] [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] - public virtual void Required_non_PK_one_to_one_are_cascade_deleted_starting_detached( + public virtual Task Required_non_PK_one_to_one_are_cascade_deleted_starting_detached( CascadeTiming cascadeDeleteTiming, CascadeTiming deleteOrphansTiming) { @@ -1691,10 +1694,10 @@ public virtual void Required_non_PK_one_to_one_are_cascade_deleted_starting_deta RequiredNonPkSingle1 removed = null; RequiredNonPkSingle2 orphaned = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - root = LoadRoot(context); + root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1746,12 +1749,13 @@ public virtual void Required_non_PK_one_to_one_are_cascade_deleted_starting_deta Assert.Same(root, removed.Root); Assert.Same(orphaned, removed.Single); } - }, - context => + + return Task.CompletedTask; + }, async context => { if (cascadeDeleteTiming != CascadeTiming.Never) { - root = LoadRoot(context); + root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1776,20 +1780,20 @@ public virtual void Required_non_PK_one_to_one_are_cascade_deleted_starting_deta [InlineData(CascadeTiming.Never, CascadeTiming.OnSaveChanges)] [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] - public virtual void Required_one_to_one_are_cascade_detached_when_Added( + public virtual Task Required_one_to_one_are_cascade_detached_when_Added( CascadeTiming cascadeDeleteTiming, CascadeTiming deleteOrphansTiming) { var removedId = 0; var orphanedId = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming; - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1840,12 +1844,11 @@ public virtual void Required_one_to_one_are_cascade_detached_when_Added( Assert.Same(root, removed.Root); Assert.Same(orphaned, removed.Single); } - }, - context => + }, async context => { if (cascadeDeleteTiming != CascadeTiming.Never) { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1870,20 +1873,20 @@ public virtual void Required_one_to_one_are_cascade_detached_when_Added( [InlineData(CascadeTiming.Never, CascadeTiming.OnSaveChanges)] [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] - public virtual void Required_non_PK_one_to_one_are_cascade_detached_when_Added( + public virtual Task Required_non_PK_one_to_one_are_cascade_detached_when_Added( CascadeTiming cascadeDeleteTiming, CascadeTiming deleteOrphansTiming) { var removedId = 0; var orphanedId = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming; - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1934,12 +1937,11 @@ public virtual void Required_non_PK_one_to_one_are_cascade_detached_when_Added( Assert.Same(root, removed.Root); Assert.Same(orphaned, removed.Single); } - }, - context => + }, async context => { if (cascadeDeleteTiming != CascadeTiming.Never) { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { diff --git a/test/EFCore.Specification.Tests/GraphUpdates/ProxyGraphUpdatesTestBaseOneToOneAk.cs b/test/EFCore.Specification.Tests/GraphUpdates/ProxyGraphUpdatesTestBaseOneToOneAk.cs index 06cf919a7f0..6ef5f5f40fd 100644 --- a/test/EFCore.Specification.Tests/GraphUpdates/ProxyGraphUpdatesTestBaseOneToOneAk.cs +++ b/test/EFCore.Specification.Tests/GraphUpdates/ProxyGraphUpdatesTestBaseOneToOneAk.cs @@ -27,7 +27,7 @@ public abstract partial class ProxyGraphUpdatesTestBase : IClassFixtur [InlineData((int)(ChangeMechanism.Fk | ChangeMechanism.Dependent), true)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), false)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), true)] - public virtual void Save_changed_optional_one_to_one_with_alternate_key(ChangeMechanism changeMechanism, bool useExistingEntities) + public virtual Task Save_changed_optional_one_to_one_with_alternate_key(ChangeMechanism changeMechanism, bool useExistingEntities) { OptionalSingleAk2 new2 = null; OptionalSingleAk2Derived new2d = null; @@ -44,7 +44,7 @@ public virtual void Save_changed_optional_one_to_one_with_alternate_key(ChangeMe OptionalSingleAk2Derived old2d = null; OptionalSingleAk2MoreDerived old2dd = null; - ExecuteWithStrategyInTransaction( + return ExecuteWithStrategyInTransactionAsync( context => { new2 = context.CreateProxy(e => e.AlternateId = Guid.NewGuid()); @@ -76,10 +76,11 @@ public virtual void Save_changed_optional_one_to_one_with_alternate_key(ChangeMe context.AddRange(new1, new1d, new1dd, new2, new2d, new2dd, new2c); context.SaveChanges(); } - }, - context => + + return Task.CompletedTask; + }, async context => { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -178,10 +179,9 @@ public virtual void Save_changed_optional_one_to_one_with_alternate_key(ChangeMe Assert.Equal(old1.AlternateId, old2c.ParentAlternateId); Assert.Equal(old1d.AlternateId, old2d.BackId); Assert.Equal(old1dd.AlternateId, old2dd.BackId); - }, - context => + }, async context => { - LoadRoot(context); + await LoadRootAsync(context); var loaded1 = context.Set().Single(e => e.Id == old1.Id); var loaded1d = context.Set().Single(e => e.Id == old1d.Id); @@ -210,7 +210,7 @@ public virtual void Save_changed_optional_one_to_one_with_alternate_key(ChangeMe } [ConditionalFact] - public virtual void Save_changed_optional_one_to_one_with_alternate_key_in_store() + public virtual Task Save_changed_optional_one_to_one_with_alternate_key_in_store() { OptionalSingleAk2 new2; OptionalSingleAk2Derived new2d; @@ -227,8 +227,8 @@ public virtual void Save_changed_optional_one_to_one_with_alternate_key_in_store OptionalSingleAk2Derived old2d = null; OptionalSingleAk2MoreDerived old2dd = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { new2 = context.CreateProxy(e => e.AlternateId = Guid.NewGuid()); new2d = context.CreateProxy(e => e.AlternateId = Guid.NewGuid()); @@ -254,7 +254,7 @@ public virtual void Save_changed_optional_one_to_one_with_alternate_key_in_store e.Single = new2dd; }); - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -373,10 +373,9 @@ public virtual void Save_changed_optional_one_to_one_with_alternate_key_in_store Assert.Equal(old1.AlternateId, old2c.ParentAlternateId); Assert.Equal(old1d.AlternateId, old2d.BackId); Assert.Equal(old1dd.AlternateId, old2dd.BackId); - }, - context => + }, async context => { - LoadRoot(context); + await LoadRootAsync(context); var loaded1 = context.Set().Single(e => e.Id == old1.Id); var loaded1d = context.Set().Single(e => e.Id == old1d.Id); @@ -411,7 +410,7 @@ public virtual void Save_changed_optional_one_to_one_with_alternate_key_in_store [InlineData((int)ChangeMechanism.Principal, true)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent), false)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent), true)] - public virtual void Save_required_one_to_one_changed_by_reference_with_alternate_key( + public virtual Task Save_required_one_to_one_changed_by_reference_with_alternate_key( ChangeMechanism changeMechanism, bool useExistingEntities) { @@ -423,7 +422,7 @@ public virtual void Save_required_one_to_one_changed_by_reference_with_alternate RequiredSingleAk2 old2 = null; RequiredSingleComposite2 old2c = null; - ExecuteWithStrategyInTransaction( + return ExecuteWithStrategyInTransactionAsync( context => { new2 = context.CreateProxy(e => e.AlternateId = Guid.NewGuid()); @@ -447,10 +446,11 @@ public virtual void Save_required_one_to_one_changed_by_reference_with_alternate context.AddRange(newRoot, new1, new2, new2c); context.SaveChanges(); } - }, - context => + + return Task.CompletedTask; + }, async context => { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -514,10 +514,9 @@ public virtual void Save_required_one_to_one_changed_by_reference_with_alternate Assert.Equal(old1.AlternateId, old2.BackId); Assert.Equal(old1.Id, old2c.BackId); Assert.Equal(old1.AlternateId, old2c.BackAlternateId); - }, - context => + }, async context => { - LoadRoot(context); + await LoadRootAsync(context); Assert.False(context.Set().Any(e => e.Id == old1.Id)); Assert.False(context.Set().Any(e => e.Id == old2.Id)); @@ -540,7 +539,7 @@ public virtual void Save_required_one_to_one_changed_by_reference_with_alternate [InlineData((int)(ChangeMechanism.Fk | ChangeMechanism.Dependent), true)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), false)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), true)] - public virtual void Save_required_non_PK_one_to_one_changed_by_reference_with_alternate_key( + public virtual Task Save_required_non_PK_one_to_one_changed_by_reference_with_alternate_key( ChangeMechanism changeMechanism, bool useExistingEntities) { @@ -558,7 +557,7 @@ public virtual void Save_required_non_PK_one_to_one_changed_by_reference_with_al RequiredNonPkSingleAk2Derived old2d = null; RequiredNonPkSingleAk2MoreDerived old2dd = null; - ExecuteWithStrategyInTransaction( + return ExecuteWithStrategyInTransactionAsync( context => { new2 = context.CreateProxy(e => e.AlternateId = Guid.NewGuid()); @@ -599,10 +598,11 @@ public virtual void Save_required_non_PK_one_to_one_changed_by_reference_with_al context.AddRange(newRoot, new1, new1d, new1dd, new2, new2d, new2dd); context.SaveChanges(); } - }, - context => + + return Task.CompletedTask; + }, async context => { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -702,10 +702,9 @@ public virtual void Save_required_non_PK_one_to_one_changed_by_reference_with_al Assert.Equal(old1.AlternateId, old2.BackId); Assert.Equal(old1d.AlternateId, old2d.BackId); Assert.Equal(old1dd.AlternateId, old2dd.BackId); - }, - context => + }, async context => { - var loadedRoot = LoadRoot(context); + var loadedRoot = await LoadRootAsync(context); Assert.False(context.Set().Any(e => e.Id == old1.Id)); Assert.False(context.Set().Any(e => e.Id == old1d.Id)); @@ -724,16 +723,16 @@ public virtual void Save_required_non_PK_one_to_one_changed_by_reference_with_al [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Fk))] [InlineData((int)(ChangeMechanism.Fk | ChangeMechanism.Dependent))] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk))] - public virtual void Sever_optional_one_to_one_with_alternate_key(ChangeMechanism changeMechanism) + public virtual Task Sever_optional_one_to_one_with_alternate_key(ChangeMechanism changeMechanism) { Root root = null; OptionalSingleAk1 old1 = null; OptionalSingleAk2 old2 = null; OptionalSingleComposite2 old2c = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - root = LoadRoot(context); + root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -781,12 +780,11 @@ public virtual void Sever_optional_one_to_one_with_alternate_key(ChangeMechanism Assert.Equal(old1.AlternateId, old2.BackId); Assert.Equal(old1.Id, old2c.BackId); Assert.Equal(old1.AlternateId, old2c.ParentAlternateId); - }, - context => + }, async context => { if ((changeMechanism & ChangeMechanism.Fk) == 0) { - var loadedRoot = LoadRoot(context); + var loadedRoot = await LoadRootAsync(context); var loaded1 = context.Set().Single(e => e.Id == old1.Id); var loaded2 = context.Set().Single(e => e.Id == old2.Id); @@ -807,16 +805,16 @@ public virtual void Sever_optional_one_to_one_with_alternate_key(ChangeMechanism [InlineData((int)ChangeMechanism.Dependent)] [InlineData((int)ChangeMechanism.Principal)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent))] - public virtual void Sever_required_one_to_one_with_alternate_key(ChangeMechanism changeMechanism) + public virtual Task Sever_required_one_to_one_with_alternate_key(ChangeMechanism changeMechanism) { Root root = null; RequiredSingleAk1 old1 = null; RequiredSingleAk2 old2 = null; RequiredSingleComposite2 old2c = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - root = LoadRoot(context); + root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -863,10 +861,9 @@ public virtual void Sever_required_one_to_one_with_alternate_key(ChangeMechanism Assert.Equal(old1.AlternateId, old2.BackId); Assert.Equal(old1.Id, old2c.BackId); Assert.Equal(old1.AlternateId, old2c.BackAlternateId); - }, - context => + }, async context => { - var loadedRoot = LoadRoot(context); + var loadedRoot = await LoadRootAsync(context); Assert.False(context.Set().Any(e => e.Id == old1.Id)); Assert.False(context.Set().Any(e => e.Id == old2.Id)); @@ -878,15 +875,15 @@ public virtual void Sever_required_one_to_one_with_alternate_key(ChangeMechanism [InlineData((int)ChangeMechanism.Dependent)] [InlineData((int)ChangeMechanism.Principal)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent))] - public virtual void Sever_required_non_PK_one_to_one_with_alternate_key(ChangeMechanism changeMechanism) + public virtual Task Sever_required_non_PK_one_to_one_with_alternate_key(ChangeMechanism changeMechanism) { Root root = null; RequiredNonPkSingleAk1 old1 = null; RequiredNonPkSingleAk2 old2 = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - root = LoadRoot(context); + root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -934,10 +931,9 @@ public virtual void Sever_required_non_PK_one_to_one_with_alternate_key(ChangeMe Assert.Null(old1.Root); Assert.Null(old2.Back); Assert.Equal(old1.AlternateId, old2.BackId); - }, - context => + }, async context => { - var loadedRoot = LoadRoot(context); + var loadedRoot = await LoadRootAsync(context); Assert.False(context.Set().Any(e => e.Id == old1.Id)); Assert.False(context.Set().Any(e => e.Id == old2.Id)); @@ -959,7 +955,7 @@ public virtual void Sever_required_non_PK_one_to_one_with_alternate_key(ChangeMe [InlineData((int)(ChangeMechanism.Fk | ChangeMechanism.Dependent), true)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), false)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), true)] - public virtual void Reparent_optional_one_to_one_with_alternate_key(ChangeMechanism changeMechanism, bool useExistingRoot) + public virtual Task Reparent_optional_one_to_one_with_alternate_key(ChangeMechanism changeMechanism, bool useExistingRoot) { Root newRoot = null; Root root; @@ -967,20 +963,19 @@ public virtual void Reparent_optional_one_to_one_with_alternate_key(ChangeMechan OptionalSingleAk2 old2 = null; OptionalSingleComposite2 old2c = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { newRoot = context.CreateProxy(e => e.AlternateId = Guid.NewGuid()); if (useExistingRoot) { context.Add(newRoot); - context.SaveChanges(); + await context.SaveChangesAsync(); } - }, - context => + }, async context => { - root = LoadRoot(context); + root = await LoadRootAsync(context); context.Entry(newRoot).State = useExistingRoot ? EntityState.Unchanged : EntityState.Added; @@ -1030,10 +1025,9 @@ public virtual void Reparent_optional_one_to_one_with_alternate_key(ChangeMechan Assert.Equal(old1.AlternateId, old2.BackId); Assert.Equal(old1.Id, old2c.BackId); Assert.Equal(old1.AlternateId, old2c.ParentAlternateId); - }, - context => + }, async context => { - LoadRoot(context); + await LoadRootAsync(context); newRoot = context.Set().Single(e => e.Id == newRoot.Id); var loaded1 = context.Set().Single(e => e.Id == old1.Id); @@ -1065,7 +1059,7 @@ public virtual void Reparent_optional_one_to_one_with_alternate_key(ChangeMechan [InlineData((int)(ChangeMechanism.Fk | ChangeMechanism.Dependent), true)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), false)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), true)] - public virtual void Reparent_required_one_to_one_with_alternate_key(ChangeMechanism changeMechanism, bool useExistingRoot) + public virtual Task Reparent_required_one_to_one_with_alternate_key(ChangeMechanism changeMechanism, bool useExistingRoot) { Root newRoot = null; Root root; @@ -1073,7 +1067,7 @@ public virtual void Reparent_required_one_to_one_with_alternate_key(ChangeMechan RequiredSingleAk2 old2 = null; RequiredSingleComposite2 old2c = null; - ExecuteWithStrategyInTransaction( + return ExecuteWithStrategyInTransactionAsync( context => { newRoot = context.CreateProxy(e => e.AlternateId = Guid.NewGuid()); @@ -1083,10 +1077,11 @@ public virtual void Reparent_required_one_to_one_with_alternate_key(ChangeMechan context.Add(newRoot); context.SaveChanges(); } - }, - context => + + return Task.CompletedTask; + }, async context => { - root = LoadRoot(context); + root = await LoadRootAsync(context); context.Entry(newRoot).State = useExistingRoot ? EntityState.Unchanged : EntityState.Added; @@ -1136,10 +1131,9 @@ public virtual void Reparent_required_one_to_one_with_alternate_key(ChangeMechan Assert.Equal(old1.AlternateId, old2.BackId); Assert.Equal(old1.Id, old2c.BackId); Assert.Equal(old1.AlternateId, old2c.BackAlternateId); - }, - context => + }, async context => { - var loadedRoot = LoadRoot(context); + var loadedRoot = await LoadRootAsync(context); newRoot = context.Set().Single(e => e.Id == newRoot.Id); var loaded1 = context.Set().Single(e => e.Id == old1.Id); @@ -1171,14 +1165,14 @@ public virtual void Reparent_required_one_to_one_with_alternate_key(ChangeMechan [InlineData((int)(ChangeMechanism.Fk | ChangeMechanism.Dependent), true)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), false)] [InlineData((int)(ChangeMechanism.Principal | ChangeMechanism.Dependent | ChangeMechanism.Fk), true)] - public virtual void Reparent_required_non_PK_one_to_one_with_alternate_key(ChangeMechanism changeMechanism, bool useExistingRoot) + public virtual Task Reparent_required_non_PK_one_to_one_with_alternate_key(ChangeMechanism changeMechanism, bool useExistingRoot) { Root newRoot = null; Root root; RequiredNonPkSingleAk1 old1 = null; RequiredNonPkSingleAk2 old2 = null; - ExecuteWithStrategyInTransaction( + return ExecuteWithStrategyInTransactionAsync( context => { newRoot = context.CreateProxy(e => e.AlternateId = Guid.NewGuid()); @@ -1188,10 +1182,11 @@ public virtual void Reparent_required_non_PK_one_to_one_with_alternate_key(Chang context.Add(newRoot); context.SaveChanges(); } - }, - context => + + return Task.CompletedTask; + }, async context => { - root = LoadRoot(context); + root = await LoadRootAsync(context); context.Entry(newRoot).State = useExistingRoot ? EntityState.Unchanged : EntityState.Added; @@ -1236,10 +1231,9 @@ public virtual void Reparent_required_non_PK_one_to_one_with_alternate_key(Chang Assert.Same(old1, old2.Back); Assert.Equal(newRoot.AlternateId, old1.RootId); Assert.Equal(old1.AlternateId, old2.BackId); - }, - context => + }, async context => { - var loadedRoot = LoadRoot(context); + var loadedRoot = await LoadRootAsync(context); newRoot = context.Set().Single(e => e.Id == newRoot.Id); var loaded1 = context.Set().Single(e => e.Id == old1.Id); @@ -1262,7 +1256,7 @@ public virtual void Reparent_required_non_PK_one_to_one_with_alternate_key(Chang [InlineData(CascadeTiming.Never, CascadeTiming.OnSaveChanges)] [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] - public virtual void Optional_one_to_one_with_alternate_key_are_orphaned( + public virtual Task Optional_one_to_one_with_alternate_key_are_orphaned( CascadeTiming cascadeDeleteTiming, CascadeTiming deleteOrphansTiming) { @@ -1270,13 +1264,13 @@ public virtual void Optional_one_to_one_with_alternate_key_are_orphaned( var orphanedId = 0; var orphanedIdC = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming; - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1317,10 +1311,9 @@ public virtual void Optional_one_to_one_with_alternate_key_are_orphaned( Assert.Same(root, removed.Root); Assert.Same(orphaned, removed.Single); - }, - context => + }, async context => { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1345,7 +1338,7 @@ public virtual void Optional_one_to_one_with_alternate_key_are_orphaned( [InlineData(CascadeTiming.Never, CascadeTiming.OnSaveChanges)] [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] - public virtual void Required_one_to_one_with_alternate_key_are_cascade_deleted( + public virtual Task Required_one_to_one_with_alternate_key_are_cascade_deleted( CascadeTiming cascadeDeleteTiming, CascadeTiming deleteOrphansTiming) { @@ -1353,13 +1346,13 @@ public virtual void Required_one_to_one_with_alternate_key_are_cascade_deleted( var orphanedId = 0; var orphanedIdC = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming; - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1407,12 +1400,11 @@ public virtual void Required_one_to_one_with_alternate_key_are_cascade_deleted( Assert.Same(root, removed.Root); Assert.Same(orphaned, removed.Single); } - }, - context => + }, async context => { if (cascadeDeleteTiming != CascadeTiming.Never) { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1438,20 +1430,20 @@ public virtual void Required_one_to_one_with_alternate_key_are_cascade_deleted( [InlineData(CascadeTiming.Never, CascadeTiming.OnSaveChanges)] [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] - public virtual void Required_non_PK_one_to_one_with_alternate_key_are_cascade_deleted( + public virtual Task Required_non_PK_one_to_one_with_alternate_key_are_cascade_deleted( CascadeTiming cascadeDeleteTiming, CascadeTiming deleteOrphansTiming) { var removedId = 0; var orphanedId = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming; - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1494,12 +1486,11 @@ public virtual void Required_non_PK_one_to_one_with_alternate_key_are_cascade_de Assert.Same(root, removed.Root); Assert.Same(orphaned, removed.Single); } - }, - context => + }, async context => { if (cascadeDeleteTiming != CascadeTiming.Never) { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1524,7 +1515,7 @@ public virtual void Required_non_PK_one_to_one_with_alternate_key_are_cascade_de [InlineData(CascadeTiming.Never, CascadeTiming.OnSaveChanges)] [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] - public virtual void Required_one_to_one_with_alternate_key_are_cascade_deleted_in_store( + public virtual Task Required_one_to_one_with_alternate_key_are_cascade_deleted_in_store( CascadeTiming cascadeDeleteTiming, CascadeTiming deleteOrphansTiming) { @@ -1532,10 +1523,10 @@ public virtual void Required_one_to_one_with_alternate_key_are_cascade_deleted_i var orphanedId = 0; var orphanedIdC = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1553,13 +1544,12 @@ public virtual void Required_one_to_one_with_alternate_key_are_cascade_deleted_i removedId = removed.Id; orphanedId = removed.Single.Id; orphanedIdC = removed.SingleComposite.Id; - }, - context => + }, async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming; - var root = context.Set().Include(e => e.RequiredSingleAk).Single(IsTheRoot); + var root = await context.Set().Include(e => e.RequiredSingleAk).SingleAsync(IsTheRoot); var removed = root.RequiredSingleAk; @@ -1595,12 +1585,11 @@ public virtual void Required_one_to_one_with_alternate_key_are_cascade_deleted_i Assert.Same(root, removed.Root); Assert.Same(orphaned, removed.Single); } - }, - context => + }, async context => { if (cascadeDeleteTiming != CascadeTiming.Never) { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1626,17 +1615,17 @@ public virtual void Required_one_to_one_with_alternate_key_are_cascade_deleted_i [InlineData(CascadeTiming.Never, CascadeTiming.OnSaveChanges)] [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] - public virtual void Required_non_PK_one_to_one_with_alternate_key_are_cascade_deleted_in_store( + public virtual Task Required_non_PK_one_to_one_with_alternate_key_are_cascade_deleted_in_store( CascadeTiming cascadeDeleteTiming, CascadeTiming deleteOrphansTiming) { var removedId = 0; var orphanedId = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1693,12 +1682,13 @@ public virtual void Required_non_PK_one_to_one_with_alternate_key_are_cascade_de Assert.Same(root, removed.Root); Assert.Same(orphaned, removed.Single); } - }, - context => + + return Task.CompletedTask; + }, async context => { if (cascadeDeleteTiming != CascadeTiming.Never) { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1723,7 +1713,7 @@ public virtual void Required_non_PK_one_to_one_with_alternate_key_are_cascade_de [InlineData(CascadeTiming.Never, CascadeTiming.OnSaveChanges)] [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] - public virtual void Optional_one_to_one_with_alternate_key_are_orphaned_in_store( + public virtual Task Optional_one_to_one_with_alternate_key_are_orphaned_in_store( CascadeTiming cascadeDeleteTiming, CascadeTiming deleteOrphansTiming) { @@ -1731,10 +1721,10 @@ public virtual void Optional_one_to_one_with_alternate_key_are_orphaned_in_store var orphanedId = 0; var orphanedIdC = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1791,10 +1781,10 @@ public virtual void Optional_one_to_one_with_alternate_key_are_orphaned_in_store Assert.Same(root, removed.Root); Assert.Same(orphaned, removed.Single); - }, - context => + return Task.CompletedTask; + }, async context => { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1819,7 +1809,7 @@ public virtual void Optional_one_to_one_with_alternate_key_are_orphaned_in_store [InlineData(CascadeTiming.Never, CascadeTiming.OnSaveChanges)] [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] - public virtual void Optional_one_to_one_with_alternate_key_are_orphaned_starting_detached( + public virtual Task Optional_one_to_one_with_alternate_key_are_orphaned_starting_detached( CascadeTiming cascadeDeleteTiming, CascadeTiming deleteOrphansTiming) { @@ -1831,10 +1821,10 @@ public virtual void Optional_one_to_one_with_alternate_key_are_orphaned_starting OptionalSingleAk2 orphaned = null; OptionalSingleComposite2 orphanedC = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - root = LoadRoot(context); + root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1884,10 +1874,10 @@ public virtual void Optional_one_to_one_with_alternate_key_are_orphaned_starting Assert.Same(root, removed.Root); Assert.Same(orphaned, removed.Single); - }, - context => + return Task.CompletedTask; + }, async context => { - root = LoadRoot(context); + root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1912,7 +1902,7 @@ public virtual void Optional_one_to_one_with_alternate_key_are_orphaned_starting [InlineData(CascadeTiming.Never, CascadeTiming.OnSaveChanges)] [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] - public virtual void Required_one_to_one_with_alternate_key_are_cascade_deleted_starting_detached( + public virtual Task Required_one_to_one_with_alternate_key_are_cascade_deleted_starting_detached( CascadeTiming cascadeDeleteTiming, CascadeTiming deleteOrphansTiming) { @@ -1924,10 +1914,10 @@ public virtual void Required_one_to_one_with_alternate_key_are_cascade_deleted_s RequiredSingleAk2 orphaned = null; RequiredSingleComposite2 orphanedC = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - root = LoadRoot(context); + root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -1984,12 +1974,13 @@ public virtual void Required_one_to_one_with_alternate_key_are_cascade_deleted_s Assert.Same(root, removed.Root); Assert.Same(orphaned, removed.Single); } - }, - context => + + return Task.CompletedTask; + }, async context => { if (cascadeDeleteTiming != CascadeTiming.Never) { - root = LoadRoot(context); + root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -2015,7 +2006,7 @@ public virtual void Required_one_to_one_with_alternate_key_are_cascade_deleted_s [InlineData(CascadeTiming.Never, CascadeTiming.OnSaveChanges)] [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] - public virtual void Required_non_PK_one_to_one_with_alternate_key_are_cascade_deleted_starting_detached( + public virtual Task Required_non_PK_one_to_one_with_alternate_key_are_cascade_deleted_starting_detached( CascadeTiming cascadeDeleteTiming, CascadeTiming deleteOrphansTiming) { @@ -2025,10 +2016,10 @@ public virtual void Required_non_PK_one_to_one_with_alternate_key_are_cascade_de RequiredNonPkSingleAk1 removed = null; RequiredNonPkSingleAk2 orphaned = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - root = LoadRoot(context); + root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -2080,12 +2071,13 @@ public virtual void Required_non_PK_one_to_one_with_alternate_key_are_cascade_de Assert.Same(root, removed.Root); Assert.Same(orphaned, removed.Single); } - }, - context => + + return Task.CompletedTask; + }, async context => { if (cascadeDeleteTiming != CascadeTiming.Never) { - root = LoadRoot(context); + root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -2110,7 +2102,7 @@ public virtual void Required_non_PK_one_to_one_with_alternate_key_are_cascade_de [InlineData(CascadeTiming.Never, CascadeTiming.OnSaveChanges)] [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] - public virtual void Required_one_to_one_with_alternate_key_are_cascade_detached_when_Added( + public virtual Task Required_one_to_one_with_alternate_key_are_cascade_detached_when_Added( CascadeTiming cascadeDeleteTiming, CascadeTiming deleteOrphansTiming) { @@ -2118,13 +2110,13 @@ public virtual void Required_one_to_one_with_alternate_key_are_cascade_detached_ var orphanedId = 0; var orphanedIdC = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming; - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -2182,12 +2174,11 @@ public virtual void Required_one_to_one_with_alternate_key_are_cascade_detached_ Assert.Same(root, removed.Root); Assert.Same(orphaned, removed.Single); } - }, - context => + }, async context => { if (cascadeDeleteTiming != CascadeTiming.Never) { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -2213,20 +2204,20 @@ public virtual void Required_one_to_one_with_alternate_key_are_cascade_detached_ [InlineData(CascadeTiming.Never, CascadeTiming.OnSaveChanges)] [InlineData(CascadeTiming.Never, CascadeTiming.Immediate)] [InlineData(CascadeTiming.Never, CascadeTiming.Never)] - public virtual void Required_non_PK_one_to_one_with_alternate_key_are_cascade_detached_when_Added( + public virtual Task Required_non_PK_one_to_one_with_alternate_key_are_cascade_detached_when_Added( CascadeTiming cascadeDeleteTiming, CascadeTiming deleteOrphansTiming) { var removedId = 0; var orphanedId = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming; context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming; - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { @@ -2277,12 +2268,11 @@ public virtual void Required_non_PK_one_to_one_with_alternate_key_are_cascade_de Assert.Same(root, removed.Root); Assert.Same(orphaned, removed.Single); } - }, - context => + }, async context => { if (cascadeDeleteTiming != CascadeTiming.Never) { - var root = LoadRoot(context); + var root = await LoadRootAsync(context); if (!DoesLazyLoading) { diff --git a/test/EFCore.Specification.Tests/InterceptionTestBase.cs b/test/EFCore.Specification.Tests/InterceptionTestBase.cs index 7829ab95d0c..865f83368b3 100644 --- a/test/EFCore.Specification.Tests/InterceptionTestBase.cs +++ b/test/EFCore.Specification.Tests/InterceptionTestBase.cs @@ -50,29 +50,29 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) } } - protected (DbContext, TInterceptor) CreateContext(bool inject = false) + protected async Task<(DbContext, TInterceptor)> CreateContextAsync(bool inject = false) where TInterceptor : class, IInterceptor, new() { var interceptor = new TInterceptor(); - var context = inject ? CreateContext(null, interceptor) : CreateContext(interceptor); + var context = inject ? await CreateContextAsync(null, interceptor) : await CreateContextAsync(interceptor); return (context, interceptor); } - public UniverseContext CreateContext(IInterceptor appInterceptor, params IInterceptor[] injectedInterceptors) - => Seed( + public Task CreateContextAsync(IInterceptor appInterceptor, params IInterceptor[] injectedInterceptors) + => SeedAsync( new UniverseContext( Fixture.CreateOptions( new[] { appInterceptor }, injectedInterceptors))); - public UniverseContext CreateContext( + public Task CreateContextAsync( IEnumerable appInterceptors, IEnumerable injectedInterceptors = null) - => Seed(new UniverseContext(Fixture.CreateOptions(appInterceptors, injectedInterceptors ?? Enumerable.Empty()))); + => SeedAsync(new UniverseContext(Fixture.CreateOptions(appInterceptors, injectedInterceptors ?? Enumerable.Empty()))); - public virtual UniverseContext Seed(UniverseContext context) - => context; + public virtual Task SeedAsync(UniverseContext context) + => Task.FromResult(context); public interface ITestDiagnosticListener : IDisposable { diff --git a/test/EFCore.Specification.Tests/JsonTypesTestBase.cs b/test/EFCore.Specification.Tests/JsonTypesTestBase.cs index 5d50b17214a..3aaa314d8b3 100644 --- a/test/EFCore.Specification.Tests/JsonTypesTestBase.cs +++ b/test/EFCore.Specification.Tests/JsonTypesTestBase.cs @@ -24,7 +24,7 @@ public abstract class JsonTypesTestBase : NonSharedModelTestBase [InlineData(sbyte.MaxValue, """{"Prop":127}""")] [InlineData((sbyte)0, """{"Prop":0}""")] [InlineData((sbyte)1, """{"Prop":1}""")] - public virtual void Can_read_write_sbyte_JSON_values(sbyte value, string json) + public virtual Task Can_read_write_sbyte_JSON_values(sbyte value, string json) => Can_read_and_write_JSON_value(nameof(Int8Type.Int8), value, json); protected class Int8Type @@ -37,7 +37,7 @@ protected class Int8Type [InlineData(short.MaxValue, """{"Prop":32767}""")] [InlineData((short)0, """{"Prop":0}""")] [InlineData((short)1, """{"Prop":1}""")] - public virtual void Can_read_write_short_JSON_values(short value, string json) + public virtual Task Can_read_write_short_JSON_values(short value, string json) => Can_read_and_write_JSON_value(nameof(Int16Type.Int16), value, json); protected class Int16Type @@ -50,7 +50,7 @@ protected class Int16Type [InlineData(int.MaxValue, """{"Prop":2147483647}""")] [InlineData(0, """{"Prop":0}""")] [InlineData(1, """{"Prop":1}""")] - public virtual void Can_read_write_int_JSON_values(int value, string json) + public virtual Task Can_read_write_int_JSON_values(int value, string json) => Can_read_and_write_JSON_value(nameof(Int32Type.Int32), value, json); protected class Int32Type @@ -63,7 +63,7 @@ protected class Int32Type [InlineData(long.MaxValue, """{"Prop":9223372036854775807}""")] [InlineData((long)0, """{"Prop":0}""")] [InlineData((long)1, """{"Prop":1}""")] - public virtual void Can_read_write_long_JSON_values(long value, string json) + public virtual Task Can_read_write_long_JSON_values(long value, string json) => Can_read_and_write_JSON_value(nameof(Int64Type.Int64), value, json); protected class Int64Type @@ -75,7 +75,7 @@ protected class Int64Type [InlineData(byte.MinValue, """{"Prop":0}""")] [InlineData(byte.MaxValue, """{"Prop":255}""")] [InlineData((byte)1, """{"Prop":1}""")] - public virtual void Can_read_write_byte_JSON_values(byte value, string json) + public virtual Task Can_read_write_byte_JSON_values(byte value, string json) => Can_read_and_write_JSON_value(nameof(UInt8Type.UInt8), value, json); protected class UInt8Type @@ -87,7 +87,7 @@ protected class UInt8Type [InlineData(ushort.MinValue, """{"Prop":0}""")] [InlineData(ushort.MaxValue, """{"Prop":65535}""")] [InlineData((ushort)1, """{"Prop":1}""")] - public virtual void Can_read_write_ushort_JSON_values(ushort value, string json) + public virtual Task Can_read_write_ushort_JSON_values(ushort value, string json) => Can_read_and_write_JSON_value(nameof(UInt16Type.UInt16), value, json); protected class UInt16Type @@ -99,7 +99,7 @@ protected class UInt16Type [InlineData(uint.MinValue, """{"Prop":0}""")] [InlineData(uint.MaxValue, """{"Prop":4294967295}""")] [InlineData((uint)1, """{"Prop":1}""")] - public virtual void Can_read_write_uint_JSON_values(uint value, string json) + public virtual Task Can_read_write_uint_JSON_values(uint value, string json) => Can_read_and_write_JSON_value(nameof(UInt32Type.UInt32), value, json); protected class UInt32Type @@ -111,7 +111,7 @@ protected class UInt32Type [InlineData(ulong.MinValue, """{"Prop":0}""")] [InlineData(ulong.MaxValue, """{"Prop":18446744073709551615}""")] [InlineData((ulong)1, """{"Prop":1}""")] - public virtual void Can_read_write_ulong_JSON_values(ulong value, string json) + public virtual Task Can_read_write_ulong_JSON_values(ulong value, string json) => Can_read_and_write_JSON_value(nameof(UInt64Type.UInt64), value, json); protected class UInt64Type @@ -124,7 +124,7 @@ protected class UInt64Type [InlineData(float.MaxValue, """{"Prop":3.4028235E+38}""")] [InlineData((float)0.0, """{"Prop":0}""")] [InlineData((float)1.1, """{"Prop":1.1}""")] - public virtual void Can_read_write_float_JSON_values(float value, string json) + public virtual Task Can_read_write_float_JSON_values(float value, string json) => Can_read_and_write_JSON_value(nameof(FloatType.Float), value, json); protected class FloatType @@ -137,7 +137,7 @@ protected class FloatType [InlineData(double.MaxValue, """{"Prop":1.7976931348623157E+308}""")] [InlineData(0.0, """{"Prop":0}""")] [InlineData(1.1, """{"Prop":1.1}""")] - public virtual void Can_read_write_double_JSON_values(double value, string json) + public virtual Task Can_read_write_double_JSON_values(double value, string json) => Can_read_and_write_JSON_value(nameof(DoubleType.Double), value, json); protected class DoubleType @@ -150,7 +150,7 @@ protected class DoubleType [InlineData("79228162514264337593543950335", """{"Prop":79228162514264337593543950335}""")] [InlineData("0.0", """{"Prop":0.0}""")] [InlineData("1.1", """{"Prop":1.1}""")] - public virtual void Can_read_write_decimal_JSON_values(decimal value, string json) + public virtual Task Can_read_write_decimal_JSON_values(decimal value, string json) => Can_read_and_write_JSON_value(nameof(DecimalType.Decimal), value, json); protected class DecimalType @@ -162,7 +162,7 @@ protected class DecimalType [InlineData("1/1/0001", """{"Prop":"0001-01-01"}""")] [InlineData("12/31/9999", """{"Prop":"9999-12-31"}""")] [InlineData("5/29/2023", """{"Prop":"2023-05-29"}""")] - public virtual void Can_read_write_DateOnly_JSON_values(string value, string json) + public virtual Task Can_read_write_DateOnly_JSON_values(string value, string json) => Can_read_and_write_JSON_value( nameof(DateOnlyType.DateOnly), DateOnly.Parse(value, CultureInfo.InvariantCulture), json); @@ -176,7 +176,7 @@ protected class DateOnlyType [InlineData("00:00:00.0000000", """{"Prop":"00:00:00.0000000"}""")] [InlineData("23:59:59.9999999", """{"Prop":"23:59:59.9999999"}""")] [InlineData("11:05:12.3456789", """{"Prop":"11:05:12.3456789"}""")] - public virtual void Can_read_write_TimeOnly_JSON_values(string value, string json) + public virtual Task Can_read_write_TimeOnly_JSON_values(string value, string json) => Can_read_and_write_JSON_value( nameof(TimeOnlyType.TimeOnly), TimeOnly.Parse(value, CultureInfo.InvariantCulture), json); @@ -190,7 +190,7 @@ protected class TimeOnlyType [InlineData("0001-01-01T00:00:00.0000000", """{"Prop":"0001-01-01T00:00:00"}""")] [InlineData("9999-12-31T23:59:59.9999999", """{"Prop":"9999-12-31T23:59:59.9999999"}""")] [InlineData("2023-05-29T10:52:47.2064353", """{"Prop":"2023-05-29T10:52:47.2064353"}""")] - public virtual void Can_read_write_DateTime_JSON_values(string value, string json) + public virtual Task Can_read_write_DateTime_JSON_values(string value, string json) => Can_read_and_write_JSON_value( nameof(DateTimeType.DateTime), DateTime.Parse(value, CultureInfo.InvariantCulture), json); @@ -205,7 +205,7 @@ protected class DateTimeType [InlineData("9999-12-31T23:59:59.9999999+02:00", """{"Prop":"9999-12-31T23:59:59.9999999+02:00"}""")] [InlineData("0001-01-01T00:00:00.0000000-03:00", """{"Prop":"0001-01-01T00:00:00-03:00"}""")] [InlineData("2023-05-29T11:11:15.5672854+04:00", """{"Prop":"2023-05-29T11:11:15.5672854+04:00"}""")] - public virtual void Can_read_write_DateTimeOffset_JSON_values(string value, string json) + public virtual Task Can_read_write_DateTimeOffset_JSON_values(string value, string json) => Can_read_and_write_JSON_value( nameof(DateTimeOffsetType.DateTimeOffset), DateTimeOffset.Parse(value, CultureInfo.InvariantCulture), json); @@ -220,7 +220,7 @@ protected class DateTimeOffsetType [InlineData("10675199.02:48:05.4775807", """{"Prop":"10675199:2:48:05.4775807"}""")] [InlineData("00:00:00", """{"Prop":"0:00:00"}""")] [InlineData("12:23:23.8018854", """{"Prop":"12:23:23.8018854"}""")] - public virtual void Can_read_write_TimeSpan_JSON_values(string value, string json) + public virtual Task Can_read_write_TimeSpan_JSON_values(string value, string json) => Can_read_and_write_JSON_value( nameof(TimeSpanType.TimeSpan), TimeSpan.Parse(value), json); @@ -233,7 +233,7 @@ protected class TimeSpanType [ConditionalTheory] [InlineData(false, """{"Prop":false}""")] [InlineData(true, """{"Prop":true}""")] - public virtual void Can_read_write_bool_JSON_values(bool value, string json) + public virtual Task Can_read_write_bool_JSON_values(bool value, string json) => Can_read_and_write_JSON_value(nameof(BooleanType.Boolean), value, json); protected class BooleanType @@ -246,7 +246,7 @@ protected class BooleanType [InlineData(char.MaxValue, """{"Prop":"\uFFFF"}""")] [InlineData(' ', """{"Prop":" "}""")] [InlineData("Z", """{"Prop":"Z"}""")] - public virtual void Can_read_write_char_JSON_values(char value, string json) + public virtual Task Can_read_write_char_JSON_values(char value, string json) => Can_read_and_write_JSON_value(nameof(CharacterType.Character), value, json); protected class CharacterType @@ -258,7 +258,7 @@ protected class CharacterType [InlineData("00000000-0000-0000-0000-000000000000", """{"Prop":"00000000-0000-0000-0000-000000000000"}""")] [InlineData("FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF", """{"Prop":"ffffffff-ffff-ffff-ffff-ffffffffffff"}""")] [InlineData("8C44242F-8E3F-4A20-8BE8-98C7C1AADEBD", """{"Prop":"8c44242f-8e3f-4a20-8be8-98c7c1aadebd"}""")] - public virtual void Can_read_write_GUID_JSON_values(Guid value, string json) + public virtual Task Can_read_write_GUID_JSON_values(Guid value, string json) => Can_read_and_write_JSON_value(nameof(GuidType.Guid), value, json); protected class GuidType @@ -273,7 +273,7 @@ protected class GuidType [InlineData( "❤❥웃유♋☮✌☏☢☠✔☑♚▲♪฿Ɖ⛏♥❣♂♀☿👍✍✉☣☤✘☒♛▼♫⌘⌛¡♡ღツ☼☁❅♾️✎©®™Σ✪✯☭➳Ⓐ✞℃℉°✿⚡☃☂✄¢€£∞✫★½☯✡☪", @"{""Prop"":""\u2764\u2765\uC6C3\uC720\u264B\u262E\u270C\u260F\u2622\u2620\u2714\u2611\u265A\u25B2\u266A\u0E3F\u0189\u26CF\u2665\u2763\u2642\u2640\u263F\uD83D\uDC4D\u270D\u2709\u2623\u2624\u2718\u2612\u265B\u25BC\u266B\u2318\u231B\u00A1\u2661\u10E6\u30C4\u263C\u2601\u2745\u267E\uFE0F\u270E\u00A9\u00AE\u2122\u03A3\u272A\u272F\u262D\u27B3\u24B6\u271E\u2103\u2109\u00B0\u273F\u26A1\u2603\u2602\u2704\u00A2\u20AC\u00A3\u221E\u272B\u2605\u00BD\u262F\u2721\u262A""}")] - public virtual void Can_read_write_string_JSON_values(string value, string json) + public virtual Task Can_read_write_string_JSON_values(string value, string json) => Can_read_and_write_JSON_value(nameof(StringType.String), value, json); protected class StringType @@ -286,7 +286,7 @@ protected class StringType [InlineData("255,255,255,255", """{"Prop":"/////w=="}""")] [InlineData("", """{"Prop":""}""")] [InlineData("1,2,3,4", """{"Prop":"AQIDBA=="}""")] - public virtual void Can_read_write_binary_JSON_values(string value, string json) + public virtual Task Can_read_write_binary_JSON_values(string value, string json) => Can_read_and_write_JSON_value( nameof(BytesType.Bytes), value == "" ? [] : value.Split(',').Select(e => byte.Parse(e)).ToArray(), json); @@ -301,7 +301,7 @@ protected class BytesType "https://user:password@www.contoso.com:80/Home/Index.htm?q1=v1&q2=v2#FragmentName", """{"Prop":"https://user:password@www.contoso.com:80/Home/Index.htm?q1=v1\u0026q2=v2#FragmentName"}""")] [InlineData("file:///C:/test/path/file.txt", """{"Prop":"file:///C:/test/path/file.txt"}""")] - public virtual void Can_read_write_URI_JSON_values(string value, string json) + public virtual Task Can_read_write_URI_JSON_values(string value, string json) => Can_read_and_write_JSON_value(nameof(UriType.Uri), new Uri(value), json); protected class UriType @@ -317,7 +317,7 @@ protected class UriType [InlineData("::1", """{"Prop":"::1"}""")] [InlineData("::", """{"Prop":"::"}""")] [InlineData("2a00:23c7:c60f:4f01:ba43:6d5a:e648:7577", """{"Prop":"2a00:23c7:c60f:4f01:ba43:6d5a:e648:7577"}""")] - public virtual void Can_read_write_IP_address_JSON_values(string value, string json) + public virtual Task Can_read_write_IP_address_JSON_values(string value, string json) => Can_read_and_write_JSON_value(nameof(IPAddressType.IpAddress), IPAddress.Parse(value), json); protected class IPAddressType @@ -329,7 +329,7 @@ protected class IPAddressType [InlineData("001122334455", """{"Prop":"001122334455"}""")] [InlineData("00-11-22-33-44-55", """{"Prop":"001122334455"}""")] [InlineData("0011.2233.4455", """{"Prop":"001122334455"}""")] - public virtual void Can_read_write_physical_address_JSON_values(string value, string json) + public virtual Task Can_read_write_physical_address_JSON_values(string value, string json) => Can_read_and_write_JSON_value( nameof(PhysicalAddressType.PhysicalAddress), PhysicalAddress.Parse(value), json); @@ -344,7 +344,7 @@ protected class PhysicalAddressType [InlineData((sbyte)Enum8.Max, """{"Prop":127}""")] [InlineData((sbyte)Enum8.Default, """{"Prop":0}""")] [InlineData((sbyte)Enum8.One, """{"Prop":1}""")] - public virtual void Can_read_write_sbyte_enum_JSON_values(Enum8 value, string json) + public virtual Task Can_read_write_sbyte_enum_JSON_values(Enum8 value, string json) => Can_read_and_write_JSON_value(nameof(Enum8Type.Enum8), value, json); protected class Enum8Type @@ -357,7 +357,7 @@ protected class Enum8Type [InlineData((short)Enum16.Max, """{"Prop":32767}""")] [InlineData((short)Enum16.Default, """{"Prop":0}""")] [InlineData((short)Enum16.One, """{"Prop":1}""")] - public virtual void Can_read_write_short_enum_JSON_values(Enum16 value, string json) + public virtual Task Can_read_write_short_enum_JSON_values(Enum16 value, string json) => Can_read_and_write_JSON_value(nameof(Enum16Type.Enum16), value, json); protected class Enum16Type @@ -370,7 +370,7 @@ protected class Enum16Type [InlineData((int)Enum32.Max, """{"Prop":2147483647}""")] [InlineData((int)Enum32.Default, """{"Prop":0}""")] [InlineData((int)Enum32.One, """{"Prop":1}""")] - public virtual void Can_read_write_int_enum_JSON_values(Enum32 value, string json) + public virtual Task Can_read_write_int_enum_JSON_values(Enum32 value, string json) => Can_read_and_write_JSON_value(nameof(Enum32Type.Enum32), value, json); protected class Enum32Type @@ -383,7 +383,7 @@ protected class Enum32Type [InlineData((long)Enum64.Max, """{"Prop":9223372036854775807}""")] [InlineData((long)Enum64.Default, """{"Prop":0}""")] [InlineData((long)Enum64.One, """{"Prop":1}""")] - public virtual void Can_read_write_long_enum_JSON_values(Enum64 value, string json) + public virtual Task Can_read_write_long_enum_JSON_values(Enum64 value, string json) => Can_read_and_write_JSON_value(nameof(Enum64Type.Enum64), value, json); protected class Enum64Type @@ -395,7 +395,7 @@ protected class Enum64Type [InlineData((byte)EnumU8.Min, """{"Prop":0}""")] [InlineData((byte)EnumU8.Max, """{"Prop":255}""")] [InlineData((byte)EnumU8.One, """{"Prop":1}""")] - public virtual void Can_read_write_byte_enum_JSON_values(EnumU8 value, string json) + public virtual Task Can_read_write_byte_enum_JSON_values(EnumU8 value, string json) => Can_read_and_write_JSON_value(nameof(EnumU8Type.EnumU8), value, json); protected class EnumU8Type @@ -407,7 +407,7 @@ protected class EnumU8Type [InlineData((ushort)EnumU16.Min, """{"Prop":0}""")] [InlineData((ushort)EnumU16.Max, """{"Prop":65535}""")] [InlineData((ushort)EnumU16.One, """{"Prop":1}""")] - public virtual void Can_read_write_ushort_enum_JSON_values(EnumU16 value, string json) + public virtual Task Can_read_write_ushort_enum_JSON_values(EnumU16 value, string json) => Can_read_and_write_JSON_value(nameof(EnumU16Type.EnumU16), value, json); protected class EnumU16Type @@ -419,7 +419,7 @@ protected class EnumU16Type [InlineData((uint)EnumU32.Min, """{"Prop":0}""")] [InlineData((uint)EnumU32.Max, """{"Prop":4294967295}""")] [InlineData((uint)EnumU32.One, """{"Prop":1}""")] - public virtual void Can_read_write_uint_enum_JSON_values(EnumU32 value, string json) + public virtual Task Can_read_write_uint_enum_JSON_values(EnumU32 value, string json) => Can_read_and_write_JSON_value(nameof(EnumU32Type.EnumU32), value, json); protected class EnumU32Type @@ -431,7 +431,7 @@ protected class EnumU32Type [InlineData((ulong)EnumU64.Min, """{"Prop":0}""")] [InlineData((ulong)EnumU64.Max, """{"Prop":18446744073709551615}""")] [InlineData((ulong)EnumU64.One, """{"Prop":1}""")] - public virtual void Can_read_write_ulong_enum_JSON_values(EnumU64 value, string json) + public virtual Task Can_read_write_ulong_enum_JSON_values(EnumU64 value, string json) => Can_read_and_write_JSON_value(nameof(EnumU64Type.EnumU64), value, json); protected class EnumU64Type @@ -445,7 +445,7 @@ protected class EnumU64Type [InlineData((sbyte)0, """{"Prop":0}""")] [InlineData((sbyte)1, """{"Prop":1}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_sbyte_JSON_values(sbyte? value, string json) + public virtual Task Can_read_write_nullable_sbyte_JSON_values(sbyte? value, string json) => Can_read_and_write_JSON_value(nameof(NullableInt8Type.Int8), value, json); protected class NullableInt8Type @@ -459,7 +459,7 @@ protected class NullableInt8Type [InlineData((short)0, """{"Prop":0}""")] [InlineData((short)1, """{"Prop":1}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_short_JSON_values(short? value, string json) + public virtual Task Can_read_write_nullable_short_JSON_values(short? value, string json) => Can_read_and_write_JSON_value(nameof(NullableInt16Type.Int16), value, json); protected class NullableInt16Type @@ -473,7 +473,7 @@ protected class NullableInt16Type [InlineData(0, """{"Prop":0}""")] [InlineData(1, """{"Prop":1}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_int_JSON_values(int? value, string json) + public virtual Task Can_read_write_nullable_int_JSON_values(int? value, string json) => Can_read_and_write_JSON_value(nameof(NullableInt32Type.Int32), value, json); protected class NullableInt32Type @@ -487,7 +487,7 @@ protected class NullableInt32Type [InlineData((long)0, """{"Prop":0}""")] [InlineData((long)1, """{"Prop":1}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_long_JSON_values(long? value, string json) + public virtual Task Can_read_write_nullable_long_JSON_values(long? value, string json) => Can_read_and_write_JSON_value(nameof(NullableInt64Type.Int64), value, json); protected class NullableInt64Type @@ -500,7 +500,7 @@ protected class NullableInt64Type [InlineData(byte.MaxValue, """{"Prop":255}""")] [InlineData((byte)1, """{"Prop":1}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_byte_JSON_values(byte? value, string json) + public virtual Task Can_read_write_nullable_byte_JSON_values(byte? value, string json) => Can_read_and_write_JSON_value(nameof(NullableUInt8Type.UInt8), value, json); protected class NullableUInt8Type @@ -513,7 +513,7 @@ protected class NullableUInt8Type [InlineData(ushort.MaxValue, """{"Prop":65535}""")] [InlineData((ushort)1, """{"Prop":1}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_ushort_JSON_values(ushort? value, string json) + public virtual Task Can_read_write_nullable_ushort_JSON_values(ushort? value, string json) => Can_read_and_write_JSON_value(nameof(NullableUInt16Type.UInt16), value, json); protected class NullableUInt16Type @@ -526,7 +526,7 @@ protected class NullableUInt16Type [InlineData(uint.MaxValue, """{"Prop":4294967295}""")] [InlineData((uint)1, """{"Prop":1}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_uint_JSON_values(uint? value, string json) + public virtual Task Can_read_write_nullable_uint_JSON_values(uint? value, string json) => Can_read_and_write_JSON_value(nameof(NullableUInt32Type.UInt32), value, json); protected class NullableUInt32Type @@ -539,7 +539,7 @@ protected class NullableUInt32Type [InlineData(ulong.MaxValue, """{"Prop":18446744073709551615}""")] [InlineData((ulong)1, """{"Prop":1}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_ulong_JSON_values(ulong? value, string json) + public virtual Task Can_read_write_nullable_ulong_JSON_values(ulong? value, string json) => Can_read_and_write_JSON_value(nameof(NullableUInt64Type.UInt64), value, json); protected class NullableUInt64Type @@ -553,7 +553,7 @@ protected class NullableUInt64Type [InlineData((float)0.0, """{"Prop":0}""")] [InlineData((float)1.1, """{"Prop":1.1}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_float_JSON_values(float? value, string json) + public virtual Task Can_read_write_nullable_float_JSON_values(float? value, string json) => Can_read_and_write_JSON_value(nameof(NullableFloatType.Float), value, json); protected class NullableFloatType @@ -567,7 +567,7 @@ protected class NullableFloatType [InlineData(0.0, """{"Prop":0}""")] [InlineData(1.1, """{"Prop":1.1}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_double_JSON_values(double? value, string json) + public virtual Task Can_read_write_nullable_double_JSON_values(double? value, string json) => Can_read_and_write_JSON_value(nameof(NullableDoubleType.Double), value, json); protected class NullableDoubleType @@ -581,7 +581,7 @@ protected class NullableDoubleType [InlineData("0.0", """{"Prop":0.0}""")] [InlineData("1.1", """{"Prop":1.1}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_decimal_JSON_values(string? value, string json) + public virtual Task Can_read_write_nullable_decimal_JSON_values(string? value, string json) => Can_read_and_write_JSON_value( nameof(NullableDecimalType.Decimal), value == null ? default(decimal?) : decimal.Parse(value, CultureInfo.InvariantCulture), json); @@ -596,7 +596,7 @@ protected class NullableDecimalType [InlineData("12/31/9999", """{"Prop":"9999-12-31"}""")] [InlineData("5/29/2023", """{"Prop":"2023-05-29"}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_DateOnly_JSON_values(string? value, string json) + public virtual Task Can_read_write_nullable_DateOnly_JSON_values(string? value, string json) => Can_read_and_write_JSON_value( nameof(NullableDateOnlyType.DateOnly), value == null ? default(DateOnly?) : DateOnly.Parse(value, CultureInfo.InvariantCulture), json); @@ -611,7 +611,7 @@ protected class NullableDateOnlyType [InlineData("23:59:59.9999999", """{"Prop":"23:59:59.9999999"}""")] [InlineData("11:05:12.3456789", """{"Prop":"11:05:12.3456789"}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_TimeOnly_JSON_values(string? value, string json) + public virtual Task Can_read_write_nullable_TimeOnly_JSON_values(string? value, string json) => Can_read_and_write_JSON_value( nameof(NullableTimeOnlyType.TimeOnly), value == null ? default(TimeOnly?) : TimeOnly.Parse(value, CultureInfo.InvariantCulture), json); @@ -626,7 +626,7 @@ protected class NullableTimeOnlyType [InlineData("9999-12-31T23:59:59.9999999", """{"Prop":"9999-12-31T23:59:59.9999999"}""")] [InlineData("2023-05-29T10:52:47.2064353", """{"Prop":"2023-05-29T10:52:47.2064353"}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_DateTime_JSON_values(string? value, string json) + public virtual Task Can_read_write_nullable_DateTime_JSON_values(string? value, string json) => Can_read_and_write_JSON_value( nameof(NullableDateTimeType.DateTime), value == null ? default(DateTime?) : DateTime.Parse(value, CultureInfo.InvariantCulture), json); @@ -642,7 +642,7 @@ protected class NullableDateTimeType [InlineData("0001-01-01T00:00:00.0000000-03:00", """{"Prop":"0001-01-01T00:00:00-03:00"}""")] [InlineData("2023-05-29T11:11:15.5672854+04:00", """{"Prop":"2023-05-29T11:11:15.5672854+04:00"}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_DateTimeOffset_JSON_values(string? value, string json) + public virtual Task Can_read_write_nullable_DateTimeOffset_JSON_values(string? value, string json) => Can_read_and_write_JSON_value( nameof(NullableDateTimeOffsetType.DateTimeOffset), value == null ? default(DateTimeOffset?) : DateTimeOffset.Parse(value, CultureInfo.InvariantCulture), json); @@ -658,7 +658,7 @@ protected class NullableDateTimeOffsetType [InlineData("00:00:00", """{"Prop":"0:00:00"}""")] [InlineData("12:23:23.8018854", """{"Prop":"12:23:23.8018854"}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_TimeSpan_JSON_values(string? value, string json) + public virtual Task Can_read_write_nullable_TimeSpan_JSON_values(string? value, string json) => Can_read_and_write_JSON_value( nameof(NullableTimeSpanType.TimeSpan), value == null ? default(TimeSpan?) : TimeSpan.Parse(value), json); @@ -672,7 +672,7 @@ protected class NullableTimeSpanType [InlineData(false, """{"Prop":false}""")] [InlineData(true, """{"Prop":true}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_bool_JSON_values(bool? value, string json) + public virtual Task Can_read_write_nullable_bool_JSON_values(bool? value, string json) => Can_read_and_write_JSON_value(nameof(NullableBooleanType.Boolean), value, json); protected class NullableBooleanType @@ -686,7 +686,7 @@ protected class NullableBooleanType [InlineData(' ', """{"Prop":" "}""")] [InlineData('Z', """{"Prop":"Z"}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_char_JSON_values(char? value, string json) + public virtual Task Can_read_write_nullable_char_JSON_values(char? value, string json) => Can_read_and_write_JSON_value(nameof(NullableCharacterType.Character), value, json); protected class NullableCharacterType @@ -699,7 +699,7 @@ protected class NullableCharacterType [InlineData("FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF", """{"Prop":"ffffffff-ffff-ffff-ffff-ffffffffffff"}""")] [InlineData("8C44242F-8E3F-4A20-8BE8-98C7C1AADEBD", """{"Prop":"8c44242f-8e3f-4a20-8be8-98c7c1aadebd"}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_GUID_JSON_values(string? value, string json) + public virtual Task Can_read_write_nullable_GUID_JSON_values(string? value, string json) => Can_read_and_write_JSON_value( nameof(NullableGuidType.Guid), value == null ? null : Guid.Parse(value, CultureInfo.InvariantCulture), json); @@ -717,7 +717,7 @@ protected class NullableGuidType "❤❥웃유♋☮✌☏☢☠✔☑♚▲♪฿Ɖ⛏♥❣♂♀☿👍✍✉☣☤✘☒♛▼♫⌘⌛¡♡ღツ☼☁❅♾️✎©®™Σ✪✯☭➳Ⓐ✞℃℉°✿⚡☃☂✄¢€£∞✫★½☯✡☪", @"{""Prop"":""\u2764\u2765\uC6C3\uC720\u264B\u262E\u270C\u260F\u2622\u2620\u2714\u2611\u265A\u25B2\u266A\u0E3F\u0189\u26CF\u2665\u2763\u2642\u2640\u263F\uD83D\uDC4D\u270D\u2709\u2623\u2624\u2718\u2612\u265B\u25BC\u266B\u2318\u231B\u00A1\u2661\u10E6\u30C4\u263C\u2601\u2745\u267E\uFE0F\u270E\u00A9\u00AE\u2122\u03A3\u272A\u272F\u262D\u27B3\u24B6\u271E\u2103\u2109\u00B0\u273F\u26A1\u2603\u2602\u2704\u00A2\u20AC\u00A3\u221E\u272B\u2605\u00BD\u262F\u2721\u262A""}")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_string_JSON_values(string? value, string json) + public virtual Task Can_read_write_nullable_string_JSON_values(string? value, string json) => Can_read_and_write_JSON_value(nameof(NullableStringType.String), value, json); protected class NullableStringType @@ -731,7 +731,7 @@ protected class NullableStringType [InlineData("", """{"Prop":""}""")] [InlineData("1,2,3,4", """{"Prop":"AQIDBA=="}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_binary_JSON_values(string? value, string json) + public virtual Task Can_read_write_nullable_binary_JSON_values(string? value, string json) => Can_read_and_write_JSON_value( nameof(NullableBytesType.Bytes), value == null @@ -751,7 +751,7 @@ protected class NullableBytesType """{"Prop":"https://user:password@www.contoso.com:80/Home/Index.htm?q1=v1\u0026q2=v2#FragmentName"}""")] [InlineData("file:///C:/test/path/file.txt", """{"Prop":"file:///C:/test/path/file.txt"}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_URI_JSON_values(string? value, string json) + public virtual Task Can_read_write_nullable_URI_JSON_values(string? value, string json) => Can_read_and_write_JSON_value( nameof(NullableUriType.Uri), value == null ? default : new Uri(value), json); @@ -770,7 +770,7 @@ protected class NullableUriType [InlineData("::", """{"Prop":"::"}""")] [InlineData("2a00:23c7:c60f:4f01:ba43:6d5a:e648:7577", """{"Prop":"2a00:23c7:c60f:4f01:ba43:6d5a:e648:7577"}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_IP_address_JSON_values(string? value, string json) + public virtual Task Can_read_write_nullable_IP_address_JSON_values(string? value, string json) => Can_read_and_write_JSON_value( nameof(NullableIPAddressType.IpAddress), value == null ? default : IPAddress.Parse(value), json); @@ -785,7 +785,7 @@ protected class NullableIPAddressType [InlineData("00-11-22-33-44-55", """{"Prop":"001122334455"}""")] [InlineData("0011.2233.4455", """{"Prop":"001122334455"}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_physical_address_JSON_values(string? value, string json) + public virtual Task Can_read_write_nullable_physical_address_JSON_values(string? value, string json) => Can_read_and_write_JSON_value( nameof(NullablePhysicalAddressType.PhysicalAddress), value == null ? default : PhysicalAddress.Parse(value), json); @@ -801,7 +801,7 @@ protected class NullablePhysicalAddressType [InlineData((sbyte)Enum8.Default, """{"Prop":0}""")] [InlineData((sbyte)Enum8.One, """{"Prop":1}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_sbyte_enum_JSON_values(object? value, string json) + public virtual Task Can_read_write_nullable_sbyte_enum_JSON_values(object? value, string json) => Can_read_and_write_JSON_value( nameof(NullableEnum8Type.Enum8), value == null ? default(Enum8?) : (Enum8)value, json); @@ -817,7 +817,7 @@ protected class NullableEnum8Type [InlineData((short)Enum16.Default, """{"Prop":0}""")] [InlineData((short)Enum16.One, """{"Prop":1}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_short_enum_JSON_values(object? value, string json) + public virtual Task Can_read_write_nullable_short_enum_JSON_values(object? value, string json) => Can_read_and_write_JSON_value( nameof(NullableEnum16Type.Enum16), value == null ? default(Enum16?) : (Enum16)value, json); @@ -833,7 +833,7 @@ protected class NullableEnum16Type [InlineData((int)Enum32.Default, """{"Prop":0}""")] [InlineData((int)Enum32.One, """{"Prop":1}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_int_enum_JSON_values(object? value, string json) + public virtual Task Can_read_write_nullable_int_enum_JSON_values(object? value, string json) => Can_read_and_write_JSON_value( nameof(NullableEnum32Type.Enum32), value == null ? default(Enum32?) : (Enum32)value, json); @@ -849,7 +849,7 @@ protected class NullableEnum32Type [InlineData((long)Enum64.Default, """{"Prop":0}""")] [InlineData((long)Enum64.One, """{"Prop":1}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_long_enum_JSON_values(object? value, string json) + public virtual Task Can_read_write_nullable_long_enum_JSON_values(object? value, string json) => Can_read_and_write_JSON_value( nameof(NullableEnum64Type.Enum64), value == null ? default(Enum64?) : (Enum64)value, json); @@ -864,7 +864,7 @@ protected class NullableEnum64Type [InlineData((byte)EnumU8.Max, """{"Prop":255}""")] [InlineData((byte)EnumU8.One, """{"Prop":1}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_byte_enum_JSON_values(object? value, string json) + public virtual Task Can_read_write_nullable_byte_enum_JSON_values(object? value, string json) => Can_read_and_write_JSON_value( nameof(NullableEnumU8Type.EnumU8), value == null ? default(EnumU8?) : (EnumU8)value, json); @@ -879,7 +879,7 @@ protected class NullableEnumU8Type [InlineData((ushort)EnumU16.Max, """{"Prop":65535}""")] [InlineData((ushort)EnumU16.One, """{"Prop":1}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_ushort_enum_JSON_values(object? value, string json) + public virtual Task Can_read_write_nullable_ushort_enum_JSON_values(object? value, string json) => Can_read_and_write_JSON_value( nameof(NullableEnumU16Type.EnumU16), value == null ? default(EnumU16?) : (EnumU16)value, json); @@ -894,7 +894,7 @@ protected class NullableEnumU16Type [InlineData((uint)EnumU32.Max, """{"Prop":4294967295}""")] [InlineData((uint)EnumU32.One, """{"Prop":1}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_uint_enum_JSON_values(object? value, string json) + public virtual Task Can_read_write_nullable_uint_enum_JSON_values(object? value, string json) => Can_read_and_write_JSON_value( nameof(NullableEnumU32Type.EnumU32), value == null ? default(EnumU32?) : (EnumU32)value, json); @@ -909,7 +909,7 @@ protected class NullableEnumU32Type [InlineData((ulong)EnumU64.Max, """{"Prop":18446744073709551615}""")] [InlineData((ulong)EnumU64.One, """{"Prop":1}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_ulong_enum_JSON_values(object? value, string json) + public virtual Task Can_read_write_nullable_ulong_enum_JSON_values(object? value, string json) => Can_read_and_write_JSON_value( nameof(NullableEnumU64Type.EnumU64), value == null ? default(EnumU64?) : (EnumU64)value, json); @@ -925,7 +925,7 @@ protected class NullableEnumU64Type [InlineData((sbyte)0, """{"Prop":"0"}""")] [InlineData((sbyte)1, """{"Prop":"1"}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_sbyte_as_string_JSON_values(sbyte? value, string json) + public virtual Task Can_read_write_nullable_sbyte_as_string_JSON_values(sbyte? value, string json) => Can_read_and_write_JSON_property_value( b => b.HasConversion(), nameof(NullableInt8Type.Int8), value, json); @@ -936,7 +936,7 @@ public virtual void Can_read_write_nullable_sbyte_as_string_JSON_values(sbyte? v [InlineData((short)0, """{"Prop":"0"}""")] [InlineData((short)1, """{"Prop":"1"}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_short_as_string_JSON_values(short? value, string json) + public virtual Task Can_read_write_nullable_short_as_string_JSON_values(short? value, string json) => Can_read_and_write_JSON_property_value( b => b.HasConversion(), nameof(NullableInt16Type.Int16), value, json); @@ -947,7 +947,7 @@ public virtual void Can_read_write_nullable_short_as_string_JSON_values(short? v [InlineData(0, """{"Prop":"0"}""")] [InlineData(1, """{"Prop":"1"}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_int_as_string_JSON_values(int? value, string json) + public virtual Task Can_read_write_nullable_int_as_string_JSON_values(int? value, string json) => Can_read_and_write_JSON_property_value( b => b.HasConversion(), nameof(NullableInt32Type.Int32), value, json); @@ -958,7 +958,7 @@ public virtual void Can_read_write_nullable_int_as_string_JSON_values(int? value [InlineData((long)0, """{"Prop":"0"}""")] [InlineData((long)1, """{"Prop":"1"}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_long_as_string_JSON_values(long? value, string json) + public virtual Task Can_read_write_nullable_long_as_string_JSON_values(long? value, string json) => Can_read_and_write_JSON_property_value( b => b.HasConversion(), nameof(NullableInt64Type.Int64), value, json); @@ -968,7 +968,7 @@ public virtual void Can_read_write_nullable_long_as_string_JSON_values(long? val [InlineData(byte.MaxValue, """{"Prop":"255"}""")] [InlineData((byte)1, """{"Prop":"1"}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_byte_as_string_JSON_values(byte? value, string json) + public virtual Task Can_read_write_nullable_byte_as_string_JSON_values(byte? value, string json) => Can_read_and_write_JSON_property_value( b => b.HasConversion(), nameof(NullableUInt8Type.UInt8), value, json); @@ -978,7 +978,7 @@ public virtual void Can_read_write_nullable_byte_as_string_JSON_values(byte? val [InlineData(ushort.MaxValue, """{"Prop":"65535"}""")] [InlineData((ushort)1, """{"Prop":"1"}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_ushort_as_string_JSON_values(ushort? value, string json) + public virtual Task Can_read_write_nullable_ushort_as_string_JSON_values(ushort? value, string json) => Can_read_and_write_JSON_property_value( b => b.HasConversion(), nameof(NullableUInt16Type.UInt16), value, json); @@ -988,7 +988,7 @@ public virtual void Can_read_write_nullable_ushort_as_string_JSON_values(ushort? [InlineData(uint.MaxValue, """{"Prop":"4294967295"}""")] [InlineData((uint)1, """{"Prop":"1"}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_uint_as_string_JSON_values(uint? value, string json) + public virtual Task Can_read_write_nullable_uint_as_string_JSON_values(uint? value, string json) => Can_read_and_write_JSON_property_value( b => b.HasConversion(), nameof(NullableUInt32Type.UInt32), value, json); @@ -998,7 +998,7 @@ public virtual void Can_read_write_nullable_uint_as_string_JSON_values(uint? val [InlineData(ulong.MaxValue, """{"Prop":"18446744073709551615"}""")] [InlineData((ulong)1, """{"Prop":"1"}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_ulong_as_string_JSON_values(ulong? value, string json) + public virtual Task Can_read_write_nullable_ulong_as_string_JSON_values(ulong? value, string json) => Can_read_and_write_JSON_property_value( b => b.HasConversion(), nameof(NullableUInt64Type.UInt64), value, json); @@ -1009,7 +1009,7 @@ public virtual void Can_read_write_nullable_ulong_as_string_JSON_values(ulong? v [InlineData((float)0.0, """{"Prop":"0"}""")] [InlineData((float)1.1, """{"Prop":"1.1"}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_float_as_string_JSON_values(float? value, string json) + public virtual Task Can_read_write_nullable_float_as_string_JSON_values(float? value, string json) => Can_read_and_write_JSON_property_value( b => b.HasConversion(), nameof(NullableFloatType.Float), value, json); @@ -1020,7 +1020,7 @@ public virtual void Can_read_write_nullable_float_as_string_JSON_values(float? v [InlineData(0.0, """{"Prop":"0"}""")] [InlineData(1.1, """{"Prop":"1.1"}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_double_as_string_JSON_values(double? value, string json) + public virtual Task Can_read_write_nullable_double_as_string_JSON_values(double? value, string json) => Can_read_and_write_JSON_property_value( b => b.HasConversion(), nameof(NullableDoubleType.Double), value, json); @@ -1031,7 +1031,7 @@ public virtual void Can_read_write_nullable_double_as_string_JSON_values(double? [InlineData("0.0", """{"Prop":"0.0"}""")] [InlineData("1.1", """{"Prop":"1.1"}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_decimal_as_string_JSON_values(string? value, string json) + public virtual Task Can_read_write_nullable_decimal_as_string_JSON_values(string? value, string json) => Can_read_and_write_JSON_property_value( b => b.HasConversion(), nameof(NullableDecimalType.Decimal), @@ -1042,7 +1042,7 @@ public virtual void Can_read_write_nullable_decimal_as_string_JSON_values(string [InlineData("12/31/9999", """{"Prop":"9999-12-31"}""")] [InlineData("5/29/2023", """{"Prop":"2023-05-29"}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_DateOnly_as_string_JSON_values(string? value, string json) + public virtual Task Can_read_write_nullable_DateOnly_as_string_JSON_values(string? value, string json) => Can_read_and_write_JSON_property_value( b => b.HasConversion(), nameof(NullableDateOnlyType.DateOnly), @@ -1053,7 +1053,7 @@ public virtual void Can_read_write_nullable_DateOnly_as_string_JSON_values(strin [InlineData("23:59:59.9999999", """{"Prop":"23:59:59.9999999"}""")] [InlineData("11:05:12.3456789", """{"Prop":"11:05:12.3456789"}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_TimeOnly_as_string_JSON_values(string? value, string json) + public virtual Task Can_read_write_nullable_TimeOnly_as_string_JSON_values(string? value, string json) => Can_read_and_write_JSON_property_value( b => b.HasConversion(), nameof(NullableTimeOnlyType.TimeOnly), @@ -1064,7 +1064,7 @@ public virtual void Can_read_write_nullable_TimeOnly_as_string_JSON_values(strin [InlineData("9999-12-31T23:59:59.9999999", """{"Prop":"9999-12-31 23:59:59.9999999"}""")] [InlineData("2023-05-29T10:52:47.2064353", """{"Prop":"2023-05-29 10:52:47.2064353"}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_DateTime_as_string_JSON_values(string? value, string json) + public virtual Task Can_read_write_nullable_DateTime_as_string_JSON_values(string? value, string json) => Can_read_and_write_JSON_property_value( b => b.HasConversion(), nameof(NullableDateTimeType.DateTime), @@ -1076,7 +1076,7 @@ public virtual void Can_read_write_nullable_DateTime_as_string_JSON_values(strin [InlineData("0001-01-01T00:00:00.0000000-03:00", """{"Prop":"0001-01-01 00:00:00-03:00"}""")] [InlineData("2023-05-29T11:11:15.5672854+04:00", """{"Prop":"2023-05-29 11:11:15.5672854\u002B04:00"}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_DateTimeOffset_as_string_JSON_values(string? value, string json) + public virtual Task Can_read_write_nullable_DateTimeOffset_as_string_JSON_values(string? value, string json) => Can_read_and_write_JSON_property_value( b => b.HasConversion(), nameof(NullableDateTimeOffsetType.DateTimeOffset), @@ -1088,7 +1088,7 @@ public virtual void Can_read_write_nullable_DateTimeOffset_as_string_JSON_values [InlineData("00:00:00", """{"Prop":"00:00:00"}""")] [InlineData("12:23:23.8018854", """{"Prop":"12:23:23.8018854"}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_TimeSpan_as_string_JSON_values(string? value, string json) + public virtual Task Can_read_write_nullable_TimeSpan_as_string_JSON_values(string? value, string json) => Can_read_and_write_JSON_property_value( b => b.HasConversion(), nameof(NullableTimeSpanType.TimeSpan), @@ -1098,7 +1098,7 @@ public virtual void Can_read_write_nullable_TimeSpan_as_string_JSON_values(strin [InlineData(false, """{"Prop":"0"}""")] [InlineData(true, """{"Prop":"1"}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_bool_as_string_JSON_values(bool? value, string json) + public virtual Task Can_read_write_nullable_bool_as_string_JSON_values(bool? value, string json) => Can_read_and_write_JSON_property_value( b => b.HasConversion(), nameof(NullableBooleanType.Boolean), value, json); @@ -1109,7 +1109,7 @@ public virtual void Can_read_write_nullable_bool_as_string_JSON_values(bool? val [InlineData(' ', """{"Prop":" "}""")] [InlineData('Z', """{"Prop":"Z"}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_char_as_string_JSON_values(char? value, string json) + public virtual Task Can_read_write_nullable_char_as_string_JSON_values(char? value, string json) => Can_read_and_write_JSON_property_value( b => b.HasConversion(), nameof(NullableCharacterType.Character), value, json); @@ -1119,7 +1119,7 @@ public virtual void Can_read_write_nullable_char_as_string_JSON_values(char? val [InlineData("FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF", """{"Prop":"ffffffff-ffff-ffff-ffff-ffffffffffff"}""")] [InlineData("8C44242F-8E3F-4A20-8BE8-98C7C1AADEBD", """{"Prop":"8c44242f-8e3f-4a20-8be8-98c7c1aadebd"}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_as_string_GUID_JSON_values(string? value, string json) + public virtual Task Can_read_write_nullable_as_string_GUID_JSON_values(string? value, string json) => Can_read_and_write_JSON_property_value( b => b.HasConversion(), nameof(NullableGuidType.Guid), @@ -1133,7 +1133,7 @@ public virtual void Can_read_write_nullable_as_string_GUID_JSON_values(string? v "❤❥웃유♋☮✌☏☢☠✔☑♚▲♪฿Ɖ⛏♥❣♂♀☿👍✍✉☣☤✘☒♛▼♫⌘⌛¡♡ღツ☼☁❅♾️✎©®™Σ✪✯☭➳Ⓐ✞℃℉°✿⚡☃☂✄¢€£∞✫★½☯✡☪", @"{""Prop"":""\u2764\u2765\uC6C3\uC720\u264B\u262E\u270C\u260F\u2622\u2620\u2714\u2611\u265A\u25B2\u266A\u0E3F\u0189\u26CF\u2665\u2763\u2642\u2640\u263F\uD83D\uDC4D\u270D\u2709\u2623\u2624\u2718\u2612\u265B\u25BC\u266B\u2318\u231B\u00A1\u2661\u10E6\u30C4\u263C\u2601\u2745\u267E\uFE0F\u270E\u00A9\u00AE\u2122\u03A3\u272A\u272F\u262D\u27B3\u24B6\u271E\u2103\u2109\u00B0\u273F\u26A1\u2603\u2602\u2704\u00A2\u20AC\u00A3\u221E\u272B\u2605\u00BD\u262F\u2721\u262A""}")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_string_as_string_JSON_values(string? value, string json) + public virtual Task Can_read_write_nullable_string_as_string_JSON_values(string? value, string json) => Can_read_and_write_JSON_property_value( b => b.HasConversion(), nameof(NullableStringType.String), value, json); @@ -1144,7 +1144,7 @@ public virtual void Can_read_write_nullable_string_as_string_JSON_values(string? [InlineData("", """{"Prop":""}""")] [InlineData("1,2,3,4", """{"Prop":"AQIDBA=="}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_binary_as_string_JSON_values(string? value, string json) + public virtual Task Can_read_write_nullable_binary_as_string_JSON_values(string? value, string json) => Can_read_and_write_JSON_property_value( b => b.HasConversion(), nameof(NullableBytesType.Bytes), @@ -1160,7 +1160,7 @@ public virtual void Can_read_write_nullable_binary_as_string_JSON_values(string? """{"Prop":"https://user:password@www.contoso.com:80/Home/Index.htm?q1=v1\u0026q2=v2#FragmentName"}""")] [InlineData("file:///C:/test/path/file.txt", """{"Prop":"file:///C:/test/path/file.txt"}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_URI_as_string_JSON_values(string? value, string json) + public virtual Task Can_read_write_nullable_URI_as_string_JSON_values(string? value, string json) => Can_read_and_write_JSON_property_value( b => b.HasConversion(), nameof(NullableUriType.Uri), @@ -1175,7 +1175,7 @@ public virtual void Can_read_write_nullable_URI_as_string_JSON_values(string? va [InlineData("::", """{"Prop":"::"}""")] [InlineData("2a00:23c7:c60f:4f01:ba43:6d5a:e648:7577", """{"Prop":"2a00:23c7:c60f:4f01:ba43:6d5a:e648:7577"}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_IP_address_as_string_JSON_values(string? value, string json) + public virtual Task Can_read_write_nullable_IP_address_as_string_JSON_values(string? value, string json) => Can_read_and_write_JSON_property_value( b => b.HasConversion(), nameof(NullableIPAddressType.IpAddress), @@ -1186,7 +1186,7 @@ public virtual void Can_read_write_nullable_IP_address_as_string_JSON_values(str [InlineData("00-11-22-33-44-55", """{"Prop":"001122334455"}""")] [InlineData("0011.2233.4455", """{"Prop":"001122334455"}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_physical_address_as_string_JSON_values(string? value, string json) + public virtual Task Can_read_write_nullable_physical_address_as_string_JSON_values(string? value, string json) => Can_read_and_write_JSON_property_value( b => b.HasConversion(), nameof(NullablePhysicalAddressType.PhysicalAddress), @@ -1199,7 +1199,7 @@ public virtual void Can_read_write_nullable_physical_address_as_string_JSON_valu [InlineData((sbyte)Enum8.One, """{"Prop":"One"}""")] [InlineData((sbyte)77, """{"Prop":"77"}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_sbyte_enum_as_string_JSON_values(object? value, string json) + public virtual Task Can_read_write_nullable_sbyte_enum_as_string_JSON_values(object? value, string json) => Can_read_and_write_JSON_property_value( b => b.HasConversion(), nameof(NullableEnum8Type.Enum8), @@ -1212,7 +1212,7 @@ public virtual void Can_read_write_nullable_sbyte_enum_as_string_JSON_values(obj [InlineData((short)Enum16.One, """{"Prop":"One"}""")] [InlineData((short)77, """{"Prop":"77"}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_short_enum_as_string_JSON_values(object? value, string json) + public virtual Task Can_read_write_nullable_short_enum_as_string_JSON_values(object? value, string json) => Can_read_and_write_JSON_property_value( b => b.HasConversion(), nameof(NullableEnum16Type.Enum16), @@ -1225,7 +1225,7 @@ public virtual void Can_read_write_nullable_short_enum_as_string_JSON_values(obj [InlineData((int)Enum32.One, """{"Prop":"One"}""")] [InlineData(77, """{"Prop":"77"}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_int_enum_as_string_JSON_values(object? value, string json) + public virtual Task Can_read_write_nullable_int_enum_as_string_JSON_values(object? value, string json) => Can_read_and_write_JSON_property_value( b => b.HasConversion(), nameof(NullableEnum32Type.Enum32), @@ -1238,7 +1238,7 @@ public virtual void Can_read_write_nullable_int_enum_as_string_JSON_values(objec [InlineData((long)Enum64.One, """{"Prop":"One"}""")] [InlineData((long)77, """{"Prop":"77"}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_long_enum_as_string_JSON_values(object? value, string json) + public virtual Task Can_read_write_nullable_long_enum_as_string_JSON_values(object? value, string json) => Can_read_and_write_JSON_property_value( b => b.HasConversion(), nameof(NullableEnum64Type.Enum64), @@ -1250,7 +1250,7 @@ public virtual void Can_read_write_nullable_long_enum_as_string_JSON_values(obje [InlineData((byte)EnumU8.One, """{"Prop":"One"}""")] [InlineData((byte)77, """{"Prop":"77"}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_byte_enum_as_string_JSON_values(object? value, string json) + public virtual Task Can_read_write_nullable_byte_enum_as_string_JSON_values(object? value, string json) => Can_read_and_write_JSON_property_value( b => b.HasConversion(), nameof(NullableEnumU8Type.EnumU8), @@ -1262,7 +1262,7 @@ public virtual void Can_read_write_nullable_byte_enum_as_string_JSON_values(obje [InlineData((ushort)EnumU16.One, """{"Prop":"One"}""")] [InlineData((ushort)77, """{"Prop":"77"}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_ushort_enum_as_string_JSON_values(object? value, string json) + public virtual Task Can_read_write_nullable_ushort_enum_as_string_JSON_values(object? value, string json) => Can_read_and_write_JSON_property_value( b => b.HasConversion(), nameof(NullableEnumU16Type.EnumU16), @@ -1274,7 +1274,7 @@ public virtual void Can_read_write_nullable_ushort_enum_as_string_JSON_values(ob [InlineData((uint)EnumU32.One, """{"Prop":"One"}""")] [InlineData((uint)77, """{"Prop":"77"}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_uint_enum_as_string_JSON_values(object? value, string json) + public virtual Task Can_read_write_nullable_uint_enum_as_string_JSON_values(object? value, string json) => Can_read_and_write_JSON_property_value( b => b.HasConversion(), nameof(NullableEnumU32Type.EnumU32), @@ -1286,18 +1286,18 @@ public virtual void Can_read_write_nullable_uint_enum_as_string_JSON_values(obje [InlineData((ulong)EnumU64.One, """{"Prop":"One"}""")] [InlineData((ulong)77, """{"Prop":"77"}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_ulong_enum_as_string_JSON_values(object? value, string json) + public virtual Task Can_read_write_nullable_ulong_enum_as_string_JSON_values(object? value, string json) => Can_read_and_write_JSON_property_value( b => b.HasConversion(), nameof(NullableEnumU64Type.EnumU64), value == null ? default(EnumU64?) : (EnumU64)value, json); [ConditionalFact] - public virtual void Can_read_write_point() + public virtual async Task Can_read_write_point() { var factory = NtsGeometryServices.Instance.CreateGeometryFactory(srid: 4326); - Can_read_and_write_JSON_value( + await Can_read_and_write_JSON_value( nameof(PointType.Point), factory.CreatePoint(new Coordinate(2, 4)), """{"Prop":"POINT (2 4)"}"""); @@ -1309,7 +1309,7 @@ public class PointType } [ConditionalFact] - public virtual void Can_read_write_nullable_point() + public virtual Task Can_read_write_nullable_point() => Can_read_and_write_JSON_value( nameof(NullablePointType.Point), null, @@ -1321,11 +1321,11 @@ public class NullablePointType } [ConditionalFact] - public virtual void Can_read_write_point_with_Z() + public async virtual Task Can_read_write_point_with_Z() { var factory = NtsGeometryServices.Instance.CreateGeometryFactory(srid: 4326); - Can_read_and_write_JSON_value( + await Can_read_and_write_JSON_value( nameof(PointZType.PointZ), factory.CreatePoint(new CoordinateZ(2, 4, 6)), """{"Prop":"POINT Z(2 4 6)"}"""); @@ -1337,11 +1337,11 @@ public class PointZType } [ConditionalFact] - public virtual void Can_read_write_point_with_M() + public virtual async Task Can_read_write_point_with_M() { var factory = NtsGeometryServices.Instance.CreateGeometryFactory(srid: 4326); - Can_read_and_write_JSON_value( + await Can_read_and_write_JSON_value( nameof(PointMType.PointM), factory.CreatePoint(new CoordinateM(2, 4, 6)), """{"Prop":"POINT (2 4)"}"""); @@ -1353,11 +1353,11 @@ public class PointMType } [ConditionalFact] - public virtual void Can_read_write_point_with_Z_and_M() + public virtual async Task Can_read_write_point_with_Z_and_M() { var factory = NtsGeometryServices.Instance.CreateGeometryFactory(srid: 4326); - Can_read_and_write_JSON_value( + await Can_read_and_write_JSON_value( nameof(PointZMType.PointZM), factory.CreatePoint(new CoordinateZM(1, 2, 3, 4)), """{"Prop":"POINT Z(1 2 3)"}"""); @@ -1369,11 +1369,11 @@ public class PointZMType } [ConditionalFact] - public virtual void Can_read_write_line_string() + public virtual async Task Can_read_write_line_string() { var factory = NtsGeometryServices.Instance.CreateGeometryFactory(srid: 4326); - Can_read_and_write_JSON_value( + await Can_read_and_write_JSON_value( nameof(LineStringType.LineString), factory.CreateLineString([new Coordinate(0, 0), new Coordinate(1, 0)]), """{"Prop":"LINESTRING (0 0, 1 0)"}"""); @@ -1385,7 +1385,7 @@ public class LineStringType } [ConditionalFact] - public virtual void Can_read_write_nullable_line_string() + public virtual Task Can_read_write_nullable_line_string() => Can_read_and_write_JSON_value( nameof(NullableLineStringType.LineString), null, @@ -1397,17 +1397,17 @@ public class NullableLineStringType } [ConditionalFact] - public virtual void Can_read_write_multi_line_string() + public virtual async Task Can_read_write_multi_line_string() { var factory = NtsGeometryServices.Instance.CreateGeometryFactory(srid: 4326); - Can_read_and_write_JSON_value( + await Can_read_and_write_JSON_value( nameof(MultiLineStringType.MultiLineString), factory.CreateMultiLineString( [ factory.CreateLineString( [new Coordinate(0, 0), new Coordinate(0, 1)]), - factory.CreateLineString( + factory.CreateLineString( [new Coordinate(1, 0), new Coordinate(1, 1)]) ]), """{"Prop":"MULTILINESTRING ((0 0, 0 1), (1 0, 1 1))"}"""); @@ -1419,7 +1419,7 @@ public class MultiLineStringType } [ConditionalFact] - public virtual void Can_read_write_nullable_multi_line_string() + public virtual Task Can_read_write_nullable_multi_line_string() => Can_read_and_write_JSON_value( nameof(NullableMultiLineStringType.MultiLineString), null, @@ -1431,11 +1431,11 @@ public class NullableMultiLineStringType } [ConditionalFact] - public virtual void Can_read_write_polygon() + public virtual async Task Can_read_write_polygon() { var factory = NtsGeometryServices.Instance.CreateGeometryFactory(srid: 4326); - Can_read_and_write_JSON_value( + await Can_read_and_write_JSON_value( nameof(PolygonType.Polygon), factory.CreatePolygon([new Coordinate(0, 0), new Coordinate(1, 0), new Coordinate(0, 1), new Coordinate(0, 0)]), """{"Prop":"POLYGON ((0 0, 1 0, 0 1, 0 0))"}"""); @@ -1447,7 +1447,7 @@ public class PolygonType } [ConditionalFact] - public virtual void Can_read_write_nullable_polygon() + public virtual Task Can_read_write_nullable_polygon() => Can_read_and_write_JSON_value( nameof(NullablePolygonType.Polygon), null, @@ -1459,11 +1459,11 @@ public class NullablePolygonType } [ConditionalFact] - public virtual void Can_read_write_polygon_typed_as_geometry() + public virtual async Task Can_read_write_polygon_typed_as_geometry() { var factory = NtsGeometryServices.Instance.CreateGeometryFactory(srid: 4326); - Can_read_and_write_JSON_value( + await Can_read_and_write_JSON_value( nameof(GeometryType.Geometry), factory.CreatePolygon([new Coordinate(0, 0), new Coordinate(1, 0), new Coordinate(0, 1), new Coordinate(0, 0)]), """{"Prop":"POLYGON ((0 0, 1 0, 0 1, 0 0))"}"""); @@ -1475,7 +1475,7 @@ public class GeometryType } [ConditionalFact] - public virtual void Can_read_write_polygon_typed_as_nullable_geometry() + public virtual Task Can_read_write_polygon_typed_as_nullable_geometry() => Can_read_and_write_JSON_value( nameof(NullableGeometryType.Geometry), null, @@ -1487,11 +1487,11 @@ public class NullableGeometryType } [ConditionalFact] - public virtual void Can_read_write_point_as_GeoJson() + public virtual async Task Can_read_write_point_as_GeoJson() { var factory = NtsGeometryServices.Instance.CreateGeometryFactory(srid: 4326); - Can_read_and_write_JSON_property_value( + await Can_read_and_write_JSON_property_value( b => b.Metadata.SetJsonValueReaderWriterType(typeof(JsonGeoJsonReaderWriter)), nameof(PointType.Point), factory.CreatePoint(new Coordinate(2, 4)), @@ -1499,7 +1499,7 @@ public virtual void Can_read_write_point_as_GeoJson() } [ConditionalFact] - public virtual void Can_read_write_nullable_point_as_GeoJson() + public virtual Task Can_read_write_nullable_point_as_GeoJson() => Can_read_and_write_JSON_property_value( b => b.Metadata.SetJsonValueReaderWriterType(typeof(JsonGeoJsonReaderWriter)), nameof(NullablePointType.Point), @@ -1507,11 +1507,11 @@ public virtual void Can_read_write_nullable_point_as_GeoJson() """{"Prop":null}"""); [ConditionalFact] - public virtual void Can_read_write_point_with_Z_as_GeoJson() + public virtual async Task Can_read_write_point_with_Z_as_GeoJson() { var factory = NtsGeometryServices.Instance.CreateGeometryFactory(srid: 4326); - Can_read_and_write_JSON_property_value( + await Can_read_and_write_JSON_property_value( b => b.Metadata.SetJsonValueReaderWriterType(typeof(JsonGeoJsonReaderWriter)), nameof(PointZType.PointZ), factory.CreatePoint(new CoordinateZ(2, 4, 6)), @@ -1519,11 +1519,11 @@ public virtual void Can_read_write_point_with_Z_as_GeoJson() } [ConditionalFact] - public virtual void Can_read_write_point_with_M_as_GeoJson() + public virtual async Task Can_read_write_point_with_M_as_GeoJson() { var factory = NtsGeometryServices.Instance.CreateGeometryFactory(srid: 4326); - Can_read_and_write_JSON_property_value( + await Can_read_and_write_JSON_property_value( b => b.Metadata.SetJsonValueReaderWriterType(typeof(JsonGeoJsonReaderWriter)), nameof(PointMType.PointM), factory.CreatePoint(new CoordinateM(2, 4, 6)), @@ -1531,11 +1531,11 @@ public virtual void Can_read_write_point_with_M_as_GeoJson() } [ConditionalFact] - public virtual void Can_read_write_point_with_Z_and_M_as_GeoJson() + public virtual async Task Can_read_write_point_with_Z_and_M_as_GeoJson() { var factory = NtsGeometryServices.Instance.CreateGeometryFactory(srid: 4326); - Can_read_and_write_JSON_property_value( + await Can_read_and_write_JSON_property_value( b => b.Metadata.SetJsonValueReaderWriterType(typeof(JsonGeoJsonReaderWriter)), nameof(PointZMType.PointZM), factory.CreatePoint(new CoordinateZM(1, 2, 3, 4)), @@ -1543,11 +1543,11 @@ public virtual void Can_read_write_point_with_Z_and_M_as_GeoJson() } [ConditionalFact] - public virtual void Can_read_write_line_string_as_GeoJson() + public virtual async Task Can_read_write_line_string_as_GeoJson() { var factory = NtsGeometryServices.Instance.CreateGeometryFactory(srid: 4326); - Can_read_and_write_JSON_property_value( + await Can_read_and_write_JSON_property_value( b => b.Metadata.SetJsonValueReaderWriterType(typeof(JsonGeoJsonReaderWriter)), nameof(LineStringType.LineString), factory.CreateLineString([new Coordinate(0, 0), new Coordinate(1, 0)]), @@ -1555,7 +1555,7 @@ public virtual void Can_read_write_line_string_as_GeoJson() } [ConditionalFact] - public virtual void Can_read_write_nullable_line_string_as_GeoJson() + public virtual Task Can_read_write_nullable_line_string_as_GeoJson() => Can_read_and_write_JSON_property_value( b => b.Metadata.SetJsonValueReaderWriterType(typeof(JsonGeoJsonReaderWriter)), nameof(NullableLineStringType.LineString), @@ -1563,25 +1563,25 @@ public virtual void Can_read_write_nullable_line_string_as_GeoJson() """{"Prop":null}"""); [ConditionalFact] - public virtual void Can_read_write_multi_line_string_as_GeoJson() + public virtual async Task Can_read_write_multi_line_string_as_GeoJson() { var factory = NtsGeometryServices.Instance.CreateGeometryFactory(srid: 4326); - Can_read_and_write_JSON_property_value( + await Can_read_and_write_JSON_property_value( b => b.Metadata.SetJsonValueReaderWriterType(typeof(JsonGeoJsonReaderWriter)), nameof(MultiLineStringType.MultiLineString), factory.CreateMultiLineString( [ factory.CreateLineString( [new Coordinate(0, 0), new Coordinate(0, 1)]), - factory.CreateLineString( + factory.CreateLineString( [new Coordinate(1, 0), new Coordinate(1, 1)]) ]), """{"Prop":{"type":"MultiLineString","coordinates":[[[0.0,0.0],[0.0,1.0]],[[1.0,0.0],[1.0,1.0]]]}}"""); } [ConditionalFact] - public virtual void Can_read_write_nullable_multi_line_string_as_GeoJson() + public virtual Task Can_read_write_nullable_multi_line_string_as_GeoJson() => Can_read_and_write_JSON_property_value( b => b.Metadata.SetJsonValueReaderWriterType(typeof(JsonGeoJsonReaderWriter)), nameof(NullableMultiLineStringType.MultiLineString), @@ -1589,11 +1589,11 @@ public virtual void Can_read_write_nullable_multi_line_string_as_GeoJson() """{"Prop":null}"""); [ConditionalFact] - public virtual void Can_read_write_polygon_as_GeoJson() + public virtual async Task Can_read_write_polygon_as_GeoJson() { var factory = NtsGeometryServices.Instance.CreateGeometryFactory(srid: 4326); - Can_read_and_write_JSON_property_value( + await Can_read_and_write_JSON_property_value( b => b.Metadata.SetJsonValueReaderWriterType(typeof(JsonGeoJsonReaderWriter)), nameof(PolygonType.Polygon), factory.CreatePolygon([new Coordinate(0, 0), new Coordinate(1, 0), new Coordinate(0, 1), new Coordinate(0, 0)]), @@ -1601,7 +1601,7 @@ public virtual void Can_read_write_polygon_as_GeoJson() } [ConditionalFact] - public virtual void Can_read_write_nullable_polygon_as_GeoJson() + public virtual Task Can_read_write_nullable_polygon_as_GeoJson() => Can_read_and_write_JSON_property_value( b => b.Metadata.SetJsonValueReaderWriterType(typeof(JsonGeoJsonReaderWriter)), nameof(NullablePolygonType.Polygon), @@ -1609,11 +1609,11 @@ public virtual void Can_read_write_nullable_polygon_as_GeoJson() """{"Prop":null}"""); [ConditionalFact] - public virtual void Can_read_write_polygon_typed_as_geometry_as_GeoJson() + public virtual async Task Can_read_write_polygon_typed_as_geometry_as_GeoJson() { var factory = NtsGeometryServices.Instance.CreateGeometryFactory(srid: 4326); - Can_read_and_write_JSON_property_value( + await Can_read_and_write_JSON_property_value( b => b.Metadata.SetJsonValueReaderWriterType(typeof(JsonGeoJsonReaderWriter)), nameof(GeometryType.Geometry), factory.CreatePolygon([new Coordinate(0, 0), new Coordinate(1, 0), new Coordinate(0, 1), new Coordinate(0, 0)]), @@ -1621,7 +1621,7 @@ public virtual void Can_read_write_polygon_typed_as_geometry_as_GeoJson() } [ConditionalFact] - public virtual void Can_read_write_polygon_typed_as_nullable_geometry_as_GeoJson() + public virtual Task Can_read_write_polygon_typed_as_nullable_geometry_as_GeoJson() => Can_read_and_write_JSON_property_value( b => b.Metadata.SetJsonValueReaderWriterType(typeof(JsonGeoJsonReaderWriter)), nameof(NullableGeometryType.Geometry), @@ -1633,7 +1633,7 @@ public virtual void Can_read_write_polygon_typed_as_nullable_geometry_as_GeoJson [InlineData(int.MaxValue, """{"Prop":2147483647}""")] [InlineData(0, """{"Prop":0}""")] [InlineData(1, """{"Prop":1}""")] - public virtual void Can_read_write_converted_type_JSON_values(int value, string json) + public virtual Task Can_read_write_converted_type_JSON_values(int value, string json) => Can_read_and_write_JSON_value( b => b.Entity().HasNoKey().Property(e => e.DddId), b => b.Properties().HaveConversion(), @@ -1651,7 +1651,7 @@ protected class DddIdType [InlineData(0, """{"Prop":0}""")] [InlineData(1, """{"Prop":1}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_converted_type_JSON_values(int? value, string json) + public virtual Task Can_read_write_nullable_converted_type_JSON_values(int? value, string json) => Can_read_and_write_JSON_value( b => b.Entity().HasNoKey().Property(e => e.DddId), b => b.Properties().HaveConversion(), @@ -1666,7 +1666,7 @@ protected class NullableDddIdType [ConditionalTheory] [InlineData(EnumProperty.FieldA, """{"Prop":"A"}""")] [InlineData(EnumProperty.FieldB, """{"Prop":"B"}""")] - public virtual void Can_read_write_enum_char_converted_type_JSON_values(int value, string json) + public virtual Task Can_read_write_enum_char_converted_type_JSON_values(int value, string json) => Can_read_and_write_JSON_value( b => b.Entity().HasNoKey().Property(e => e.EnumProperty), b => b.Properties().HaveConversion>(), @@ -1698,7 +1698,7 @@ protected enum EnumProperty [InlineData("::1", """{"Prop":"::1"}""")] [InlineData("::", """{"Prop":"::"}""")] [InlineData("2a00:23c7:c60f:4f01:ba43:6d5a:e648:7577", """{"Prop":"2a00:23c7:c60f:4f01:ba43:6d5a:e648:7577"}""")] - public virtual void Can_read_write_custom_converted_type_JSON_values(string value, string json) + public virtual Task Can_read_write_custom_converted_type_JSON_values(string value, string json) => Can_read_and_write_JSON_value( b => b.Entity().HasNoKey().Property(e => e.Address), b => b.Properties().HaveConversion(), @@ -1730,7 +1730,7 @@ public override int GetHashCode() } [ConditionalFact] - public virtual void Can_read_write_collection_of_sbyte_JSON_values() + public virtual Task Can_read_write_collection_of_sbyte_JSON_values() => Can_read_and_write_JSON_value>( nameof(Int8CollectionType.Int8), [ @@ -1747,7 +1747,7 @@ protected class Int8CollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_short_JSON_values() + public virtual Task Can_read_write_collection_of_short_JSON_values() => Can_read_and_write_JSON_value>( nameof(Int16CollectionType.Int16), [ @@ -1764,7 +1764,7 @@ protected class Int16CollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_int_JSON_values() + public virtual Task Can_read_write_collection_of_int_JSON_values() => Can_read_and_write_JSON_value>( nameof(Int32CollectionType.Int32), [ @@ -1781,7 +1781,7 @@ protected class Int32CollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_long_JSON_values() + public virtual Task Can_read_write_collection_of_long_JSON_values() => Can_read_and_write_JSON_value>( nameof(Int64CollectionType.Int64), [ @@ -1798,7 +1798,7 @@ protected class Int64CollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_byte_JSON_values() + public virtual Task Can_read_write_collection_of_byte_JSON_values() => Can_read_and_write_JSON_value>( nameof(UInt8CollectionType.UInt8), [ @@ -1815,7 +1815,7 @@ protected class UInt8CollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_ushort_JSON_values() + public virtual Task Can_read_write_collection_of_ushort_JSON_values() => Can_read_and_write_JSON_value>( nameof(UInt16CollectionType.UInt16), [ @@ -1832,7 +1832,7 @@ protected class UInt16CollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_uint_JSON_values() + public virtual Task Can_read_write_collection_of_uint_JSON_values() => Can_read_and_write_JSON_value>( nameof(UInt32CollectionType.UInt32), [ @@ -1849,7 +1849,7 @@ protected class UInt32CollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_ulong_JSON_values() + public virtual Task Can_read_write_collection_of_ulong_JSON_values() => Can_read_and_write_JSON_value>( nameof(UInt64CollectionType.UInt64), [ @@ -1867,7 +1867,7 @@ protected class UInt64CollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_float_JSON_values() + public virtual Task Can_read_write_collection_of_float_JSON_values() => Can_read_and_write_JSON_value>( nameof(FloatCollectionType.Float), [ @@ -1884,7 +1884,7 @@ protected class FloatCollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_double_JSON_values() + public virtual Task Can_read_write_collection_of_double_JSON_values() => Can_read_and_write_JSON_value>( nameof(DoubleCollectionType.Double), [ @@ -1901,7 +1901,7 @@ protected class DoubleCollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_decimal_JSON_values() + public virtual Task Can_read_write_collection_of_decimal_JSON_values() => Can_read_and_write_JSON_value>( nameof(DecimalCollectionType.Decimal), [ @@ -1918,7 +1918,7 @@ protected class DecimalCollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_DateOnly_JSON_values() + public virtual Task Can_read_write_collection_of_DateOnly_JSON_values() => Can_read_and_write_JSON_value>( nameof(DateOnlyCollectionType.DateOnly), [ @@ -1935,7 +1935,7 @@ protected class DateOnlyCollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_TimeOnly_JSON_values() + public virtual Task Can_read_write_collection_of_TimeOnly_JSON_values() => Can_read_and_write_JSON_value>( nameof(TimeOnlyCollectionType.TimeOnly), [ @@ -1953,7 +1953,7 @@ protected class TimeOnlyCollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_DateTime_JSON_values() + public virtual Task Can_read_write_collection_of_DateTime_JSON_values() => Can_read_and_write_JSON_value>( nameof(DateTimeCollectionType.DateTime), [ @@ -1970,7 +1970,7 @@ protected class DateTimeCollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_DateTimeOffset_JSON_values() + public virtual Task Can_read_write_collection_of_DateTimeOffset_JSON_values() => Can_read_and_write_JSON_value>( nameof(DateTimeOffsetCollectionType.DateTimeOffset), [ @@ -1989,7 +1989,7 @@ protected class DateTimeOffsetCollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_TimeSpan_JSON_values() + public virtual Task Can_read_write_collection_of_TimeSpan_JSON_values() => Can_read_and_write_JSON_value>( nameof(TimeSpanCollectionType.TimeSpan), [ @@ -2006,7 +2006,7 @@ protected class TimeSpanCollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_bool_JSON_values() + public virtual Task Can_read_write_collection_of_bool_JSON_values() => Can_read_and_write_JSON_value>( nameof(BooleanCollectionType.Boolean), [false, true], @@ -2019,7 +2019,7 @@ protected class BooleanCollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_char_JSON_values() + public virtual Task Can_read_write_collection_of_char_JSON_values() => Can_read_and_write_JSON_value>( nameof(CharacterCollectionType.Character), [ @@ -2036,7 +2036,7 @@ protected class CharacterCollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_GUID_JSON_values() + public virtual Task Can_read_write_collection_of_GUID_JSON_values() => Can_read_and_write_JSON_value>( nameof(GuidCollectionType.Guid), [ @@ -2053,7 +2053,7 @@ protected class GuidCollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_string_JSON_values() + public virtual Task Can_read_write_collection_of_string_JSON_values() => Can_read_and_write_JSON_value>( nameof(StringCollectionType.String), [ @@ -2070,7 +2070,7 @@ protected class StringCollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_binary_JSON_values() + public virtual Task Can_read_write_collection_of_binary_JSON_values() => Can_read_and_write_JSON_value>( nameof(BytesCollectionType.Bytes), [ @@ -2088,7 +2088,7 @@ protected class BytesCollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_URI_JSON_values() + public virtual Task Can_read_write_collection_of_URI_JSON_values() => Can_read_and_write_JSON_value>( nameof(UriCollectionType.Uri), [ @@ -2104,7 +2104,7 @@ protected class UriCollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_IP_address_JSON_values() + public virtual Task Can_read_write_collection_of_IP_address_JSON_values() => Can_read_and_write_JSON_value>( nameof(IpAddressCollectionType.IpAddress), [ @@ -2125,7 +2125,7 @@ protected class IpAddressCollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_physical_address_JSON_values() + public virtual Task Can_read_write_collection_of_physical_address_JSON_values() => Can_read_and_write_JSON_value>( nameof(PhysicalAddressCollectionType.PhysicalAddress), [ @@ -2143,7 +2143,7 @@ protected class PhysicalAddressCollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_sbyte_enum_JSON_values() + public virtual Task Can_read_write_collection_of_sbyte_enum_JSON_values() => Can_read_and_write_JSON_value>( nameof(Enum8CollectionType.Enum8), [ @@ -2162,7 +2162,7 @@ protected class Enum8CollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_short_enum_JSON_values() + public virtual Task Can_read_write_collection_of_short_enum_JSON_values() => Can_read_and_write_JSON_value>( nameof(Enum16CollectionType.Enum16), [ @@ -2181,7 +2181,7 @@ protected class Enum16CollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_int_enum_JSON_values() + public virtual Task Can_read_write_collection_of_int_enum_JSON_values() => Can_read_and_write_JSON_value>( nameof(Enum32CollectionType.Enum32), [ @@ -2200,7 +2200,7 @@ protected class Enum32CollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_long_enum_JSON_values() + public virtual Task Can_read_write_collection_of_long_enum_JSON_values() => Can_read_and_write_JSON_value>( nameof(Enum64CollectionType.Enum64), [ @@ -2219,7 +2219,7 @@ protected class Enum64CollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_byte_enum_JSON_values() + public virtual Task Can_read_write_collection_of_byte_enum_JSON_values() => Can_read_and_write_JSON_value>( nameof(EnumU8CollectionType.EnumU8), [ @@ -2238,7 +2238,7 @@ protected class EnumU8CollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_ushort_enum_JSON_values() + public virtual Task Can_read_write_collection_of_ushort_enum_JSON_values() => Can_read_and_write_JSON_value>( nameof(EnumU16CollectionType.EnumU16), [ @@ -2257,7 +2257,7 @@ protected class EnumU16CollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_uint_enum_JSON_values() + public virtual Task Can_read_write_collection_of_uint_enum_JSON_values() => Can_read_and_write_JSON_value>( nameof(EnumU32CollectionType.EnumU32), [ @@ -2277,7 +2277,7 @@ protected class EnumU32CollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_ulong_enum_JSON_values() + public virtual Task Can_read_write_collection_of_ulong_enum_JSON_values() => Can_read_and_write_JSON_value>( nameof(EnumU64CollectionType.EnumU64), [ @@ -2296,7 +2296,7 @@ protected class EnumU64CollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_nullable_sbyte_JSON_values() + public virtual Task Can_read_write_collection_of_nullable_sbyte_JSON_values() => Can_read_and_write_JSON_value>( nameof(NullableInt8CollectionType.Int8), [ @@ -2314,7 +2314,7 @@ protected class NullableInt8CollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_nullable_short_JSON_values() + public virtual Task Can_read_write_collection_of_nullable_short_JSON_values() => Can_read_and_write_JSON_value>( nameof(NullableInt16CollectionType.Int16), [ @@ -2332,7 +2332,7 @@ protected class NullableInt16CollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_nullable_int_JSON_values() + public virtual Task Can_read_write_collection_of_nullable_int_JSON_values() => Can_read_and_write_JSON_value>( nameof(NullableInt32CollectionType.Int32), [ @@ -2350,7 +2350,7 @@ protected class NullableInt32CollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_nullable_long_JSON_values() + public virtual Task Can_read_write_collection_of_nullable_long_JSON_values() => Can_read_and_write_JSON_value>( nameof(NullableInt64CollectionType.Int64), [ @@ -2368,7 +2368,7 @@ protected class NullableInt64CollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_nullable_byte_JSON_values() + public virtual Task Can_read_write_collection_of_nullable_byte_JSON_values() => Can_read_and_write_JSON_value>( nameof(NullableUInt8CollectionType.UInt8), [ @@ -2386,7 +2386,7 @@ protected class NullableUInt8CollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_nullable_ushort_JSON_values() + public virtual Task Can_read_write_collection_of_nullable_ushort_JSON_values() => Can_read_and_write_JSON_value>( nameof(NullableUInt16CollectionType.UInt16), [ @@ -2404,7 +2404,7 @@ protected class NullableUInt16CollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_nullable_uint_JSON_values() + public virtual Task Can_read_write_collection_of_nullable_uint_JSON_values() => Can_read_and_write_JSON_value>( nameof(NullableUInt32CollectionType.UInt32), [ @@ -2422,7 +2422,7 @@ protected class NullableUInt32CollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_nullable_ulong_JSON_values() + public virtual Task Can_read_write_collection_of_nullable_ulong_JSON_values() => Can_read_and_write_JSON_value>( nameof(NullableUInt64CollectionType.UInt64), [ @@ -2440,7 +2440,7 @@ protected class NullableUInt64CollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_nullable_float_JSON_values() + public virtual Task Can_read_write_collection_of_nullable_float_JSON_values() => Can_read_and_write_JSON_value>( nameof(NullableFloatCollectionType.Float), [ @@ -2458,7 +2458,7 @@ protected class NullableFloatCollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_nullable_double_JSON_values() + public virtual Task Can_read_write_collection_of_nullable_double_JSON_values() => Can_read_and_write_JSON_value>( nameof(NullableDoubleCollectionType.Double), [ @@ -2476,7 +2476,7 @@ protected class NullableDoubleCollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_nullable_decimal_JSON_values() + public virtual Task Can_read_write_collection_of_nullable_decimal_JSON_values() => Can_read_and_write_JSON_value>( nameof(NullableDecimalCollectionType.Decimal), [ @@ -2494,7 +2494,7 @@ protected class NullableDecimalCollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_nullable_DateOnly_JSON_values() + public virtual Task Can_read_write_collection_of_nullable_DateOnly_JSON_values() => Can_read_and_write_JSON_value>( nameof(NullableDateOnlyCollectionType.DateOnly), [ @@ -2512,7 +2512,7 @@ protected class NullableDateOnlyCollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_nullable_TimeOnly_JSON_values() + public virtual Task Can_read_write_collection_of_nullable_TimeOnly_JSON_values() => Can_read_and_write_JSON_value>( nameof(NullableTimeOnlyCollectionType.TimeOnly), [ @@ -2530,7 +2530,7 @@ protected class NullableTimeOnlyCollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_nullable_DateTime_JSON_values() + public virtual Task Can_read_write_collection_of_nullable_DateTime_JSON_values() => Can_read_and_write_JSON_value>( nameof(NullableDateTimeCollectionType.DateTime), [ @@ -2548,7 +2548,7 @@ protected class NullableDateTimeCollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_nullable_DateTimeOffset_JSON_values() + public virtual Task Can_read_write_collection_of_nullable_DateTimeOffset_JSON_values() => Can_read_and_write_JSON_value>( nameof(NullableDateTimeOffsetCollectionType.DateTimeOffset), [ @@ -2568,7 +2568,7 @@ protected class NullableDateTimeOffsetCollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_nullable_TimeSpan_JSON_values() + public virtual Task Can_read_write_collection_of_nullable_TimeSpan_JSON_values() => Can_read_and_write_JSON_value>( nameof(NullableTimeSpanCollectionType.TimeSpan), [ @@ -2586,7 +2586,7 @@ protected class NullableTimeSpanCollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_nullable_bool_JSON_values() + public virtual Task Can_read_write_collection_of_nullable_bool_JSON_values() => Can_read_and_write_JSON_value>( nameof(NullableBooleanCollectionType.Boolean), [ @@ -2603,7 +2603,7 @@ protected class NullableBooleanCollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_nullable_char_JSON_values() + public virtual Task Can_read_write_collection_of_nullable_char_JSON_values() => Can_read_and_write_JSON_value>( nameof(NullableCharacterCollectionType.Character), [ @@ -2621,7 +2621,7 @@ protected class NullableCharacterCollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_nullable_GUID_JSON_values() + public virtual Task Can_read_write_collection_of_nullable_GUID_JSON_values() => Can_read_and_write_JSON_value>( nameof(NullableGuidCollectionType.Guid), [ @@ -2639,7 +2639,7 @@ protected class NullableGuidCollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_nullable_string_JSON_values() + public virtual Task Can_read_write_collection_of_nullable_string_JSON_values() => Can_read_and_write_JSON_value>( nameof(NullableStringCollectionType.String), [ @@ -2657,7 +2657,7 @@ protected class NullableStringCollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_nullable_binary_JSON_values() + public virtual Task Can_read_write_collection_of_nullable_binary_JSON_values() => Can_read_and_write_JSON_value>( nameof(NullableBytesCollectionType.Bytes), [ @@ -2676,7 +2676,7 @@ protected class NullableBytesCollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_nullable_URI_JSON_values() + public virtual Task Can_read_write_collection_of_nullable_URI_JSON_values() => Can_read_and_write_JSON_value>( nameof(NullableUriCollectionType.Uri), [ @@ -2693,7 +2693,7 @@ protected class NullableUriCollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_nullable_IP_address_JSON_values() + public virtual Task Can_read_write_collection_of_nullable_IP_address_JSON_values() => Can_read_and_write_JSON_value>( nameof(NullableIpAddressCollectionType.IpAddress), [ @@ -2715,7 +2715,7 @@ protected class NullableIpAddressCollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_nullable_physical_address_JSON_values() + public virtual Task Can_read_write_collection_of_nullable_physical_address_JSON_values() => Can_read_and_write_JSON_value>( nameof(NullablePhysicalAddressCollectionType.PhysicalAddress), [ @@ -2734,7 +2734,7 @@ protected class NullablePhysicalAddressCollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_nullable_sbyte_enum_JSON_values() + public virtual Task Can_read_write_collection_of_nullable_sbyte_enum_JSON_values() => Can_read_and_write_JSON_value>( nameof(NullableEnum8CollectionType.Enum8), [ @@ -2754,7 +2754,7 @@ protected class NullableEnum8CollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_nullable_short_enum_JSON_values() + public virtual Task Can_read_write_collection_of_nullable_short_enum_JSON_values() => Can_read_and_write_JSON_value>( nameof(NullableEnum16CollectionType.Enum16), [ @@ -2774,7 +2774,7 @@ protected class NullableEnum16CollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_nullable_int_enum_JSON_values() + public virtual Task Can_read_write_collection_of_nullable_int_enum_JSON_values() => Can_read_and_write_JSON_value>( nameof(NullableEnum32CollectionType.Enum32), [ @@ -2794,7 +2794,7 @@ protected class NullableEnum32CollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_nullable_long_enum_JSON_values() + public virtual Task Can_read_write_collection_of_nullable_long_enum_JSON_values() => Can_read_and_write_JSON_value>( nameof(NullableEnum64CollectionType.Enum64), [ @@ -2814,7 +2814,7 @@ protected class NullableEnum64CollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_nullable_byte_enum_JSON_values() + public virtual Task Can_read_write_collection_of_nullable_byte_enum_JSON_values() => Can_read_and_write_JSON_value>( nameof(NullableEnumU8CollectionType.EnumU8), [ @@ -2834,7 +2834,7 @@ protected class NullableEnumU8CollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_nullable_ushort_enum_JSON_values() + public virtual Task Can_read_write_collection_of_nullable_ushort_enum_JSON_values() => Can_read_and_write_JSON_value>( nameof(NullableEnumU16CollectionType.EnumU16), [ @@ -2854,7 +2854,7 @@ protected class NullableEnumU16CollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_nullable_uint_enum_JSON_values() + public virtual Task Can_read_write_collection_of_nullable_uint_enum_JSON_values() => Can_read_and_write_JSON_value>( nameof(NullableEnumU32CollectionType.EnumU32), [ @@ -2874,7 +2874,7 @@ protected class NullableEnumU32CollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_nullable_ulong_enum_JSON_values() + public virtual Task Can_read_write_collection_of_nullable_ulong_enum_JSON_values() => Can_read_and_write_JSON_value>( nameof(NullableEnumU64CollectionType.EnumU64), [ @@ -2894,7 +2894,7 @@ protected class NullableEnumU64CollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_sbyte_values_with_converter_as_JSON_string() + public virtual Task Can_read_write_collection_of_sbyte_values_with_converter_as_JSON_string() => Can_read_and_write_JSON_property_value( b => b.HasConversion, CustomCollectionComparer>(), nameof(Int8ConvertedType.Int8Converted), @@ -2907,7 +2907,7 @@ protected class Int8ConvertedType } [ConditionalFact] - public virtual void Can_read_write_collection_of_int_values_with_converter_as_JSON_string() + public virtual Task Can_read_write_collection_of_int_values_with_converter_as_JSON_string() => Can_read_and_write_JSON_property_value>( b => b.HasConversion, int>, CustomCollectionComparer, int>>(), nameof(Int32ConvertedType.Int32Converted), @@ -2924,7 +2924,7 @@ protected class Int32ConvertedType } [ConditionalFact] - public virtual void Can_read_write_collection_of_ulong_values_with_converter_as_JSON_string() + public virtual Task Can_read_write_collection_of_ulong_values_with_converter_as_JSON_string() => Can_read_and_write_JSON_property_value>( b => b.HasConversion, ulong>, CustomCollectionComparer, ulong>>(), @@ -2942,7 +2942,7 @@ protected class UInt64ConvertedType } [ConditionalFact] - public virtual void Can_read_write_collection_of_double_values_with_converter_as_JSON_string() + public virtual Task Can_read_write_collection_of_double_values_with_converter_as_JSON_string() => Can_read_and_write_JSON_property_value( b => b.HasConversion, CustomCollectionComparer>(), nameof(DoubleConvertedType.DoubleConverted), @@ -2955,7 +2955,7 @@ protected class DoubleConvertedType } [ConditionalFact] - public virtual void Can_read_write_collection_of_DateOnly_values_with_converter_as_JSON_string() + public virtual Task Can_read_write_collection_of_DateOnly_values_with_converter_as_JSON_string() => Can_read_and_write_JSON_property_value>( b => b.HasConversion, DateOnly>, CustomCollectionComparer, DateOnly>>(), @@ -2974,7 +2974,7 @@ protected class DateOnlyConvertedType } [ConditionalFact] - public virtual void Can_read_write_collection_of_DateTime_values_with_converter_as_JSON_string() + public virtual Task Can_read_write_collection_of_DateTime_values_with_converter_as_JSON_string() => Can_read_and_write_JSON_property_value>( b => b .HasConversion, DateTime>, CustomCollectionComparer, DateTime>>(), @@ -2993,7 +2993,7 @@ protected class DateTimeConvertedType } [ConditionalFact] - public virtual void Can_read_write_collection_of_bool_values_with_converter_as_JSON_string() + public virtual Task Can_read_write_collection_of_bool_values_with_converter_as_JSON_string() => Can_read_and_write_JSON_property_value>( b => b.HasConversion, bool>, CustomCollectionComparer, bool>>(), nameof(BooleanConvertedType.BooleanConverted), @@ -3006,7 +3006,7 @@ protected class BooleanConvertedType } [ConditionalFact] - public virtual void Can_read_write_collection_of_char_values_with_converter_as_JSON_string() + public virtual Task Can_read_write_collection_of_char_values_with_converter_as_JSON_string() => Can_read_and_write_JSON_property_value>( b => b.HasConversion, char>, CustomCollectionComparer, char>>(), nameof(CharacterConvertedType.CharacterConverted), @@ -3024,7 +3024,7 @@ protected class CharacterConvertedType } [ConditionalFact] - public virtual void Can_read_write_collection_of_string_values_with_converter_as_JSON_string() + public virtual Task Can_read_write_collection_of_string_values_with_converter_as_JSON_string() => Can_read_and_write_JSON_property_value>( b => b.HasConversion, string>, CustomCollectionComparer, string>>(), nameof(StringConvertedType.StringConverted), @@ -3042,7 +3042,7 @@ protected class StringConvertedType } [ConditionalFact] - public virtual void Can_read_write_collection_of_binary_values_with_converter_as_JSON_string() + public virtual Task Can_read_write_collection_of_binary_values_with_converter_as_JSON_string() => Can_read_and_write_JSON_property_value>( b => b.HasConversion, byte[]>, CustomCollectionComparer, byte[]>>(), nameof(BytesConvertedType.BytesConverted), @@ -3061,7 +3061,7 @@ protected class BytesConvertedType } [ConditionalFact] - public virtual void Can_read_write_collection_of_int_enum_values_with_converter_as_JSON_string() + public virtual Task Can_read_write_collection_of_int_enum_values_with_converter_as_JSON_string() => Can_read_and_write_JSON_property_value>( b => b.HasConversion, Enum32>, CustomCollectionComparer, Enum32>>(), nameof(Enum32ConvertedType.Enum32Converted), @@ -3080,7 +3080,7 @@ protected class Enum32ConvertedType } [ConditionalFact] - public virtual void Can_read_write_collection_of_ulong_enum_values_with_converter_as_JSON_string() + public virtual Task Can_read_write_collection_of_ulong_enum_values_with_converter_as_JSON_string() => Can_read_and_write_JSON_property_value>( b => b.HasConversion, EnumU64>, CustomCollectionComparer, EnumU64>>(), nameof(EnumU64ConvertedType.EnumU64Converted), @@ -3100,7 +3100,7 @@ protected class EnumU64ConvertedType } [ConditionalFact] - public virtual void Can_read_write_collection_of_nullable_sbyte_values_with_converter_as_JSON_string() + public virtual Task Can_read_write_collection_of_nullable_sbyte_values_with_converter_as_JSON_string() => Can_read_and_write_JSON_property_value( b => b.HasConversion, CustomCollectionComparer>(), nameof(NullableInt8ConvertedType.Int8Converted), @@ -3113,7 +3113,7 @@ protected class NullableInt8ConvertedType } [ConditionalFact] - public virtual void Can_read_write_collection_of_nullable_int_values_with_converter_as_JSON_string() + public virtual Task Can_read_write_collection_of_nullable_int_values_with_converter_as_JSON_string() => Can_read_and_write_JSON_property_value>( b => b.HasConversion, int?>, CustomCollectionComparer, int?>>(), nameof(NullableInt32ConvertedType.Int32Converted), @@ -3131,7 +3131,7 @@ protected class NullableInt32ConvertedType } [ConditionalFact] - public virtual void Can_read_write_collection_of_nullable_ulong_values_with_converter_as_JSON_string() + public virtual Task Can_read_write_collection_of_nullable_ulong_values_with_converter_as_JSON_string() => Can_read_and_write_JSON_property_value>( b => b.HasConversion, ulong?>, CustomCollectionComparer, ulong?>>(), @@ -3150,7 +3150,7 @@ protected class NullableUInt64ConvertedType } [ConditionalFact] - public virtual void Can_read_write_collection_of_nullable_double_values_with_converter_as_JSON_string() + public virtual Task Can_read_write_collection_of_nullable_double_values_with_converter_as_JSON_string() => Can_read_and_write_JSON_property_value( b => b.HasConversion, CustomCollectionComparer>(), nameof(NullableDoubleConvertedType.DoubleConverted), @@ -3163,7 +3163,7 @@ protected class NullableDoubleConvertedType } [ConditionalFact] - public virtual void Can_read_write_collection_of_nullable_DateOnly_values_with_converter_as_JSON_string() + public virtual Task Can_read_write_collection_of_nullable_DateOnly_values_with_converter_as_JSON_string() => Can_read_and_write_JSON_property_value>( b => b.HasConversion, DateOnly?>, CustomCollectionComparer, DateOnly?>>(), @@ -3183,7 +3183,7 @@ protected class NullableDateOnlyConvertedType } [ConditionalFact] - public virtual void Can_read_write_collection_of_nullable_DateTime_values_with_converter_as_JSON_string() + public virtual Task Can_read_write_collection_of_nullable_DateTime_values_with_converter_as_JSON_string() => Can_read_and_write_JSON_property_value>( b => b .HasConversion, DateTime?>, @@ -3204,7 +3204,7 @@ protected class NullableDateTimeConvertedType } [ConditionalFact] - public virtual void Can_read_write_collection_of_nullable_bool_values_with_converter_as_JSON_string() + public virtual Task Can_read_write_collection_of_nullable_bool_values_with_converter_as_JSON_string() => Can_read_and_write_JSON_property_value>( b => b.HasConversion, bool?>, CustomCollectionComparer, bool?>>(), nameof(NullableBooleanConvertedType.BooleanConverted), @@ -3222,7 +3222,7 @@ protected class NullableBooleanConvertedType } [ConditionalFact] - public virtual void Can_read_write_collection_of_nullable_char_values_with_converter_as_JSON_string() + public virtual Task Can_read_write_collection_of_nullable_char_values_with_converter_as_JSON_string() => Can_read_and_write_JSON_property_value>( b => b.HasConversion, char?>, CustomCollectionComparer, char?>>(), nameof(NullableCharacterConvertedType.CharacterConverted), @@ -3241,7 +3241,7 @@ protected class NullableCharacterConvertedType } [ConditionalFact] - public virtual void Can_read_write_collection_of_nullable_string_values_with_converter_as_JSON_string() + public virtual Task Can_read_write_collection_of_nullable_string_values_with_converter_as_JSON_string() => Can_read_and_write_JSON_property_value>( b => b.HasConversion, string?>, CustomCollectionComparer, string?>>(), nameof(NullableStringConvertedType.StringConverted), @@ -3260,7 +3260,7 @@ protected class NullableStringConvertedType } [ConditionalFact] - public virtual void Can_read_write_collection_of_nullable_binary_values_with_converter_as_JSON_string() + public virtual Task Can_read_write_collection_of_nullable_binary_values_with_converter_as_JSON_string() => Can_read_and_write_JSON_property_value>( b => b.HasConversion, byte[]?>, CustomCollectionComparer, byte[]?>>(), nameof(NullableBytesConvertedType.BytesConverted), @@ -3280,7 +3280,7 @@ protected class NullableBytesConvertedType } [ConditionalFact] - public virtual void Can_read_write_collection_of_nullable_int_enum_values_with_converter_as_JSON_string() + public virtual Task Can_read_write_collection_of_nullable_int_enum_values_with_converter_as_JSON_string() => Can_read_and_write_JSON_property_value>( b => b.HasConversion, Enum32?>, CustomCollectionComparer, Enum32?>>(), nameof(NullableEnum32ConvertedType.Enum32Converted), @@ -3300,7 +3300,7 @@ protected class NullableEnum32ConvertedType } [ConditionalFact] - public virtual void Can_read_write_collection_of_nullable_ulong_enum_values_with_converter_as_JSON_string() + public virtual Task Can_read_write_collection_of_nullable_ulong_enum_values_with_converter_as_JSON_string() => Can_read_and_write_JSON_property_value>( b => b .HasConversion, EnumU64?>, CustomCollectionComparer, EnumU64?>>(), @@ -3322,7 +3322,7 @@ protected class NullableEnumU64ConvertedType } [ConditionalFact] - public virtual void Can_read_write_collection_of_int_with_converter_JSON_values() + public virtual Task Can_read_write_collection_of_int_with_converter_JSON_values() => Can_read_and_write_JSON_collection_value>( b => b.ElementType( b => @@ -3345,7 +3345,7 @@ protected class DddIdCollectionType } [ConditionalFact] - public virtual void Can_read_write_collection_of_nullable_int_with_converter_JSON_values() + public virtual Task Can_read_write_collection_of_nullable_int_with_converter_JSON_values() => Can_read_and_write_JSON_collection_value>( b => b.ElementType().HasConversion(), nameof(NullableDddIdCollectionType.DddId), @@ -3365,7 +3365,7 @@ protected class NullableDddIdCollectionType } [ConditionalFact] - public virtual void Can_read_write_binary_as_collection() + public virtual Task Can_read_write_binary_as_collection() => Can_read_and_write_JSON_collection_value( _ => { }, nameof(BinaryAsJsonType.BinaryAsJson), @@ -3378,7 +3378,7 @@ protected class BinaryAsJsonType } [ConditionalFact] - public virtual void Can_read_write_collection_of_decimal_with_precision_and_scale_JSON_values() + public virtual Task Can_read_write_collection_of_decimal_with_precision_and_scale_JSON_values() => Can_read_and_write_JSON_collection_value>( b => b.ElementType().HasPrecision(12, 6), nameof(DecimalCollectionType.Decimal), @@ -3391,7 +3391,7 @@ public virtual void Can_read_write_collection_of_decimal_with_precision_and_scal facets: new Dictionary { { CoreAnnotationNames.Precision, 12 }, { CoreAnnotationNames.Scale, 6 } }); [ConditionalFact] - public virtual void Can_read_write_collection_of_Guid_converted_to_bytes_JSON_values() + public virtual Task Can_read_write_collection_of_Guid_converted_to_bytes_JSON_values() => Can_read_and_write_JSON_collection_value>( b => b.ElementType().HasConversion(), nameof(GuidCollectionType.Guid), @@ -3403,7 +3403,7 @@ public virtual void Can_read_write_collection_of_Guid_converted_to_bytes_JSON_va """{"Prop":["AAAAAAAAAAAAAAAAAAAAAA==","LyREjD+OIEqL6JjHwarevQ==","/////////////////////w=="]}""", facets: new Dictionary { { CoreAnnotationNames.ProviderClrType, typeof(byte[]) } }); - protected virtual void Can_read_and_write_JSON_value( + protected virtual async Task Can_read_and_write_JSON_value( string propertyName, TModel value, string json, @@ -3414,7 +3414,7 @@ protected virtual void Can_read_and_write_JSON_value( { if (mappedCollection) { - Can_read_and_write_JSON_value( + await Can_read_and_write_JSON_value( b => b.Entity().HasNoKey().PrimitiveCollection(propertyName), null, propertyName, @@ -3426,7 +3426,7 @@ protected virtual void Can_read_and_write_JSON_value( } else { - Can_read_and_write_JSON_value( + await Can_read_and_write_JSON_value( b => b.Entity().HasNoKey().Property(propertyName), null, propertyName, @@ -3438,7 +3438,7 @@ protected virtual void Can_read_and_write_JSON_value( } } - protected virtual void Can_read_and_write_JSON_property_value( + protected virtual Task Can_read_and_write_JSON_property_value( Action buildProperty, string propertyName, TModel value, @@ -3453,10 +3453,10 @@ protected virtual void Can_read_and_write_JSON_property_value( value, json, mappedCollection: false, - existingObject, - facets); + existingObject: existingObject, + facets: facets); - protected virtual void Can_read_and_write_JSON_collection_value( + protected virtual Task Can_read_and_write_JSON_collection_value( Action buildCollection, string propertyName, TModel value, @@ -3471,10 +3471,10 @@ protected virtual void Can_read_and_write_JSON_collection_value value, json, mappedCollection: true, - existingObject, - facets); + existingObject: existingObject, + facets: facets); - protected virtual void Can_read_and_write_JSON_value( + protected virtual async Task Can_read_and_write_JSON_value( Action buildModel, Action? configureConventions, string propertyName, @@ -3485,7 +3485,7 @@ protected virtual void Can_read_and_write_JSON_value( Dictionary? facets = null) where TEntity : class { - var contextFactory = CreateContextFactory( + var contextFactory = await CreateContextFactory( buildModel, addServices: AddServices, configureConventions: configureConventions); @@ -3563,7 +3563,8 @@ protected virtual void Can_read_and_write_JSON_value( } } - protected override string StoreName => "JsonTypesTest"; + protected override string StoreName + => "JsonTypesTest"; protected virtual IServiceCollection AddServices(IServiceCollection serviceCollection) => serviceCollection; diff --git a/test/EFCore.Specification.Tests/KeysWithConvertersTestBase.cs b/test/EFCore.Specification.Tests/KeysWithConvertersTestBase.cs index 520191204d9..de6c348506f 100644 --- a/test/EFCore.Specification.Tests/KeysWithConvertersTestBase.cs +++ b/test/EFCore.Specification.Tests/KeysWithConvertersTestBase.cs @@ -22,13 +22,15 @@ protected DbContext CreateContext() => Fixture.CreateContext(); [ConditionalFact] - public virtual void Can_insert_and_read_back_with_struct_key_and_optional_dependents() + public virtual async Task Can_insert_and_read_back_with_struct_key_and_optional_dependents() { - InsertOptionalGraph(); + IntStructKeyPrincipal[] principals = null; + IntStructKeyOptionalDependent[] dependents = null; + await InsertOptionalGraph(); using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -50,12 +52,12 @@ public virtual void Can_insert_and_read_back_with_struct_key_and_optional_depend principals[0].OptionalDependents.Add( new IntStructKeyOptionalDependent { Id = new IntStructKey(dependents[0].Id.Id), }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -64,23 +66,20 @@ public virtual void Can_insert_and_read_back_with_struct_key_and_optional_depend [(0, 0), (1, null), (2, 2), (3, 0), (4, null), (5, 0)]); } - void RunQueries( - DbContext context, - out IntStructKeyPrincipal[] principals, - out IntStructKeyOptionalDependent[] dependents) + async Task RunQueries(DbContext context) { var two = 2; var three = new IntStructKey(3); principals = [ - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new IntStructKey(1))), - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new IntStructKey { Id = two })), - context.Set().Include(e => e.OptionalDependents).Single(e => e.Id.Equals(three)), - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new IntStructKey { Id = 4 })) + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new IntStructKey(1))), + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new IntStructKey { Id = two })), + await context.Set().Include(e => e.OptionalDependents).SingleAsync(e => e.Id.Equals(three)), + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new IntStructKey { Id = 4 })) ]; var oneOhTwo = 102; @@ -90,20 +89,20 @@ void RunQueries( dependents = [ - context.Set().Single(e => e.Id.Equals(new IntStructKey(101))), - context.Set().Single(e => e.Id.Equals(new IntStructKey(oneOhTwo))), - context.Set().Single(e => e.Id.Equals(oneOhThree)), - context.Set().Single(e => e.Id.Equals(new IntStructKey(104))), - context.Set().Single(e => e.Id.Equals(new IntStructKey(oneOhFive))), - context.Set().Single(e => e.Id.Equals(oneOhSix)) + await context.Set().SingleAsync(e => e.Id.Equals(new IntStructKey(101))), + await context.Set().SingleAsync(e => e.Id.Equals(new IntStructKey(oneOhTwo))), + await context.Set().SingleAsync(e => e.Id.Equals(oneOhThree)), + await context.Set().SingleAsync(e => e.Id.Equals(new IntStructKey(104))), + await context.Set().SingleAsync(e => e.Id.Equals(new IntStructKey(oneOhFive))), + await context.Set().SingleAsync(e => e.Id.Equals(oneOhSix)) ]; - Assert.Same(dependents[0], context.Set().Find(new IntStructKey(101))); - Assert.Same(dependents[1], context.Set().Find(new IntStructKey(oneOhTwo))); - Assert.Same(dependents[2], context.Set().Find(oneOhThree)); - Assert.Same(dependents[3], context.Find(typeof(IntStructKeyOptionalDependent), new IntStructKey(104))); - Assert.Same(dependents[4], context.Find(typeof(IntStructKeyOptionalDependent), new IntStructKey(oneOhFive))); - Assert.Same(dependents[5], context.Find(typeof(IntStructKeyOptionalDependent), oneOhSix)); + Assert.Same(dependents[0], await context.Set().FindAsync(new IntStructKey(101))); + Assert.Same(dependents[1], await context.Set().FindAsync(new IntStructKey(oneOhTwo))); + Assert.Same(dependents[2], await context.Set().FindAsync(oneOhThree)); + Assert.Same(dependents[3], await context.FindAsync(typeof(IntStructKeyOptionalDependent), new IntStructKey(104))); + Assert.Same(dependents[4], await context.FindAsync(typeof(IntStructKeyOptionalDependent), new IntStructKey(oneOhFive))); + Assert.Same(dependents[5], await context.FindAsync(typeof(IntStructKeyOptionalDependent), oneOhSix)); } void Validate( @@ -121,13 +120,15 @@ void Validate( } [ConditionalFact] - public virtual void Can_insert_and_read_back_with_comparable_struct_key_and_optional_dependents() + public virtual async Task Can_insert_and_read_back_with_comparable_struct_key_and_optional_dependents() { - InsertOptionalGraph(); + ComparableIntStructKeyPrincipal[] principals = null; + ComparableIntStructKeyOptionalDependent[] dependents = null; + await InsertOptionalGraph(); using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -149,12 +150,12 @@ public virtual void Can_insert_and_read_back_with_comparable_struct_key_and_opti principals[0].OptionalDependents.Add( new ComparableIntStructKeyOptionalDependent { Id = new ComparableIntStructKey(dependents[0].Id.Id), }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -163,23 +164,20 @@ public virtual void Can_insert_and_read_back_with_comparable_struct_key_and_opti [(0, 0), (1, null), (2, 2), (3, 0), (4, null), (5, 0)]); } - void RunQueries( - DbContext context, - out ComparableIntStructKeyPrincipal[] principals, - out ComparableIntStructKeyOptionalDependent[] dependents) + async Task RunQueries(DbContext context) { var two = 2; var three = new ComparableIntStructKey(3); principals = [ - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new ComparableIntStructKey(1))), - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new ComparableIntStructKey { Id = two })), - context.Set().Include(e => e.OptionalDependents).Single(e => e.Id.Equals(three)), - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new ComparableIntStructKey { Id = 4 })) + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new ComparableIntStructKey(1))), + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new ComparableIntStructKey { Id = two })), + await context.Set().Include(e => e.OptionalDependents).SingleAsync(e => e.Id.Equals(three)), + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new ComparableIntStructKey { Id = 4 })) ]; var oneOhTwo = 102; @@ -189,30 +187,30 @@ void RunQueries( dependents = [ - context.Set() - .Single(e => e.Id.Equals(new ComparableIntStructKey(101))), - context.Set() - .Single(e => e.Id.Equals(new ComparableIntStructKey(oneOhTwo))), - context.Set().Single(e => e.Id.Equals(oneOhThree)), - context.Set() - .Single(e => e.Id.Equals(new ComparableIntStructKey(104))), - context.Set() - .Single(e => e.Id.Equals(new ComparableIntStructKey(oneOhFive))), - context.Set().Single(e => e.Id.Equals(oneOhSix)) + await context.Set() + .SingleAsync(e => e.Id.Equals(new ComparableIntStructKey(101))), + await context.Set() + .SingleAsync(e => e.Id.Equals(new ComparableIntStructKey(oneOhTwo))), + await context.Set().SingleAsync(e => e.Id.Equals(oneOhThree)), + await context.Set() + .SingleAsync(e => e.Id.Equals(new ComparableIntStructKey(104))), + await context.Set() + .SingleAsync(e => e.Id.Equals(new ComparableIntStructKey(oneOhFive))), + await context.Set().SingleAsync(e => e.Id.Equals(oneOhSix)) ]; Assert.Same( - dependents[0], context.Set().Find(new ComparableIntStructKey(101))); + dependents[0], await context.Set().FindAsync(new ComparableIntStructKey(101))); Assert.Same( dependents[1], - context.Set().Find(new ComparableIntStructKey(oneOhTwo))); - Assert.Same(dependents[2], context.Set().Find(oneOhThree)); + await context.Set().FindAsync(new ComparableIntStructKey(oneOhTwo))); + Assert.Same(dependents[2], await context.Set().FindAsync(oneOhThree)); Assert.Same( - dependents[3], context.Find(typeof(ComparableIntStructKeyOptionalDependent), new ComparableIntStructKey(104))); + dependents[3], await context.FindAsync(typeof(ComparableIntStructKeyOptionalDependent), new ComparableIntStructKey(104))); Assert.Same( dependents[4], - context.Find(typeof(ComparableIntStructKeyOptionalDependent), new ComparableIntStructKey(oneOhFive))); - Assert.Same(dependents[5], context.Find(typeof(ComparableIntStructKeyOptionalDependent), oneOhSix)); + await context.FindAsync(typeof(ComparableIntStructKeyOptionalDependent), new ComparableIntStructKey(oneOhFive))); + Assert.Same(dependents[5], await context.FindAsync(typeof(ComparableIntStructKeyOptionalDependent), oneOhSix)); } void Validate( @@ -230,13 +228,15 @@ void Validate( } [ConditionalFact] - public virtual void Can_insert_and_read_back_with_generic_comparable_struct_key_and_optional_dependents() + public virtual async Task Can_insert_and_read_back_with_generic_comparable_struct_key_and_optional_dependents() { - InsertOptionalGraph(); + GenericComparableIntStructKeyPrincipal[] principals = null; + GenericComparableIntStructKeyOptionalDependent[] dependents = null; + await InsertOptionalGraph(); using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -258,12 +258,12 @@ public virtual void Can_insert_and_read_back_with_generic_comparable_struct_key_ principals[0].OptionalDependents.Add( new GenericComparableIntStructKeyOptionalDependent { Id = new GenericComparableIntStructKey(dependents[0].Id.Id), }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -272,24 +272,21 @@ public virtual void Can_insert_and_read_back_with_generic_comparable_struct_key_ [(0, 0), (1, null), (2, 2), (3, 0), (4, null), (5, 0)]); } - void RunQueries( - DbContext context, - out GenericComparableIntStructKeyPrincipal[] principals, - out GenericComparableIntStructKeyOptionalDependent[] dependents) + async Task RunQueries(DbContext context) { var two = 2; var three = new GenericComparableIntStructKey(3); principals = [ - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new GenericComparableIntStructKey(1))), - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new GenericComparableIntStructKey { Id = two })), - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(three)), - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new GenericComparableIntStructKey { Id = 4 })) + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new GenericComparableIntStructKey(1))), + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new GenericComparableIntStructKey { Id = two })), + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(three)), + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new GenericComparableIntStructKey { Id = 4 })) ]; var oneOhTwo = 102; @@ -299,34 +296,34 @@ void RunQueries( dependents = [ - context.Set() - .Single(e => e.Id.Equals(new GenericComparableIntStructKey(101))), - context.Set() - .Single(e => e.Id.Equals(new GenericComparableIntStructKey(oneOhTwo))), - context.Set().Single(e => e.Id.Equals(oneOhThree)), - context.Set() - .Single(e => e.Id.Equals(new GenericComparableIntStructKey(104))), - context.Set() - .Single(e => e.Id.Equals(new GenericComparableIntStructKey(oneOhFive))), - context.Set().Single(e => e.Id.Equals(oneOhSix)) + await context.Set() + .SingleAsync(e => e.Id.Equals(new GenericComparableIntStructKey(101))), + await context.Set() + .SingleAsync(e => e.Id.Equals(new GenericComparableIntStructKey(oneOhTwo))), + await context.Set().SingleAsync(e => e.Id.Equals(oneOhThree)), + await context.Set() + .SingleAsync(e => e.Id.Equals(new GenericComparableIntStructKey(104))), + await context.Set() + .SingleAsync(e => e.Id.Equals(new GenericComparableIntStructKey(oneOhFive))), + await context.Set().SingleAsync(e => e.Id.Equals(oneOhSix)) ]; Assert.Same( dependents[0], - context.Set().Find(new GenericComparableIntStructKey(101))); + await context.Set().FindAsync(new GenericComparableIntStructKey(101))); Assert.Same( dependents[1], - context.Set() - .Find(new GenericComparableIntStructKey(oneOhTwo))); - Assert.Same(dependents[2], context.Set().Find(oneOhThree)); + await context.Set() + .FindAsync(new GenericComparableIntStructKey(oneOhTwo))); + Assert.Same(dependents[2], await context.Set().FindAsync(oneOhThree)); Assert.Same( dependents[3], - context.Find(typeof(GenericComparableIntStructKeyOptionalDependent), new GenericComparableIntStructKey(104))); + await context.FindAsync(typeof(GenericComparableIntStructKeyOptionalDependent), new GenericComparableIntStructKey(104))); Assert.Same( dependents[4], - context.Find( + await context.FindAsync( typeof(GenericComparableIntStructKeyOptionalDependent), new GenericComparableIntStructKey(oneOhFive))); - Assert.Same(dependents[5], context.Find(typeof(GenericComparableIntStructKeyOptionalDependent), oneOhSix)); + Assert.Same(dependents[5], await context.FindAsync(typeof(GenericComparableIntStructKeyOptionalDependent), oneOhSix)); } void Validate( @@ -344,13 +341,15 @@ void Validate( } [ConditionalFact] - public virtual void Can_insert_and_read_back_with_struct_key_and_required_dependents() + public virtual async Task Can_insert_and_read_back_with_struct_key_and_required_dependents() { - InsertRequiredGraph(); + IntStructKeyPrincipal[] principals = null; + IntStructKeyRequiredDependent[] dependents = null; + await InsertRequiredGraph(); using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -372,12 +371,12 @@ public virtual void Can_insert_and_read_back_with_struct_key_and_required_depend principals[0].RequiredDependents.Add( new IntStructKeyRequiredDependent { Id = new IntStructKey(dependents[0].Id.Id), }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -386,23 +385,20 @@ public virtual void Can_insert_and_read_back_with_struct_key_and_required_depend [(0, 0), (2, 2), (3, 0), (5, 0)]); } - void RunQueries( - DbContext context, - out IntStructKeyPrincipal[] principals, - out IntStructKeyRequiredDependent[] dependents) + async Task RunQueries(DbContext context) { var twelve = 12; var thirteen = new IntStructKey { Id = 13 }; principals = [ - context.Set().Include(e => e.RequiredDependents) - .Single(e => e.Id.Equals(new IntStructKey { Id = 11 })), - context.Set().Include(e => e.RequiredDependents) - .Single(e => e.Id.Equals(new IntStructKey { Id = twelve })), - context.Set().Include(e => e.RequiredDependents).Single(e => e.Id.Equals(thirteen)), - context.Set().Include(e => e.RequiredDependents) - .Single(e => e.Id.Equals(new IntStructKey { Id = 14 })) + await context.Set().Include(e => e.RequiredDependents) + .SingleAsync(e => e.Id.Equals(new IntStructKey { Id = 11 })), + await context.Set().Include(e => e.RequiredDependents) + .SingleAsync(e => e.Id.Equals(new IntStructKey { Id = twelve })), + await context.Set().Include(e => e.RequiredDependents).SingleAsync(e => e.Id.Equals(thirteen)), + await context.Set().Include(e => e.RequiredDependents) + .SingleAsync(e => e.Id.Equals(new IntStructKey { Id = 14 })) ]; var oneTwelve = 112; @@ -412,21 +408,21 @@ void RunQueries( dependents = [ - context.Set().FirstOrDefault(e => e.Id.Equals(new IntStructKey { Id = 111 })), - context.Set().FirstOrDefault(e => e.Id.Equals(new IntStructKey { Id = oneTwelve })), - context.Set().FirstOrDefault(e => e.Id.Equals(oneThirteen)), - context.Set().FirstOrDefault(e => e.Id.Equals(new IntStructKey { Id = 114 })), - context.Set() - .FirstOrDefault(e => e.Id.Equals(new IntStructKey { Id = oneFifteeen })), - context.Set().FirstOrDefault(e => e.Id.Equals(oneSixteen)) + await context.Set().FirstOrDefaultAsync(e => e.Id.Equals(new IntStructKey { Id = 111 })), + await context.Set().FirstOrDefaultAsync(e => e.Id.Equals(new IntStructKey { Id = oneTwelve })), + await context.Set().FirstOrDefaultAsync(e => e.Id.Equals(oneThirteen)), + await context.Set().FirstOrDefaultAsync(e => e.Id.Equals(new IntStructKey { Id = 114 })), + await context.Set() + .FirstOrDefaultAsync(e => e.Id.Equals(new IntStructKey { Id = oneFifteeen })), + await context.Set().FirstOrDefaultAsync(e => e.Id.Equals(oneSixteen)) ]; - Assert.Same(dependents[0], context.Set().Find(new IntStructKey { Id = 111 })); - Assert.Same(dependents[1], context.Set().Find(new IntStructKey { Id = oneTwelve })); - Assert.Same(dependents[2], context.Set().Find(oneThirteen)); - Assert.Same(dependents[3], context.Find(typeof(IntStructKeyRequiredDependent), new IntStructKey { Id = 114 })); - Assert.Same(dependents[4], context.Find(typeof(IntStructKeyRequiredDependent), new IntStructKey { Id = oneFifteeen })); - Assert.Same(dependents[5], context.Find(typeof(IntStructKeyRequiredDependent), oneSixteen)); + Assert.Same(dependents[0], await context.Set().FindAsync(new IntStructKey { Id = 111 })); + Assert.Same(dependents[1], await context.Set().FindAsync(new IntStructKey { Id = oneTwelve })); + Assert.Same(dependents[2], await context.Set().FindAsync(oneThirteen)); + Assert.Same(dependents[3], await context.FindAsync(typeof(IntStructKeyRequiredDependent), new IntStructKey { Id = 114 })); + Assert.Same(dependents[4], await context.FindAsync(typeof(IntStructKeyRequiredDependent), new IntStructKey { Id = oneFifteeen })); + Assert.Same(dependents[5], await context.FindAsync(typeof(IntStructKeyRequiredDependent), oneSixteen)); } void Validate( @@ -444,13 +440,15 @@ void Validate( } [ConditionalFact] - public virtual void Can_insert_and_read_back_with_comparable_struct_key_and_required_dependents() + public virtual async Task Can_insert_and_read_back_with_comparable_struct_key_and_required_dependents() { - InsertRequiredGraph(); + ComparableIntStructKeyPrincipal[] principals = null; + ComparableIntStructKeyRequiredDependent[] dependents = null; + await InsertRequiredGraph(); using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -472,12 +470,12 @@ public virtual void Can_insert_and_read_back_with_comparable_struct_key_and_requ principals[0].RequiredDependents.Add( new ComparableIntStructKeyRequiredDependent { Id = new ComparableIntStructKey(dependents[0].Id.Id), }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -486,24 +484,21 @@ public virtual void Can_insert_and_read_back_with_comparable_struct_key_and_requ [(0, 0), (2, 2), (3, 0), (5, 0)]); } - void RunQueries( - DbContext context, - out ComparableIntStructKeyPrincipal[] principals, - out ComparableIntStructKeyRequiredDependent[] dependents) + async Task RunQueries(DbContext context) { var twelve = 12; var thirteen = new ComparableIntStructKey { Id = 13 }; principals = [ - context.Set().Include(e => e.RequiredDependents) - .Single(e => e.Id.Equals(new ComparableIntStructKey { Id = 11 })), - context.Set().Include(e => e.RequiredDependents) - .Single(e => e.Id.Equals(new ComparableIntStructKey { Id = twelve })), - context.Set().Include(e => e.RequiredDependents) - .Single(e => e.Id.Equals(thirteen)), - context.Set().Include(e => e.RequiredDependents) - .Single(e => e.Id.Equals(new ComparableIntStructKey { Id = 14 })) + await context.Set().Include(e => e.RequiredDependents) + .SingleAsync(e => e.Id.Equals(new ComparableIntStructKey { Id = 11 })), + await context.Set().Include(e => e.RequiredDependents) + .SingleAsync(e => e.Id.Equals(new ComparableIntStructKey { Id = twelve })), + await context.Set().Include(e => e.RequiredDependents) + .SingleAsync(e => e.Id.Equals(thirteen)), + await context.Set().Include(e => e.RequiredDependents) + .SingleAsync(e => e.Id.Equals(new ComparableIntStructKey { Id = 14 })) ]; var oneTwelve = 112; @@ -513,30 +508,30 @@ void RunQueries( dependents = [ - context.Set() - .FirstOrDefault(e => e.Id.Equals(new ComparableIntStructKey { Id = 111 })), - context.Set() - .FirstOrDefault(e => e.Id.Equals(new ComparableIntStructKey { Id = oneTwelve })), - context.Set().FirstOrDefault(e => e.Id.Equals(oneThirteen)), - context.Set() - .FirstOrDefault(e => e.Id.Equals(new ComparableIntStructKey { Id = 114 })), - context.Set() - .FirstOrDefault(e => e.Id.Equals(new ComparableIntStructKey { Id = oneFifteeen })), - context.Set().FirstOrDefault(e => e.Id.Equals(oneSixteen)) + await context.Set() + .FirstOrDefaultAsync(e => e.Id.Equals(new ComparableIntStructKey { Id = 111 })), + await context.Set() + .FirstOrDefaultAsync(e => e.Id.Equals(new ComparableIntStructKey { Id = oneTwelve })), + await context.Set().FirstOrDefaultAsync(e => e.Id.Equals(oneThirteen)), + await context.Set() + .FirstOrDefaultAsync(e => e.Id.Equals(new ComparableIntStructKey { Id = 114 })), + await context.Set() + .FirstOrDefaultAsync(e => e.Id.Equals(new ComparableIntStructKey { Id = oneFifteeen })), + await context.Set().FirstOrDefaultAsync(e => e.Id.Equals(oneSixteen)) ]; Assert.Same( - dependents[0], context.Set().Find(new ComparableIntStructKey { Id = 111 })); + dependents[0], await context.Set().FindAsync(new ComparableIntStructKey { Id = 111 })); Assert.Same( dependents[1], - context.Set().Find(new ComparableIntStructKey { Id = oneTwelve })); - Assert.Same(dependents[2], context.Set().Find(oneThirteen)); + await context.Set().FindAsync(new ComparableIntStructKey { Id = oneTwelve })); + Assert.Same(dependents[2], await context.Set().FindAsync(oneThirteen)); Assert.Same( - dependents[3], context.Find(typeof(ComparableIntStructKeyRequiredDependent), new ComparableIntStructKey { Id = 114 })); + dependents[3], await context.FindAsync(typeof(ComparableIntStructKeyRequiredDependent), new ComparableIntStructKey { Id = 114 })); Assert.Same( dependents[4], - context.Find(typeof(ComparableIntStructKeyRequiredDependent), new ComparableIntStructKey { Id = oneFifteeen })); - Assert.Same(dependents[5], context.Find(typeof(ComparableIntStructKeyRequiredDependent), oneSixteen)); + await context.FindAsync(typeof(ComparableIntStructKeyRequiredDependent), new ComparableIntStructKey { Id = oneFifteeen })); + Assert.Same(dependents[5], await context.FindAsync(typeof(ComparableIntStructKeyRequiredDependent), oneSixteen)); } void Validate( @@ -554,13 +549,15 @@ void Validate( } [ConditionalFact] - public virtual void Can_insert_and_read_back_with_generic_comparable_struct_key_and_required_dependents() + public virtual async Task Can_insert_and_read_back_with_generic_comparable_struct_key_and_required_dependents() { - InsertRequiredGraph(); + GenericComparableIntStructKeyPrincipal[] principals = null; + GenericComparableIntStructKeyRequiredDependent[] dependents = null; + await InsertRequiredGraph(); using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -582,12 +579,12 @@ public virtual void Can_insert_and_read_back_with_generic_comparable_struct_key_ principals[0].RequiredDependents.Add( new GenericComparableIntStructKeyRequiredDependent { Id = new GenericComparableIntStructKey(dependents[0].Id.Id), }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -596,24 +593,21 @@ public virtual void Can_insert_and_read_back_with_generic_comparable_struct_key_ [(0, 0), (2, 2), (3, 0), (5, 0)]); } - void RunQueries( - DbContext context, - out GenericComparableIntStructKeyPrincipal[] principals, - out GenericComparableIntStructKeyRequiredDependent[] dependents) + async Task RunQueries(DbContext context) { var twelve = 12; var thirteen = new GenericComparableIntStructKey { Id = 13 }; principals = [ - context.Set().Include(e => e.RequiredDependents) - .Single(e => e.Id.Equals(new GenericComparableIntStructKey { Id = 11 })), - context.Set().Include(e => e.RequiredDependents) - .Single(e => e.Id.Equals(new GenericComparableIntStructKey { Id = twelve })), - context.Set().Include(e => e.RequiredDependents) - .Single(e => e.Id.Equals(thirteen)), - context.Set().Include(e => e.RequiredDependents) - .Single(e => e.Id.Equals(new GenericComparableIntStructKey { Id = 14 })) + await context.Set().Include(e => e.RequiredDependents) + .SingleAsync(e => e.Id.Equals(new GenericComparableIntStructKey { Id = 11 })), + await context.Set().Include(e => e.RequiredDependents) + .SingleAsync(e => e.Id.Equals(new GenericComparableIntStructKey { Id = twelve })), + await context.Set().Include(e => e.RequiredDependents) + .SingleAsync(e => e.Id.Equals(thirteen)), + await context.Set().Include(e => e.RequiredDependents) + .SingleAsync(e => e.Id.Equals(new GenericComparableIntStructKey { Id = 14 })) ]; var oneTwelve = 112; @@ -623,34 +617,34 @@ void RunQueries( dependents = [ - context.Set() - .FirstOrDefault(e => e.Id.Equals(new GenericComparableIntStructKey { Id = 111 })), - context.Set().FirstOrDefault( + await context.Set() + .FirstOrDefaultAsync(e => e.Id.Equals(new GenericComparableIntStructKey { Id = 111 })), + await context.Set().FirstOrDefaultAsync( e => e.Id.Equals(new GenericComparableIntStructKey { Id = oneTwelve })), - context.Set().FirstOrDefault(e => e.Id.Equals(oneThirteen)), - context.Set() - .FirstOrDefault(e => e.Id.Equals(new GenericComparableIntStructKey { Id = 114 })), - context.Set().FirstOrDefault( + await context.Set().FirstOrDefaultAsync(e => e.Id.Equals(oneThirteen)), + await context.Set() + .FirstOrDefaultAsync(e => e.Id.Equals(new GenericComparableIntStructKey { Id = 114 })), + await context.Set().FirstOrDefaultAsync( e => e.Id.Equals(new GenericComparableIntStructKey { Id = oneFifteeen })), - context.Set().FirstOrDefault(e => e.Id.Equals(oneSixteen)) + await context.Set().FirstOrDefaultAsync(e => e.Id.Equals(oneSixteen)) ]; Assert.Same( dependents[0], - context.Set().Find(new GenericComparableIntStructKey { Id = 111 })); + await context.Set().FindAsync(new GenericComparableIntStructKey { Id = 111 })); Assert.Same( dependents[1], - context.Set() - .Find(new GenericComparableIntStructKey { Id = oneTwelve })); - Assert.Same(dependents[2], context.Set().Find(oneThirteen)); + await context.Set() + .FindAsync(new GenericComparableIntStructKey { Id = oneTwelve })); + Assert.Same(dependents[2], await context.Set().FindAsync(oneThirteen)); Assert.Same( dependents[3], - context.Find(typeof(GenericComparableIntStructKeyRequiredDependent), new GenericComparableIntStructKey { Id = 114 })); + await context.FindAsync(typeof(GenericComparableIntStructKeyRequiredDependent), new GenericComparableIntStructKey { Id = 114 })); Assert.Same( dependents[4], - context.Find( + await context.FindAsync( typeof(GenericComparableIntStructKeyRequiredDependent), new GenericComparableIntStructKey { Id = oneFifteeen })); - Assert.Same(dependents[5], context.Find(typeof(GenericComparableIntStructKeyRequiredDependent), oneSixteen)); + Assert.Same(dependents[5], await context.FindAsync(typeof(GenericComparableIntStructKeyRequiredDependent), oneSixteen)); } void Validate( @@ -668,13 +662,15 @@ void Validate( } [ConditionalFact] - public virtual void Can_insert_and_read_back_with_class_key_and_optional_dependents() + public virtual async Task Can_insert_and_read_back_with_class_key_and_optional_dependents() { - InsertOptionalGraph(); + IntClassKeyPrincipal[] principals = null; + IntClassKeyOptionalDependent[] dependents = null; + await InsertOptionalGraph(); using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -696,12 +692,12 @@ public virtual void Can_insert_and_read_back_with_class_key_and_optional_depende principals[0].OptionalDependents.Add( new IntClassKeyOptionalDependent { Id = new IntClassKey(dependents[0].Id.Id), }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -710,23 +706,20 @@ public virtual void Can_insert_and_read_back_with_class_key_and_optional_depende [(0, 0), (1, null), (2, 2), (3, 0), (4, null), (5, 0)]); } - void RunQueries( - DbContext context, - out IntClassKeyPrincipal[] principals, - out IntClassKeyOptionalDependent[] dependents) + async Task RunQueries(DbContext context) { var two = 2; var three = new IntClassKey(3); principals = [ - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new IntClassKey(1))), - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new IntClassKey(two))), - context.Set().Include(e => e.OptionalDependents).Single(e => e.Id.Equals(three)), - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new IntClassKey(4))) + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new IntClassKey(1))), + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new IntClassKey(two))), + await context.Set().Include(e => e.OptionalDependents).SingleAsync(e => e.Id.Equals(three)), + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new IntClassKey(4))) ]; var oneOhTwo = 102; @@ -736,20 +729,20 @@ void RunQueries( dependents = [ - context.Set().Single(e => e.Id.Equals(new IntClassKey(101))), - context.Set().Single(e => e.Id.Equals(new IntClassKey(oneOhTwo))), - context.Set().Single(e => e.Id.Equals(oneOhThree)), - context.Set().Single(e => e.Id == new IntClassKey(104)), - context.Set().Single(e => e.Id == new IntClassKey(oneOhFive)), - context.Set().Single(e => e.Id == oneOhSix) + await context.Set().SingleAsync(e => e.Id.Equals(new IntClassKey(101))), + await context.Set().SingleAsync(e => e.Id.Equals(new IntClassKey(oneOhTwo))), + await context.Set().SingleAsync(e => e.Id.Equals(oneOhThree)), + await context.Set().SingleAsync(e => e.Id == new IntClassKey(104)), + await context.Set().SingleAsync(e => e.Id == new IntClassKey(oneOhFive)), + await context.Set().SingleAsync(e => e.Id == oneOhSix) ]; - Assert.Same(dependents[0], context.Set().Find(new IntClassKey(101))); - Assert.Same(dependents[1], context.Set().Find(new IntClassKey(oneOhTwo))); - Assert.Same(dependents[2], context.Set().Find(oneOhThree)); - Assert.Same(dependents[3], context.Find(new IntClassKey(104))); - Assert.Same(dependents[4], context.Find(new IntClassKey(oneOhFive))); - Assert.Same(dependents[5], context.Find(oneOhSix)); + Assert.Same(dependents[0], await context.Set().FindAsync(new IntClassKey(101))); + Assert.Same(dependents[1], await context.Set().FindAsync(new IntClassKey(oneOhTwo))); + Assert.Same(dependents[2], await context.Set().FindAsync(oneOhThree)); + Assert.Same(dependents[3], await context.FindAsync(new IntClassKey(104))); + Assert.Same(dependents[4], await context.FindAsync(new IntClassKey(oneOhFive))); + Assert.Same(dependents[5], await context.FindAsync(oneOhSix)); } void Validate( @@ -767,13 +760,15 @@ void Validate( } [ConditionalFact] - public virtual void Can_insert_and_read_back_with_enumerable_class_key_and_optional_dependents() + public virtual async Task Can_insert_and_read_back_with_enumerable_class_key_and_optional_dependents() { - InsertOptionalGraph(); + EnumerableClassKeyPrincipal[] principals = null; + EnumerableClassKeyOptionalDependent[] dependents = null; + await InsertOptionalGraph(); using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -795,12 +790,12 @@ public virtual void Can_insert_and_read_back_with_enumerable_class_key_and_optio principals[0].OptionalDependents.Add( new EnumerableClassKeyOptionalDependent { Id = new EnumerableClassKey(dependents[0].Id.Id), }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -809,23 +804,20 @@ public virtual void Can_insert_and_read_back_with_enumerable_class_key_and_optio [(0, 0), (1, null), (2, 2), (3, 0), (4, null), (5, 0)]); } - void RunQueries( - DbContext context, - out EnumerableClassKeyPrincipal[] principals, - out EnumerableClassKeyOptionalDependent[] dependents) + async Task RunQueries(DbContext context) { var two = 2; var three = new EnumerableClassKey(3); principals = [ - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new EnumerableClassKey(1))), - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new EnumerableClassKey(two))), - context.Set().Include(e => e.OptionalDependents).Single(e => e.Id.Equals(three)), - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new EnumerableClassKey(4))) + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new EnumerableClassKey(1))), + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new EnumerableClassKey(two))), + await context.Set().Include(e => e.OptionalDependents).SingleAsync(e => e.Id.Equals(three)), + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new EnumerableClassKey(4))) ]; var oneOhTwo = 102; @@ -835,20 +827,20 @@ void RunQueries( dependents = [ - context.Set().Single(e => e.Id.Equals(new EnumerableClassKey(101))), - context.Set().Single(e => e.Id.Equals(new EnumerableClassKey(oneOhTwo))), - context.Set().Single(e => e.Id.Equals(oneOhThree)), - context.Set().Single(e => e.Id == new EnumerableClassKey(104)), - context.Set().Single(e => e.Id == new EnumerableClassKey(oneOhFive)), - context.Set().Single(e => e.Id == oneOhSix) + await context.Set().SingleAsync(e => e.Id.Equals(new EnumerableClassKey(101))), + await context.Set().SingleAsync(e => e.Id.Equals(new EnumerableClassKey(oneOhTwo))), + await context.Set().SingleAsync(e => e.Id.Equals(oneOhThree)), + await context.Set().SingleAsync(e => e.Id == new EnumerableClassKey(104)), + await context.Set().SingleAsync(e => e.Id == new EnumerableClassKey(oneOhFive)), + await context.Set().SingleAsync(e => e.Id == oneOhSix) ]; - Assert.Same(dependents[0], context.Set().Find(new EnumerableClassKey(101))); - Assert.Same(dependents[1], context.Set().Find(new EnumerableClassKey(oneOhTwo))); - Assert.Same(dependents[2], context.Set().Find(oneOhThree)); - Assert.Same(dependents[3], context.Find(new EnumerableClassKey(104))); - Assert.Same(dependents[4], context.Find(new EnumerableClassKey(oneOhFive))); - Assert.Same(dependents[5], context.Find(oneOhSix)); + Assert.Same(dependents[0], await context.Set().FindAsync(new EnumerableClassKey(101))); + Assert.Same(dependents[1], await context.Set().FindAsync(new EnumerableClassKey(oneOhTwo))); + Assert.Same(dependents[2], await context.Set().FindAsync(oneOhThree)); + Assert.Same(dependents[3], await context.FindAsync(new EnumerableClassKey(104))); + Assert.Same(dependents[4], await context.FindAsync(new EnumerableClassKey(oneOhFive))); + Assert.Same(dependents[5], await context.FindAsync(oneOhSix)); } void Validate( @@ -866,13 +858,15 @@ void Validate( } [ConditionalFact] - public virtual void Can_insert_and_read_back_with_bare_class_key_and_optional_dependents() + public virtual async Task Can_insert_and_read_back_with_bare_class_key_and_optional_dependents() { - InsertOptionalGraph(); + BareIntClassKeyPrincipal[] principals = null; + BareIntClassKeyOptionalDependent[] dependents = null; + await InsertOptionalGraph(); using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -894,12 +888,12 @@ public virtual void Can_insert_and_read_back_with_bare_class_key_and_optional_de principals[0].OptionalDependents.Add( new BareIntClassKeyOptionalDependent { Id = new BareIntClassKey(dependents[0].Id.Id), }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -908,23 +902,20 @@ public virtual void Can_insert_and_read_back_with_bare_class_key_and_optional_de [(0, 0), (1, null), (2, 2), (3, 0), (4, null), (5, 0)]); } - void RunQueries( - DbContext context, - out BareIntClassKeyPrincipal[] principals, - out BareIntClassKeyOptionalDependent[] dependents) + async Task RunQueries(DbContext context) { var two = 2; var three = new BareIntClassKey(3); principals = [ - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new BareIntClassKey(1))), - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new BareIntClassKey(two))), - context.Set().Include(e => e.OptionalDependents).Single(e => e.Id.Equals(three)), - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new BareIntClassKey(4))) + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new BareIntClassKey(1))), + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new BareIntClassKey(two))), + await context.Set().Include(e => e.OptionalDependents).SingleAsync(e => e.Id.Equals(three)), + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new BareIntClassKey(4))) ]; var oneOhTwo = 102; @@ -934,20 +925,20 @@ void RunQueries( dependents = [ - context.Set().Single(e => e.Id.Equals(new BareIntClassKey(101))), - context.Set().Single(e => e.Id.Equals(new BareIntClassKey(oneOhTwo))), - context.Set().Single(e => e.Id.Equals(oneOhThree)), - context.Set().Single(e => e.Id == new BareIntClassKey(104)), - context.Set().Single(e => e.Id == new BareIntClassKey(oneOhFive)), - context.Set().Single(e => e.Id == oneOhSix) + await context.Set().SingleAsync(e => e.Id.Equals(new BareIntClassKey(101))), + await context.Set().SingleAsync(e => e.Id.Equals(new BareIntClassKey(oneOhTwo))), + await context.Set().SingleAsync(e => e.Id.Equals(oneOhThree)), + await context.Set().SingleAsync(e => e.Id == new BareIntClassKey(104)), + await context.Set().SingleAsync(e => e.Id == new BareIntClassKey(oneOhFive)), + await context.Set().SingleAsync(e => e.Id == oneOhSix) ]; - Assert.Same(dependents[0], context.Set().Find(new BareIntClassKey(101))); - Assert.Same(dependents[1], context.Set().Find(new BareIntClassKey(oneOhTwo))); - Assert.Same(dependents[2], context.Set().Find(oneOhThree)); - Assert.Same(dependents[3], context.Find(new BareIntClassKey(104))); - Assert.Same(dependents[4], context.Find(new BareIntClassKey(oneOhFive))); - Assert.Same(dependents[5], context.Find(oneOhSix)); + Assert.Same(dependents[0], await context.Set().FindAsync(new BareIntClassKey(101))); + Assert.Same(dependents[1], await context.Set().FindAsync(new BareIntClassKey(oneOhTwo))); + Assert.Same(dependents[2], await context.Set().FindAsync(oneOhThree)); + Assert.Same(dependents[3], await context.FindAsync(new BareIntClassKey(104))); + Assert.Same(dependents[4], await context.FindAsync(new BareIntClassKey(oneOhFive))); + Assert.Same(dependents[5], await context.FindAsync(oneOhSix)); } void Validate( @@ -965,13 +956,15 @@ void Validate( } [ConditionalFact] - public virtual void Can_insert_and_read_back_with_comparable_class_key_and_optional_dependents() + public virtual async Task Can_insert_and_read_back_with_comparable_class_key_and_optional_dependents() { - InsertOptionalGraph(); + ComparableIntClassKeyPrincipal[] principals = null; + ComparableIntClassKeyOptionalDependent[] dependents = null; + await InsertOptionalGraph(); using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -993,12 +986,12 @@ public virtual void Can_insert_and_read_back_with_comparable_class_key_and_optio principals[0].OptionalDependents.Add( new ComparableIntClassKeyOptionalDependent { Id = new ComparableIntClassKey(dependents[0].Id.Id), }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -1007,23 +1000,20 @@ public virtual void Can_insert_and_read_back_with_comparable_class_key_and_optio [(0, 0), (1, null), (2, 2), (3, 0), (4, null), (5, 0)]); } - void RunQueries( - DbContext context, - out ComparableIntClassKeyPrincipal[] principals, - out ComparableIntClassKeyOptionalDependent[] dependents) + async Task RunQueries(DbContext context) { var two = 2; var three = new ComparableIntClassKey(3); principals = [ - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new ComparableIntClassKey(1))), - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new ComparableIntClassKey(two))), - context.Set().Include(e => e.OptionalDependents).Single(e => e.Id.Equals(three)), - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new ComparableIntClassKey(4))) + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new ComparableIntClassKey(1))), + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new ComparableIntClassKey(two))), + await context.Set().Include(e => e.OptionalDependents).SingleAsync(e => e.Id.Equals(three)), + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new ComparableIntClassKey(4))) ]; var oneOhTwo = 102; @@ -1033,26 +1023,26 @@ void RunQueries( dependents = [ - context.Set() - .Single(e => e.Id.Equals(new ComparableIntClassKey(101))), - context.Set() - .Single(e => e.Id.Equals(new ComparableIntClassKey(oneOhTwo))), - context.Set().Single(e => e.Id.Equals(oneOhThree)), - context.Set().Single(e => e.Id == new ComparableIntClassKey(104)), - context.Set() - .Single(e => e.Id == new ComparableIntClassKey(oneOhFive)), - context.Set().Single(e => e.Id == oneOhSix) + await context.Set() + .SingleAsync(e => e.Id.Equals(new ComparableIntClassKey(101))), + await context.Set() + .SingleAsync(e => e.Id.Equals(new ComparableIntClassKey(oneOhTwo))), + await context.Set().SingleAsync(e => e.Id.Equals(oneOhThree)), + await context.Set().SingleAsync(e => e.Id == new ComparableIntClassKey(104)), + await context.Set() + .SingleAsync(e => e.Id == new ComparableIntClassKey(oneOhFive)), + await context.Set().SingleAsync(e => e.Id == oneOhSix) ]; Assert.Same( - dependents[0], context.Set().Find(new ComparableIntClassKey(101))); + dependents[0], await context.Set().FindAsync(new ComparableIntClassKey(101))); Assert.Same( - dependents[1], context.Set().Find(new ComparableIntClassKey(oneOhTwo))); - Assert.Same(dependents[2], context.Set().Find(oneOhThree)); - Assert.Same(dependents[3], context.Find(new ComparableIntClassKey(104))); + dependents[1], await context.Set().FindAsync(new ComparableIntClassKey(oneOhTwo))); + Assert.Same(dependents[2], await context.Set().FindAsync(oneOhThree)); + Assert.Same(dependents[3], await context.FindAsync(new ComparableIntClassKey(104))); Assert.Same( - dependents[4], context.Find(new ComparableIntClassKey(oneOhFive))); - Assert.Same(dependents[5], context.Find(oneOhSix)); + dependents[4], await context.FindAsync(new ComparableIntClassKey(oneOhFive))); + Assert.Same(dependents[5], await context.FindAsync(oneOhSix)); } void Validate( @@ -1070,13 +1060,15 @@ void Validate( } [ConditionalFact] - public virtual void Can_insert_and_read_back_with_struct_binary_key_and_optional_dependents() + public virtual async Task Can_insert_and_read_back_with_struct_binary_key_and_optional_dependents() { - InsertOptionalBytesGraph(); + BytesStructKeyPrincipal[] principals = null; + BytesStructKeyOptionalDependent[] dependents = null; + await InsertOptionalBytesGraph(); using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -1098,12 +1090,12 @@ public virtual void Can_insert_and_read_back_with_struct_binary_key_and_optional principals[0].OptionalDependents.Add( new BytesStructKeyOptionalDependent { Id = new BytesStructKey(dependents[0].Id.Id), }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -1112,23 +1104,20 @@ public virtual void Can_insert_and_read_back_with_struct_binary_key_and_optional [(0, 0), (1, null), (2, 2), (3, 0), (4, null), (5, 0)]); } - void RunQueries( - DbContext context, - out BytesStructKeyPrincipal[] principals, - out BytesStructKeyOptionalDependent[] dependents) + async Task RunQueries(DbContext context) { var two = new byte[] { 2, 2 }; var three = new BytesStructKey { Id = [3, 3, 3] }; principals = [ - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new BytesStructKey { Id = new byte[] { 1 } })), - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new BytesStructKey(two))), - context.Set().Include(e => e.OptionalDependents).Where(e => e.Id.Equals(three)).ToList() + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new BytesStructKey { Id = new byte[] { 1 } })), + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new BytesStructKey(two))), + (await context.Set().Include(e => e.OptionalDependents).Where(e => e.Id.Equals(three)).ToListAsync()) .Single(), - context.Set().Include(e => e.OptionalDependents).Single( + await context.Set().Include(e => e.OptionalDependents).SingleAsync( e => e.Id.Equals(new BytesStructKey { Id = new byte[] { 4, 4, 4, 4 } })) ]; @@ -1139,24 +1128,24 @@ void RunQueries( dependents = [ - context.Set() - .Single(e => e.Id.Equals(new BytesStructKey { Id = new byte[] { 101 } })), - context.Set().Single(e => e.Id.Equals(new BytesStructKey(oneOhTwo))), - context.Set().Single(e => e.Id.Equals(oneOhThree)), - context.Set() - .Single(e => e.Id.Equals(new BytesStructKey { Id = new byte[] { 104 } })), - context.Set().Single(e => e.Id.Equals(new BytesStructKey(oneOhFive))), - context.Set().Single(e => e.Id.Equals(oneOhSix)) + await context.Set() + .SingleAsync(e => e.Id.Equals(new BytesStructKey { Id = new byte[] { 101 } })), + await context.Set().SingleAsync(e => e.Id.Equals(new BytesStructKey(oneOhTwo))), + await context.Set().SingleAsync(e => e.Id.Equals(oneOhThree)), + await context.Set() + .SingleAsync(e => e.Id.Equals(new BytesStructKey { Id = new byte[] { 104 } })), + await context.Set().SingleAsync(e => e.Id.Equals(new BytesStructKey(oneOhFive))), + await context.Set().SingleAsync(e => e.Id.Equals(oneOhSix)) ]; Assert.Same( - dependents[0], context.Set().Find(new BytesStructKey { Id = [101] })); - Assert.Same(dependents[1], context.Set().Find(new BytesStructKey(oneOhTwo))); - Assert.Same(dependents[2], context.Set().Find(oneOhThree)); + dependents[0], await context.Set().FindAsync(new BytesStructKey { Id = [101] })); + Assert.Same(dependents[1], await context.Set().FindAsync(new BytesStructKey(oneOhTwo))); + Assert.Same(dependents[2], await context.Set().FindAsync(oneOhThree)); Assert.Same( - dependents[3], context.Find(typeof(BytesStructKeyOptionalDependent), new BytesStructKey { Id = [104] })); - Assert.Same(dependents[4], context.Find(typeof(BytesStructKeyOptionalDependent), new BytesStructKey(oneOhFive))); - Assert.Same(dependents[5], context.Find(typeof(BytesStructKeyOptionalDependent), oneOhSix)); + dependents[3], await context.FindAsync(typeof(BytesStructKeyOptionalDependent), new BytesStructKey { Id = [104] })); + Assert.Same(dependents[4], await context.FindAsync(typeof(BytesStructKeyOptionalDependent), new BytesStructKey(oneOhFive))); + Assert.Same(dependents[5], await context.FindAsync(typeof(BytesStructKeyOptionalDependent), oneOhSix)); } void Validate( @@ -1174,13 +1163,15 @@ void Validate( } [ConditionalFact] - public virtual void Can_insert_and_read_back_with_structural_struct_binary_key_and_optional_dependents() + public virtual async Task Can_insert_and_read_back_with_structural_struct_binary_key_and_optional_dependents() { - InsertOptionalBytesGraph(); + StructuralComparableBytesStructKeyPrincipal[] principals = null; + StructuralComparableBytesStructKeyOptionalDependent[] dependents = null; + await InsertOptionalBytesGraph(); using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -1205,12 +1196,12 @@ public virtual void Can_insert_and_read_back_with_structural_struct_binary_key_a Id = new StructuralComparableBytesStructKey(dependents[0].Id.Id), }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -1219,23 +1210,20 @@ public virtual void Can_insert_and_read_back_with_structural_struct_binary_key_a [(0, 0), (1, null), (2, 2), (3, 0), (4, null), (5, 0)]); } - void RunQueries( - DbContext context, - out StructuralComparableBytesStructKeyPrincipal[] principals, - out StructuralComparableBytesStructKeyOptionalDependent[] dependents) + async Task RunQueries(DbContext context) { var two = new byte[] { 2, 2 }; var three = new StructuralComparableBytesStructKey { Id = [3, 3, 3] }; principals = [ - context.Set().Include(e => e.OptionalDependents).Single( + await context.Set().Include(e => e.OptionalDependents).SingleAsync( e => e.Id.Equals(new StructuralComparableBytesStructKey { Id = new byte[] { 1 } })), - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new StructuralComparableBytesStructKey(two))), - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(three)), - context.Set().Include(e => e.OptionalDependents).Single( + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new StructuralComparableBytesStructKey(two))), + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(three)), + await context.Set().Include(e => e.OptionalDependents).SingleAsync( e => e.Id.Equals(new StructuralComparableBytesStructKey { Id = new byte[] { 4, 4, 4, 4 } })) ]; @@ -1246,38 +1234,38 @@ void RunQueries( dependents = [ - context.Set().Single( + await context.Set().SingleAsync( e => e.Id.Equals(new StructuralComparableBytesStructKey { Id = new byte[] { 101 } })), - context.Set().Single( + await context.Set().SingleAsync( e => e.Id.Equals(new StructuralComparableBytesStructKey(oneOhTwo))), - context.Set().Single(e => e.Id.Equals(oneOhThree)), - context.Set().Single( + await context.Set().SingleAsync(e => e.Id.Equals(oneOhThree)), + await context.Set().SingleAsync( e => e.Id.Equals(new StructuralComparableBytesStructKey { Id = new byte[] { 104 } })), - context.Set().Single( + await context.Set().SingleAsync( e => e.Id.Equals(new StructuralComparableBytesStructKey(oneOhFive))), - context.Set().Single(e => e.Id.Equals(oneOhSix)) + await context.Set().SingleAsync(e => e.Id.Equals(oneOhSix)) ]; Assert.Same( dependents[0], - context.Set() - .Find(new StructuralComparableBytesStructKey { Id = [101] })); + await context.Set() + .FindAsync(new StructuralComparableBytesStructKey { Id = [101] })); Assert.Same( dependents[1], - context.Set() - .Find(new StructuralComparableBytesStructKey(oneOhTwo))); - Assert.Same(dependents[2], context.Set().Find(oneOhThree)); + await context.Set() + .FindAsync(new StructuralComparableBytesStructKey(oneOhTwo))); + Assert.Same(dependents[2], await context.Set().FindAsync(oneOhThree)); Assert.Same( dependents[3], - context.Find( + await context.FindAsync( typeof(StructuralComparableBytesStructKeyOptionalDependent), new StructuralComparableBytesStructKey { Id = [104] })); Assert.Same( dependents[4], - context.Find( + await context.FindAsync( typeof(StructuralComparableBytesStructKeyOptionalDependent), new StructuralComparableBytesStructKey(oneOhFive))); - Assert.Same(dependents[5], context.Find(typeof(StructuralComparableBytesStructKeyOptionalDependent), oneOhSix)); + Assert.Same(dependents[5], await context.FindAsync(typeof(StructuralComparableBytesStructKeyOptionalDependent), oneOhSix)); } void Validate( @@ -1296,13 +1284,15 @@ void Validate( } [ConditionalFact] - public virtual void Can_insert_and_read_back_with_comparable_struct_binary_key_and_optional_dependents() + public virtual async Task Can_insert_and_read_back_with_comparable_struct_binary_key_and_optional_dependents() { - InsertOptionalBytesGraph(); + ComparableBytesStructKeyPrincipal[] principals = null; + ComparableBytesStructKeyOptionalDependent[] dependents = null; + await InsertOptionalBytesGraph(); using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -1324,12 +1314,12 @@ public virtual void Can_insert_and_read_back_with_comparable_struct_binary_key_a principals[0].OptionalDependents.Add( new ComparableBytesStructKeyOptionalDependent { Id = new ComparableBytesStructKey(dependents[0].Id.Id), }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -1338,23 +1328,20 @@ public virtual void Can_insert_and_read_back_with_comparable_struct_binary_key_a [(0, 0), (1, null), (2, 2), (3, 0), (4, null), (5, 0)]); } - void RunQueries( - DbContext context, - out ComparableBytesStructKeyPrincipal[] principals, - out ComparableBytesStructKeyOptionalDependent[] dependents) + async Task RunQueries(DbContext context) { var two = new byte[] { 2, 2 }; var three = new ComparableBytesStructKey { Id = [3, 3, 3] }; principals = [ - context.Set().Include(e => e.OptionalDependents).Single( + await context.Set().Include(e => e.OptionalDependents).SingleAsync( e => e.Id.Equals(new ComparableBytesStructKey { Id = new byte[] { 1 } })), - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new ComparableBytesStructKey(two))), - context.Set().Include(e => e.OptionalDependents).ToList() + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new ComparableBytesStructKey(two))), + (await context.Set().Include(e => e.OptionalDependents).ToListAsync()) .Where(e => e.Id.Equals(three)).ToList().Single(), - context.Set().Include(e => e.OptionalDependents).Single( + await context.Set().Include(e => e.OptionalDependents).SingleAsync( e => e.Id.Equals(new ComparableBytesStructKey { Id = new byte[] { 4, 4, 4, 4 } })) ]; @@ -1365,34 +1352,34 @@ void RunQueries( dependents = [ - context.Set().Single( + await context.Set().SingleAsync( e => e.Id.Equals(new ComparableBytesStructKey { Id = new byte[] { 101 } })), - context.Set() - .Single(e => e.Id.Equals(new ComparableBytesStructKey(oneOhTwo))), - context.Set().Single(e => e.Id.Equals(oneOhThree)), - context.Set().Single( + await context.Set() + .SingleAsync(e => e.Id.Equals(new ComparableBytesStructKey(oneOhTwo))), + await context.Set().SingleAsync(e => e.Id.Equals(oneOhThree)), + await context.Set().SingleAsync( e => e.Id.Equals(new ComparableBytesStructKey { Id = new byte[] { 104 } })), - context.Set() - .Single(e => e.Id.Equals(new ComparableBytesStructKey(oneOhFive))), - context.Set().Single(e => e.Id.Equals(oneOhSix)) + await context.Set() + .SingleAsync(e => e.Id.Equals(new ComparableBytesStructKey(oneOhFive))), + await context.Set().SingleAsync(e => e.Id.Equals(oneOhSix)) ]; Assert.Same( dependents[0], - context.Set() - .Find(new ComparableBytesStructKey { Id = [101] })); + await context.Set() + .FindAsync(new ComparableBytesStructKey { Id = [101] })); Assert.Same( dependents[1], - context.Set().Find(new ComparableBytesStructKey(oneOhTwo))); - Assert.Same(dependents[2], context.Set().Find(oneOhThree)); + await context.Set().FindAsync(new ComparableBytesStructKey(oneOhTwo))); + Assert.Same(dependents[2], await context.Set().FindAsync(oneOhThree)); Assert.Same( dependents[3], - context.Find( + await context.FindAsync( typeof(ComparableBytesStructKeyOptionalDependent), new ComparableBytesStructKey { Id = [104] })); Assert.Same( dependents[4], - context.Find(typeof(ComparableBytesStructKeyOptionalDependent), new ComparableBytesStructKey(oneOhFive))); - Assert.Same(dependents[5], context.Find(typeof(ComparableBytesStructKeyOptionalDependent), oneOhSix)); + await context.FindAsync(typeof(ComparableBytesStructKeyOptionalDependent), new ComparableBytesStructKey(oneOhFive))); + Assert.Same(dependents[5], await context.FindAsync(typeof(ComparableBytesStructKeyOptionalDependent), oneOhSix)); } void Validate( @@ -1410,13 +1397,15 @@ void Validate( } [ConditionalFact] - public virtual void Can_insert_and_read_back_with_generic_comparable_struct_binary_key_and_optional_dependents() + public virtual async Task Can_insert_and_read_back_with_generic_comparable_struct_binary_key_and_optional_dependents() { - InsertOptionalBytesGraph(); + GenericComparableBytesStructKeyPrincipal[] principals = null; + GenericComparableBytesStructKeyOptionalDependent[] dependents = null; + await InsertOptionalBytesGraph(); using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -1438,12 +1427,12 @@ public virtual void Can_insert_and_read_back_with_generic_comparable_struct_bina principals[0].OptionalDependents.Add( new GenericComparableBytesStructKeyOptionalDependent { Id = new GenericComparableBytesStructKey(dependents[0].Id.Id), }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -1452,23 +1441,20 @@ public virtual void Can_insert_and_read_back_with_generic_comparable_struct_bina [(0, 0), (1, null), (2, 2), (3, 0), (4, null), (5, 0)]); } - void RunQueries( - DbContext context, - out GenericComparableBytesStructKeyPrincipal[] principals, - out GenericComparableBytesStructKeyOptionalDependent[] dependents) + async Task RunQueries(DbContext context) { var two = new byte[] { 2, 2 }; var three = new GenericComparableBytesStructKey { Id = [3, 3, 3] }; principals = [ - context.Set().Include(e => e.OptionalDependents).Single( + await context.Set().Include(e => e.OptionalDependents).SingleAsync( e => e.Id.Equals(new GenericComparableBytesStructKey { Id = new byte[] { 1 } })), - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new GenericComparableBytesStructKey(two))), - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(three)), - context.Set().Include(e => e.OptionalDependents).Single( + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new GenericComparableBytesStructKey(two))), + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(three)), + await context.Set().Include(e => e.OptionalDependents).SingleAsync( e => e.Id.Equals(new GenericComparableBytesStructKey { Id = new byte[] { 4, 4, 4, 4 } })) ]; @@ -1479,37 +1465,37 @@ void RunQueries( dependents = [ - context.Set().Single( + await context.Set().SingleAsync( e => e.Id.Equals(new GenericComparableBytesStructKey { Id = new byte[] { 101 } })), - context.Set().Single( + await context.Set().SingleAsync( e => e.Id.Equals(new GenericComparableBytesStructKey(oneOhTwo))), - context.Set().Single(e => e.Id.Equals(oneOhThree)), - context.Set().Single( + await context.Set().SingleAsync(e => e.Id.Equals(oneOhThree)), + await context.Set().SingleAsync( e => e.Id.Equals(new GenericComparableBytesStructKey { Id = new byte[] { 104 } })), - context.Set().Single( + await context.Set().SingleAsync( e => e.Id.Equals(new GenericComparableBytesStructKey(oneOhFive))), - context.Set().Single(e => e.Id.Equals(oneOhSix)) + await context.Set().SingleAsync(e => e.Id.Equals(oneOhSix)) ]; Assert.Same( dependents[0], - context.Set() - .Find(new GenericComparableBytesStructKey { Id = [101] })); + await context.Set() + .FindAsync(new GenericComparableBytesStructKey { Id = [101] })); Assert.Same( dependents[1], - context.Set() - .Find(new GenericComparableBytesStructKey(oneOhTwo))); - Assert.Same(dependents[2], context.Set().Find(oneOhThree)); + await context.Set() + .FindAsync(new GenericComparableBytesStructKey(oneOhTwo))); + Assert.Same(dependents[2], await context.Set().FindAsync(oneOhThree)); Assert.Same( dependents[3], - context.Find( + await context.FindAsync( typeof(GenericComparableBytesStructKeyOptionalDependent), new GenericComparableBytesStructKey { Id = [104] })); Assert.Same( dependents[4], - context.Find( + await context.FindAsync( typeof(GenericComparableBytesStructKeyOptionalDependent), new GenericComparableBytesStructKey(oneOhFive))); - Assert.Same(dependents[5], context.Find(typeof(GenericComparableBytesStructKeyOptionalDependent), oneOhSix)); + Assert.Same(dependents[5], await context.FindAsync(typeof(GenericComparableBytesStructKeyOptionalDependent), oneOhSix)); } void Validate( @@ -1527,13 +1513,15 @@ void Validate( } [ConditionalFact] - public virtual void Can_insert_and_read_back_with_struct_binary_key_and_required_dependents() + public virtual async Task Can_insert_and_read_back_with_struct_binary_key_and_required_dependents() { - InsertRequiredBytesGraph(); + BytesStructKeyPrincipal[] principals = null; + BytesStructKeyRequiredDependent[] dependents = null; + await InsertRequiredBytesGraph(); using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -1555,12 +1543,12 @@ public virtual void Can_insert_and_read_back_with_struct_binary_key_and_required principals[0].RequiredDependents.Add( new BytesStructKeyRequiredDependent { Id = new BytesStructKey(dependents[0].Id.Id), }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -1569,22 +1557,19 @@ public virtual void Can_insert_and_read_back_with_struct_binary_key_and_required [(0, 0), (2, 2), (3, 0), (5, 0)]); } - void RunQueries( - DbContext context, - out BytesStructKeyPrincipal[] principals, - out BytesStructKeyRequiredDependent[] dependents) + async Task RunQueries(DbContext context) { var twelve = new byte[] { 12, 12 }; var thirteen = new BytesStructKey { Id = [13, 13, 13] }; principals = [ - context.Set().Include(e => e.RequiredDependents) - .Single(e => e.Id.Equals(new BytesStructKey { Id = new byte[] { 11 } })), - context.Set().Include(e => e.RequiredDependents) - .Single(e => e.Id.Equals(new BytesStructKey { Id = twelve })), - context.Set().Include(e => e.RequiredDependents).Single(e => e.Id.Equals(thirteen)), - context.Set().Include(e => e.RequiredDependents).Single( + await context.Set().Include(e => e.RequiredDependents) + .SingleAsync(e => e.Id.Equals(new BytesStructKey { Id = new byte[] { 11 } })), + await context.Set().Include(e => e.RequiredDependents) + .SingleAsync(e => e.Id.Equals(new BytesStructKey { Id = twelve })), + await context.Set().Include(e => e.RequiredDependents).SingleAsync(e => e.Id.Equals(thirteen)), + await context.Set().Include(e => e.RequiredDependents).SingleAsync( e => e.Id.Equals(new BytesStructKey { Id = new byte[] { 14, 14, 14, 14 } })) ]; @@ -1595,26 +1580,26 @@ void RunQueries( dependents = [ - context.Set() - .FirstOrDefault(e => e.Id.Equals(new BytesStructKey { Id = new byte[] { 111 } })), - context.Set() - .FirstOrDefault(e => e.Id.Equals(new BytesStructKey { Id = oneTwelve })), - context.Set().FirstOrDefault(e => e.Id.Equals(oneThirteen)), - context.Set() - .FirstOrDefault(e => e.Id.Equals(new BytesStructKey { Id = new byte[] { 114 } })), - context.Set() - .FirstOrDefault(e => e.Id.Equals(new BytesStructKey { Id = oneFifteeen })), - context.Set().FirstOrDefault(e => e.Id.Equals(oneSixteen)) + await context.Set() + .FirstOrDefaultAsync(e => e.Id.Equals(new BytesStructKey { Id = new byte[] { 111 } })), + await context.Set() + .FirstOrDefaultAsync(e => e.Id.Equals(new BytesStructKey { Id = oneTwelve })), + await context.Set().FirstOrDefaultAsync(e => e.Id.Equals(oneThirteen)), + await context.Set() + .FirstOrDefaultAsync(e => e.Id.Equals(new BytesStructKey { Id = new byte[] { 114 } })), + await context.Set() + .FirstOrDefaultAsync(e => e.Id.Equals(new BytesStructKey { Id = oneFifteeen })), + await context.Set().FirstOrDefaultAsync(e => e.Id.Equals(oneSixteen)) ]; Assert.Same( - dependents[0], context.Set().Find(new BytesStructKey { Id = [111] })); - Assert.Same(dependents[1], context.Set().Find(new BytesStructKey { Id = oneTwelve })); - Assert.Same(dependents[2], context.Set().Find(oneThirteen)); + dependents[0], await context.Set().FindAsync(new BytesStructKey { Id = [111] })); + Assert.Same(dependents[1], await context.Set().FindAsync(new BytesStructKey { Id = oneTwelve })); + Assert.Same(dependents[2], await context.Set().FindAsync(oneThirteen)); Assert.Same( - dependents[3], context.Find(typeof(BytesStructKeyRequiredDependent), new BytesStructKey { Id = [114] })); - Assert.Same(dependents[4], context.Find(typeof(BytesStructKeyRequiredDependent), new BytesStructKey { Id = oneFifteeen })); - Assert.Same(dependents[5], context.Find(typeof(BytesStructKeyRequiredDependent), oneSixteen)); + dependents[3], await context.FindAsync(typeof(BytesStructKeyRequiredDependent), new BytesStructKey { Id = [114] })); + Assert.Same(dependents[4], await context.FindAsync(typeof(BytesStructKeyRequiredDependent), new BytesStructKey { Id = oneFifteeen })); + Assert.Same(dependents[5], await context.FindAsync(typeof(BytesStructKeyRequiredDependent), oneSixteen)); } void Validate( @@ -1632,13 +1617,15 @@ void Validate( } [ConditionalFact] - public virtual void Can_insert_and_read_back_with_comparable_struct_binary_key_and_required_dependents() + public virtual async Task Can_insert_and_read_back_with_comparable_struct_binary_key_and_required_dependents() { - InsertRequiredBytesGraph(); + ComparableBytesStructKeyPrincipal[] principals = null; + ComparableBytesStructKeyRequiredDependent[] dependents = null; + await InsertRequiredBytesGraph(); using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -1660,12 +1647,12 @@ public virtual void Can_insert_and_read_back_with_comparable_struct_binary_key_a principals[0].RequiredDependents.Add( new ComparableBytesStructKeyRequiredDependent { Id = new ComparableBytesStructKey(dependents[0].Id.Id), }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -1674,23 +1661,20 @@ public virtual void Can_insert_and_read_back_with_comparable_struct_binary_key_a [(0, 0), (2, 2), (3, 0), (5, 0)]); } - void RunQueries( - DbContext context, - out ComparableBytesStructKeyPrincipal[] principals, - out ComparableBytesStructKeyRequiredDependent[] dependents) + async Task RunQueries(DbContext context) { var twelve = new byte[] { 12, 12 }; var thirteen = new ComparableBytesStructKey { Id = [13, 13, 13] }; principals = [ - context.Set().Include(e => e.RequiredDependents).Single( + await context.Set().Include(e => e.RequiredDependents).SingleAsync( e => e.Id.Equals(new ComparableBytesStructKey { Id = new byte[] { 11 } })), - context.Set().Include(e => e.RequiredDependents) - .Single(e => e.Id.Equals(new ComparableBytesStructKey { Id = twelve })), - context.Set().Include(e => e.RequiredDependents) - .Single(e => e.Id.Equals(thirteen)), - context.Set().Include(e => e.RequiredDependents).Single( + await context.Set().Include(e => e.RequiredDependents) + .SingleAsync(e => e.Id.Equals(new ComparableBytesStructKey { Id = twelve })), + await context.Set().Include(e => e.RequiredDependents) + .SingleAsync(e => e.Id.Equals(thirteen)), + await context.Set().Include(e => e.RequiredDependents).SingleAsync( e => e.Id.Equals(new ComparableBytesStructKey { Id = new byte[] { 14, 14, 14, 14 } })) ]; @@ -1701,34 +1685,34 @@ void RunQueries( dependents = [ - context.Set().FirstOrDefault( + await context.Set().FirstOrDefaultAsync( e => e.Id.Equals(new ComparableBytesStructKey { Id = new byte[] { 111 } })), - context.Set() - .FirstOrDefault(e => e.Id.Equals(new ComparableBytesStructKey { Id = oneTwelve })), - context.Set().FirstOrDefault(e => e.Id.Equals(oneThirteen)), - context.Set().FirstOrDefault( + await context.Set() + .FirstOrDefaultAsync(e => e.Id.Equals(new ComparableBytesStructKey { Id = oneTwelve })), + await context.Set().FirstOrDefaultAsync(e => e.Id.Equals(oneThirteen)), + await context.Set().FirstOrDefaultAsync( e => e.Id.Equals(new ComparableBytesStructKey { Id = new byte[] { 114 } })), - context.Set() - .FirstOrDefault(e => e.Id.Equals(new ComparableBytesStructKey { Id = oneFifteeen })), - context.Set().FirstOrDefault(e => e.Id.Equals(oneSixteen)) + await context.Set() + .FirstOrDefaultAsync(e => e.Id.Equals(new ComparableBytesStructKey { Id = oneFifteeen })), + await context.Set().FirstOrDefaultAsync(e => e.Id.Equals(oneSixteen)) ]; Assert.Same( dependents[0], - context.Set() - .Find(new ComparableBytesStructKey { Id = [111] })); + await context.Set() + .FindAsync(new ComparableBytesStructKey { Id = [111] })); Assert.Same( dependents[1], - context.Set().Find(new ComparableBytesStructKey { Id = oneTwelve })); - Assert.Same(dependents[2], context.Set().Find(oneThirteen)); + await context.Set().FindAsync(new ComparableBytesStructKey { Id = oneTwelve })); + Assert.Same(dependents[2], await context.Set().FindAsync(oneThirteen)); Assert.Same( dependents[3], - context.Find( + await context.FindAsync( typeof(ComparableBytesStructKeyRequiredDependent), new ComparableBytesStructKey { Id = [114] })); Assert.Same( dependents[4], - context.Find(typeof(ComparableBytesStructKeyRequiredDependent), new ComparableBytesStructKey { Id = oneFifteeen })); - Assert.Same(dependents[5], context.Find(typeof(ComparableBytesStructKeyRequiredDependent), oneSixteen)); + await context.FindAsync(typeof(ComparableBytesStructKeyRequiredDependent), new ComparableBytesStructKey { Id = oneFifteeen })); + Assert.Same(dependents[5], await context.FindAsync(typeof(ComparableBytesStructKeyRequiredDependent), oneSixteen)); } void Validate( @@ -1746,13 +1730,15 @@ void Validate( } [ConditionalFact] - public virtual void Can_insert_and_read_back_with_structural_struct_binary_key_and_required_dependents() + public virtual async Task Can_insert_and_read_back_with_structural_struct_binary_key_and_required_dependents() { - InsertRequiredBytesGraph(); + StructuralComparableBytesStructKeyPrincipal[] principals = null; + StructuralComparableBytesStructKeyRequiredDependent[] dependents = null; + await InsertRequiredBytesGraph(); using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -1777,12 +1763,12 @@ public virtual void Can_insert_and_read_back_with_structural_struct_binary_key_a Id = new StructuralComparableBytesStructKey(dependents[0].Id.Id), }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -1791,23 +1777,20 @@ public virtual void Can_insert_and_read_back_with_structural_struct_binary_key_a [(0, 0), (2, 2), (3, 0), (5, 0)]); } - void RunQueries( - DbContext context, - out StructuralComparableBytesStructKeyPrincipal[] principals, - out StructuralComparableBytesStructKeyRequiredDependent[] dependents) + async Task RunQueries(DbContext context) { var twelve = new byte[] { 12, 12 }; var thirteen = new StructuralComparableBytesStructKey { Id = [13, 13, 13] }; principals = [ - context.Set().Include(e => e.RequiredDependents).Single( + await context.Set().Include(e => e.RequiredDependents).SingleAsync( e => e.Id.Equals(new StructuralComparableBytesStructKey { Id = new byte[] { 11 } })), - context.Set().Include(e => e.RequiredDependents) - .Single(e => e.Id.Equals(new StructuralComparableBytesStructKey { Id = twelve })), - context.Set().Include(e => e.RequiredDependents) - .Single(e => e.Id.Equals(thirteen)), - context.Set().Include(e => e.RequiredDependents).Single( + await context.Set().Include(e => e.RequiredDependents) + .SingleAsync(e => e.Id.Equals(new StructuralComparableBytesStructKey { Id = twelve })), + await context.Set().Include(e => e.RequiredDependents) + .SingleAsync(e => e.Id.Equals(thirteen)), + await context.Set().Include(e => e.RequiredDependents).SingleAsync( e => e.Id.Equals(new StructuralComparableBytesStructKey { Id = new byte[] { 14, 14, 14, 14 } })) ]; @@ -1818,38 +1801,38 @@ void RunQueries( dependents = [ - context.Set().FirstOrDefault( + await context.Set().FirstOrDefaultAsync( e => e.Id.Equals(new StructuralComparableBytesStructKey { Id = new byte[] { 111 } })), - context.Set().FirstOrDefault( + await context.Set().FirstOrDefaultAsync( e => e.Id.Equals(new StructuralComparableBytesStructKey { Id = oneTwelve })), - context.Set().FirstOrDefault(e => e.Id.Equals(oneThirteen)), - context.Set().FirstOrDefault( + await context.Set().FirstOrDefaultAsync(e => e.Id.Equals(oneThirteen)), + await context.Set().FirstOrDefaultAsync( e => e.Id.Equals(new StructuralComparableBytesStructKey { Id = new byte[] { 114 } })), - context.Set().FirstOrDefault( + await context.Set().FirstOrDefaultAsync( e => e.Id.Equals(new StructuralComparableBytesStructKey { Id = oneFifteeen })), - context.Set().FirstOrDefault(e => e.Id.Equals(oneSixteen)) + await context.Set().FirstOrDefaultAsync(e => e.Id.Equals(oneSixteen)) ]; Assert.Same( dependents[0], - context.Set() - .Find(new StructuralComparableBytesStructKey { Id = [111] })); + await context.Set() + .FindAsync(new StructuralComparableBytesStructKey { Id = [111] })); Assert.Same( dependents[1], - context.Set() - .Find(new StructuralComparableBytesStructKey { Id = oneTwelve })); - Assert.Same(dependents[2], context.Set().Find(oneThirteen)); + await context.Set() + .FindAsync(new StructuralComparableBytesStructKey { Id = oneTwelve })); + Assert.Same(dependents[2], await context.Set().FindAsync(oneThirteen)); Assert.Same( dependents[3], - context.Find( + await context.FindAsync( typeof(StructuralComparableBytesStructKeyRequiredDependent), new StructuralComparableBytesStructKey { Id = [114] })); Assert.Same( dependents[4], - context.Find( + await context.FindAsync( typeof(StructuralComparableBytesStructKeyRequiredDependent), new StructuralComparableBytesStructKey { Id = oneFifteeen })); - Assert.Same(dependents[5], context.Find(typeof(StructuralComparableBytesStructKeyRequiredDependent), oneSixteen)); + Assert.Same(dependents[5], await context.FindAsync(typeof(StructuralComparableBytesStructKeyRequiredDependent), oneSixteen)); } void Validate( @@ -1868,13 +1851,15 @@ void Validate( } [ConditionalFact] - public virtual void Can_insert_and_read_back_with_generic_comparable_struct_binary_key_and_required_dependents() + public virtual async Task Can_insert_and_read_back_with_generic_comparable_struct_binary_key_and_required_dependents() { - InsertRequiredBytesGraph(); + GenericComparableBytesStructKeyPrincipal[] principals = null; + GenericComparableBytesStructKeyRequiredDependent[] dependents = null; + await InsertRequiredBytesGraph(); using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -1896,12 +1881,12 @@ public virtual void Can_insert_and_read_back_with_generic_comparable_struct_bina principals[0].RequiredDependents.Add( new GenericComparableBytesStructKeyRequiredDependent { Id = new GenericComparableBytesStructKey(dependents[0].Id.Id), }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -1910,23 +1895,20 @@ public virtual void Can_insert_and_read_back_with_generic_comparable_struct_bina [(0, 0), (2, 2), (3, 0), (5, 0)]); } - void RunQueries( - DbContext context, - out GenericComparableBytesStructKeyPrincipal[] principals, - out GenericComparableBytesStructKeyRequiredDependent[] dependents) + async Task RunQueries(DbContext context) { var twelve = new byte[] { 12, 12 }; var thirteen = new GenericComparableBytesStructKey { Id = [13, 13, 13] }; principals = [ - context.Set().Include(e => e.RequiredDependents).Single( + await context.Set().Include(e => e.RequiredDependents).SingleAsync( e => e.Id.Equals(new GenericComparableBytesStructKey { Id = new byte[] { 11 } })), - context.Set().Include(e => e.RequiredDependents) - .Single(e => e.Id.Equals(new GenericComparableBytesStructKey { Id = twelve })), - context.Set().Include(e => e.RequiredDependents) - .Single(e => e.Id.Equals(thirteen)), - context.Set().Include(e => e.RequiredDependents).Single( + await context.Set().Include(e => e.RequiredDependents) + .SingleAsync(e => e.Id.Equals(new GenericComparableBytesStructKey { Id = twelve })), + await context.Set().Include(e => e.RequiredDependents) + .SingleAsync(e => e.Id.Equals(thirteen)), + await context.Set().Include(e => e.RequiredDependents).SingleAsync( e => e.Id.Equals(new GenericComparableBytesStructKey { Id = new byte[] { 14, 14, 14, 14 } })) ]; @@ -1937,38 +1919,38 @@ void RunQueries( dependents = [ - context.Set().FirstOrDefault( + await context.Set().FirstOrDefaultAsync( e => e.Id.Equals(new GenericComparableBytesStructKey { Id = new byte[] { 111 } })), - context.Set().FirstOrDefault( + await context.Set().FirstOrDefaultAsync( e => e.Id.Equals(new GenericComparableBytesStructKey { Id = oneTwelve })), - context.Set().FirstOrDefault(e => e.Id.Equals(oneThirteen)), - context.Set().FirstOrDefault( + await context.Set().FirstOrDefaultAsync(e => e.Id.Equals(oneThirteen)), + await context.Set().FirstOrDefaultAsync( e => e.Id.Equals(new GenericComparableBytesStructKey { Id = new byte[] { 114 } })), - context.Set().FirstOrDefault( + await context.Set().FirstOrDefaultAsync( e => e.Id.Equals(new GenericComparableBytesStructKey { Id = oneFifteeen })), - context.Set().FirstOrDefault(e => e.Id.Equals(oneSixteen)) + await context.Set().FirstOrDefaultAsync(e => e.Id.Equals(oneSixteen)) ]; Assert.Same( dependents[0], - context.Set() - .Find(new GenericComparableBytesStructKey { Id = [111] })); + await context.Set() + .FindAsync(new GenericComparableBytesStructKey { Id = [111] })); Assert.Same( dependents[1], - context.Set() - .Find(new GenericComparableBytesStructKey { Id = oneTwelve })); - Assert.Same(dependents[2], context.Set().Find(oneThirteen)); + await context.Set() + .FindAsync(new GenericComparableBytesStructKey { Id = oneTwelve })); + Assert.Same(dependents[2], await context.Set().FindAsync(oneThirteen)); Assert.Same( dependents[3], - context.Find( + await context.FindAsync( typeof(GenericComparableBytesStructKeyRequiredDependent), new GenericComparableBytesStructKey { Id = [114] })); Assert.Same( dependents[4], - context.Find( + await context.FindAsync( typeof(GenericComparableBytesStructKeyRequiredDependent), new GenericComparableBytesStructKey { Id = oneFifteeen })); - Assert.Same(dependents[5], context.Find(typeof(GenericComparableBytesStructKeyRequiredDependent), oneSixteen)); + Assert.Same(dependents[5], await context.FindAsync(typeof(GenericComparableBytesStructKeyRequiredDependent), oneSixteen)); } void Validate( @@ -1986,7 +1968,7 @@ void Validate( } [ConditionalFact] - public virtual void Can_query_and_update_owned_entity_with_value_converter() + public virtual async Task Can_query_and_update_owned_entity_with_value_converter() { using (var context = CreateContext()) { @@ -1997,13 +1979,13 @@ public virtual void Can_query_and_update_owned_entity_with_value_converter() context.Add(ownedEntity); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { var key = new Key("1-1-1"); - var ownedEntity = context.Set().Single(o => o.Name == key); + var ownedEntity = await context.Set().SingleAsync(o => o.Name == key); Assert.Equal(1, ownedEntity.Text.Position); @@ -2011,183 +1993,183 @@ public virtual void Can_query_and_update_owned_entity_with_value_converter() ownedEntity.Text = updatedText; context.Set().Update(ownedEntity); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { var key = new Key("1-1-1"); - var ownedEntity = context.Set().Find(key); + var ownedEntity = await context.Set().FindAsync(key); Assert.Equal(0, ownedEntity.Text.Position); } } [ConditionalFact] - public virtual void Can_query_and_update_owned_entity_with_int_struct_key() + public virtual async Task Can_query_and_update_owned_entity_with_int_struct_key() { using (var context = CreateContext()) { context.Add(new OwnerIntStructKey(new IntStructKey(1), new OwnedIntStructKey(77))); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - var owner = context.Set().Single(o => o.Id.Equals(new IntStructKey(1))); + var owner = await context.Set().SingleAsync(o => o.Id.Equals(new IntStructKey(1))); Assert.Equal(77, owner.Owned.Position); owner.Owned = new OwnedIntStructKey(88); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - var owner = context.Set().Find(new IntStructKey(1)); + var owner = await context.Set().FindAsync(new IntStructKey(1)); Assert.Equal(88, owner.Owned.Position); } } [ConditionalFact] - public virtual void Can_query_and_update_owned_entity_with_binary_struct_key() + public virtual async Task Can_query_and_update_owned_entity_with_binary_struct_key() { using (var context = CreateContext()) { context.Add(new OwnerBytesStructKey(new BytesStructKey([1, 5, 7, 1]), new OwnedBytesStructKey(77))); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - var owner = context.Set().Single(o => o.Id.Equals(new BytesStructKey(new byte[] { 1, 5, 7, 1 }))); + var owner = await context.Set().SingleAsync(o => o.Id.Equals(new BytesStructKey(new byte[] { 1, 5, 7, 1 }))); Assert.Equal(77, owner.Owned.Position); owner.Owned = new OwnedBytesStructKey(88); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - var owner = context.Set().Find(new BytesStructKey([1, 5, 7, 1])); + var owner = await context.Set().FindAsync(new BytesStructKey([1, 5, 7, 1])); Assert.Equal(88, owner.Owned.Position); } } [ConditionalFact] - public virtual void Can_query_and_update_owned_entity_with_comparable_int_struct_key() + public virtual async Task Can_query_and_update_owned_entity_with_comparable_int_struct_key() { using (var context = CreateContext()) { context.Add(new OwnerComparableIntStructKey(new ComparableIntStructKey(1), new OwnedComparableIntStructKey(77))); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - var owner = context.Set().Single(o => o.Id.Equals(new ComparableIntStructKey(1))); + var owner = await context.Set().SingleAsync(o => o.Id.Equals(new ComparableIntStructKey(1))); Assert.Equal(77, owner.Owned.Position); owner.Owned = new OwnedComparableIntStructKey(88); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - var owner = context.Set().Find(new ComparableIntStructKey(1)); + var owner = await context.Set().FindAsync(new ComparableIntStructKey(1)); Assert.Equal(88, owner.Owned.Position); } } [ConditionalFact] - public virtual void Can_query_and_update_owned_entity_with_comparable_bytes_struct_key() + public virtual async Task Can_query_and_update_owned_entity_with_comparable_bytes_struct_key() { using (var context = CreateContext()) { context.Add( new OwnerComparableBytesStructKey( new ComparableBytesStructKey([1, 5, 7, 1]), new OwnedComparableBytesStructKey(77))); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - var owner = context.Set() - .Single(o => o.Id.Equals(new ComparableBytesStructKey(new byte[] { 1, 5, 7, 1 }))); + var owner = await context.Set() + .SingleAsync(o => o.Id.Equals(new ComparableBytesStructKey(new byte[] { 1, 5, 7, 1 }))); Assert.Equal(77, owner.Owned.Position); owner.Owned = new OwnedComparableBytesStructKey(88); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - var owner = context.Set().Find(new ComparableBytesStructKey([1, 5, 7, 1])); + var owner = await context.Set().FindAsync(new ComparableBytesStructKey([1, 5, 7, 1])); Assert.Equal(88, owner.Owned.Position); } } [ConditionalFact] - public virtual void Can_query_and_update_owned_entity_with_generic_comparable_int_struct_key() + public virtual async Task Can_query_and_update_owned_entity_with_generic_comparable_int_struct_key() { using (var context = CreateContext()) { context.Add( new OwnerGenericComparableIntStructKey( new GenericComparableIntStructKey(1), new OwnedGenericComparableIntStructKey(77))); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - var owner = context.Set() - .Single(o => o.Id.Equals(new GenericComparableIntStructKey(1))); + var owner = await context.Set() + .SingleAsync(o => o.Id.Equals(new GenericComparableIntStructKey(1))); Assert.Equal(77, owner.Owned.Position); owner.Owned = new OwnedGenericComparableIntStructKey(88); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - var owner = context.Set().Find(new GenericComparableIntStructKey(1)); + var owner = await context.Set().FindAsync(new GenericComparableIntStructKey(1)); Assert.Equal(88, owner.Owned.Position); } } [ConditionalFact] - public virtual void Can_query_and_update_owned_entity_with_generic_comparable_bytes_struct_key() + public virtual async Task Can_query_and_update_owned_entity_with_generic_comparable_bytes_struct_key() { using (var context = CreateContext()) { context.Add( new OwnerGenericComparableBytesStructKey( new GenericComparableBytesStructKey([1, 5, 7, 1]), new OwnedGenericComparableBytesStructKey(77))); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - var owner = context.Set() - .Single(o => o.Id.Equals(new GenericComparableBytesStructKey(new byte[] { 1, 5, 7, 1 }))); + var owner = await context.Set() + .SingleAsync(o => o.Id.Equals(new GenericComparableBytesStructKey(new byte[] { 1, 5, 7, 1 }))); Assert.Equal(77, owner.Owned.Position); owner.Owned = new OwnedGenericComparableBytesStructKey(88); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - var owner = context.Set() - .Find(new GenericComparableBytesStructKey([1, 5, 7, 1])); + var owner = await context.Set() + .FindAsync(new GenericComparableBytesStructKey([1, 5, 7, 1])); Assert.Equal(88, owner.Owned.Position); } } [ConditionalFact] - public virtual void Can_query_and_update_owned_entity_with_structural_generic_comparable_bytes_struct_key() + public virtual async Task Can_query_and_update_owned_entity_with_structural_generic_comparable_bytes_struct_key() { using (var context = CreateContext()) { @@ -2195,134 +2177,136 @@ public virtual void Can_query_and_update_owned_entity_with_structural_generic_co new OwnerStructuralComparableBytesStructKey( new StructuralComparableBytesStructKey([1, 5, 7, 1]), new OwnedStructuralComparableBytesStructKey(77))); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - var owner = context.Set().Single( + var owner = await context.Set().SingleAsync( o => o.Id.Equals(new StructuralComparableBytesStructKey(new byte[] { 1, 5, 7, 1 }))); Assert.Equal(77, owner.Owned.Position); owner.Owned = new OwnedStructuralComparableBytesStructKey(88); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - var owner = context.Set() - .Find(new StructuralComparableBytesStructKey([1, 5, 7, 1])); + var owner = await context.Set() + .FindAsync(new StructuralComparableBytesStructKey([1, 5, 7, 1])); Assert.Equal(88, owner.Owned.Position); } } [ConditionalFact] - public virtual void Can_query_and_update_owned_entity_with_int_class_key() + public virtual async Task Can_query_and_update_owned_entity_with_int_class_key() { using (var context = CreateContext()) { context.Add(new OwnerIntClassKey(new IntClassKey(1), new OwnedIntClassKey(77))); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - var owner = context.Set().Single(o => o.Id.Equals(new IntClassKey(1))); + var owner = await context.Set().SingleAsync(o => o.Id.Equals(new IntClassKey(1))); Assert.Equal(77, owner.Owned.Position); owner.Owned = new OwnedIntClassKey(88); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - var owner = context.Set().Find(new IntClassKey(1)); + var owner = await context.Set().FindAsync(new IntClassKey(1)); Assert.Equal(88, owner.Owned.Position); } } [ConditionalFact] - public virtual void Can_query_and_update_owned_entity_with_int_bare_class_key() + public virtual async Task Can_query_and_update_owned_entity_with_int_bare_class_key() { using (var context = CreateContext()) { context.Add(new OwnerBareIntClassKey(new BareIntClassKey(1), new OwnedBareIntClassKey(77))); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - var owner = context.Set().Single(o => o.Id.Equals(new BareIntClassKey(1))); + var owner = await context.Set().SingleAsync(o => o.Id.Equals(new BareIntClassKey(1))); Assert.Equal(77, owner.Owned.Position); owner.Owned = new OwnedBareIntClassKey(88); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - var owner = context.Set().Find(new BareIntClassKey(1)); + var owner = await context.Set().FindAsync(new BareIntClassKey(1)); Assert.Equal(88, owner.Owned.Position); } } [ConditionalFact] - public virtual void Can_query_and_update_owned_entity_with_comparable_int_class_key() + public virtual async Task Can_query_and_update_owned_entity_with_comparable_int_class_key() { using (var context = CreateContext()) { context.Add(new OwnerComparableIntClassKey(new ComparableIntClassKey(1), new OwnedComparableIntClassKey(77))); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - var owner = context.Set().Single(o => o.Id.Equals(new ComparableIntClassKey(1))); + var owner = await context.Set().SingleAsync(o => o.Id.Equals(new ComparableIntClassKey(1))); Assert.Equal(77, owner.Owned.Position); owner.Owned = new OwnedComparableIntClassKey(88); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - var owner = context.Set().Find(new ComparableIntClassKey(1)); + var owner = await context.Set().FindAsync(new ComparableIntClassKey(1)); Assert.Equal(88, owner.Owned.Position); } } [ConditionalFact] - public virtual void Can_query_and_update_owned_entity_with_generic_comparable_int_class_key() + public virtual async Task Can_query_and_update_owned_entity_with_generic_comparable_int_class_key() { using (var context = CreateContext()) { context.Add( new OwnerGenericComparableIntClassKey(new GenericComparableIntClassKey(1), new OwnedGenericComparableIntClassKey(77))); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - var owner = context.Set().Single(o => o.Id.Equals(new GenericComparableIntClassKey(1))); + var owner = await context.Set().SingleAsync(o => o.Id.Equals(new GenericComparableIntClassKey(1))); Assert.Equal(77, owner.Owned.Position); owner.Owned = new OwnedGenericComparableIntClassKey(88); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - var owner = context.Set().Find(new GenericComparableIntClassKey(1)); + var owner = await context.Set().FindAsync(new GenericComparableIntClassKey(1)); Assert.Equal(88, owner.Owned.Position); } } [ConditionalFact] - public virtual void Can_insert_and_read_back_with_struct_key_and_optional_dependents_with_shadow_FK() + public virtual async Task Can_insert_and_read_back_with_struct_key_and_optional_dependents_with_shadow_FK() { + IntStructKeyPrincipalShadow[] principals = null; + IntStructKeyOptionalDependentShadow[] dependents = null; using (var context = CreateContext()) { - var principals = new IntStructKeyPrincipalShadow[] + var principals0 = new IntStructKeyPrincipalShadow[] { new() { Id = new IntStructKey(1), Foo = "X1" }, new() { Id = new IntStructKey(2), Foo = "X2" }, @@ -2330,22 +2314,22 @@ public virtual void Can_insert_and_read_back_with_struct_key_and_optional_depend new() { Id = new IntStructKey(4), Foo = "X4" } }; - context.Set().AddRange(principals); + context.Set().AddRange(principals0); context.Set().AddRange( - new IntStructKeyOptionalDependentShadow { Id = new IntStructKey(101), Principal = principals[0] }, - new IntStructKeyOptionalDependentShadow { Id = new IntStructKey(102), Principal = principals[1] }, - new IntStructKeyOptionalDependentShadow { Id = new IntStructKey(103), Principal = principals[2] }, - new IntStructKeyOptionalDependentShadow { Id = new IntStructKey(104), Principal = principals[2] }, - new IntStructKeyOptionalDependentShadow { Id = new IntStructKey(105), Principal = principals[2] }, + new IntStructKeyOptionalDependentShadow { Id = new IntStructKey(101), Principal = principals0[0] }, + new IntStructKeyOptionalDependentShadow { Id = new IntStructKey(102), Principal = principals0[1] }, + new IntStructKeyOptionalDependentShadow { Id = new IntStructKey(103), Principal = principals0[2] }, + new IntStructKeyOptionalDependentShadow { Id = new IntStructKey(104), Principal = principals0[2] }, + new IntStructKeyOptionalDependentShadow { Id = new IntStructKey(105), Principal = principals0[2] }, new IntStructKeyOptionalDependentShadow { Id = new IntStructKey(106) }); - Assert.Equal(10, context.SaveChanges()); + Assert.Equal(10, await context.SaveChangesAsync()); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -2368,12 +2352,12 @@ public virtual void Can_insert_and_read_back_with_struct_key_and_optional_depend principals[0].OptionalDependents.Add( new IntStructKeyOptionalDependentShadow { Id = new IntStructKey(dependents[0].Id.Id), }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -2382,23 +2366,20 @@ public virtual void Can_insert_and_read_back_with_struct_key_and_optional_depend [(0, 0), (1, null), (2, 2), (3, 0), (4, null), (5, 0)]); } - void RunQueries( - DbContext context, - out IntStructKeyPrincipalShadow[] principals, - out IntStructKeyOptionalDependentShadow[] dependents) + async Task RunQueries(DbContext context) { var two = 2; var three = new IntStructKey(3); principals = [ - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new IntStructKey(1))), - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new IntStructKey(two))), - context.Set().Include(e => e.OptionalDependents).Single(e => e.Id.Equals(three)), - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new IntStructKey(4))) + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new IntStructKey(1))), + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new IntStructKey(two))), + await context.Set().Include(e => e.OptionalDependents).SingleAsync(e => e.Id.Equals(three)), + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new IntStructKey(4))) ]; var oneOhTwo = 102; @@ -2408,20 +2389,20 @@ void RunQueries( dependents = [ - context.Set().Single(e => e.Id.Equals(new IntStructKey(101))), - context.Set().Single(e => e.Id.Equals(new IntStructKey(oneOhTwo))), - context.Set().Single(e => e.Id.Equals(oneOhThree)), - context.Set().Single(e => e.Id.Equals(new IntStructKey(104))), - context.Set().Single(e => e.Id.Equals(new IntStructKey(oneOhFive))), - context.Set().Single(e => e.Id.Equals(oneOhSix)) + await context.Set().SingleAsync(e => e.Id.Equals(new IntStructKey(101))), + await context.Set().SingleAsync(e => e.Id.Equals(new IntStructKey(oneOhTwo))), + await context.Set().SingleAsync(e => e.Id.Equals(oneOhThree)), + await context.Set().SingleAsync(e => e.Id.Equals(new IntStructKey(104))), + await context.Set().SingleAsync(e => e.Id.Equals(new IntStructKey(oneOhFive))), + await context.Set().SingleAsync(e => e.Id.Equals(oneOhSix)) ]; - Assert.Same(dependents[0], context.Set().Find(new IntStructKey(101))); - Assert.Same(dependents[1], context.Set().Find(new IntStructKey(oneOhTwo))); - Assert.Same(dependents[2], context.Set().Find(oneOhThree)); - Assert.Same(dependents[3], context.Find(typeof(IntStructKeyOptionalDependentShadow), new IntStructKey(104))); - Assert.Same(dependents[4], context.Find(typeof(IntStructKeyOptionalDependentShadow), new IntStructKey(oneOhFive))); - Assert.Same(dependents[5], context.Find(typeof(IntStructKeyOptionalDependentShadow), oneOhSix)); + Assert.Same(dependents[0], await context.Set().FindAsync(new IntStructKey(101))); + Assert.Same(dependents[1], await context.Set().FindAsync(new IntStructKey(oneOhTwo))); + Assert.Same(dependents[2], await context.Set().FindAsync(oneOhThree)); + Assert.Same(dependents[3], await context.FindAsync(typeof(IntStructKeyOptionalDependentShadow), new IntStructKey(104))); + Assert.Same(dependents[4], await context.FindAsync(typeof(IntStructKeyOptionalDependentShadow), new IntStructKey(oneOhFive))); + Assert.Same(dependents[5], await context.FindAsync(typeof(IntStructKeyOptionalDependentShadow), oneOhSix)); } void Validate( @@ -2466,11 +2447,13 @@ void Validate( } [ConditionalFact] - public virtual void Can_insert_and_read_back_with_comparable_struct_key_and_optional_dependents_with_shadow_FK() + public virtual async Task Can_insert_and_read_back_with_comparable_struct_key_and_optional_dependents_with_shadow_FK() { + ComparableIntStructKeyPrincipalShadow[] principals = null; + ComparableIntStructKeyOptionalDependentShadow[] dependents = null; using (var context = CreateContext()) { - var principals = new ComparableIntStructKeyPrincipalShadow[] + var principals0 = new ComparableIntStructKeyPrincipalShadow[] { new() { Id = new ComparableIntStructKey(1), Foo = "X1" }, new() { Id = new ComparableIntStructKey(2), Foo = "X2" }, @@ -2478,22 +2461,22 @@ public virtual void Can_insert_and_read_back_with_comparable_struct_key_and_opti new() { Id = new ComparableIntStructKey(4), Foo = "X4" } }; - context.Set().AddRange(principals); + context.Set().AddRange(principals0); context.Set().AddRange( - new ComparableIntStructKeyOptionalDependentShadow { Id = new ComparableIntStructKey(101), Principal = principals[0] }, - new ComparableIntStructKeyOptionalDependentShadow { Id = new ComparableIntStructKey(102), Principal = principals[1] }, - new ComparableIntStructKeyOptionalDependentShadow { Id = new ComparableIntStructKey(103), Principal = principals[2] }, - new ComparableIntStructKeyOptionalDependentShadow { Id = new ComparableIntStructKey(104), Principal = principals[2] }, - new ComparableIntStructKeyOptionalDependentShadow { Id = new ComparableIntStructKey(105), Principal = principals[2] }, + new ComparableIntStructKeyOptionalDependentShadow { Id = new ComparableIntStructKey(101), Principal = principals0[0] }, + new ComparableIntStructKeyOptionalDependentShadow { Id = new ComparableIntStructKey(102), Principal = principals0[1] }, + new ComparableIntStructKeyOptionalDependentShadow { Id = new ComparableIntStructKey(103), Principal = principals0[2] }, + new ComparableIntStructKeyOptionalDependentShadow { Id = new ComparableIntStructKey(104), Principal = principals0[2] }, + new ComparableIntStructKeyOptionalDependentShadow { Id = new ComparableIntStructKey(105), Principal = principals0[2] }, new ComparableIntStructKeyOptionalDependentShadow { Id = new ComparableIntStructKey(106) }); - Assert.Equal(10, context.SaveChanges()); + Assert.Equal(10, await context.SaveChangesAsync()); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -2516,12 +2499,12 @@ public virtual void Can_insert_and_read_back_with_comparable_struct_key_and_opti principals[0].OptionalDependents.Add( new ComparableIntStructKeyOptionalDependentShadow { Id = new ComparableIntStructKey(dependents[0].Id.Id), }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -2530,23 +2513,20 @@ public virtual void Can_insert_and_read_back_with_comparable_struct_key_and_opti [(0, 0), (1, null), (2, 2), (3, 0), (4, null), (5, 0)]); } - void RunQueries( - DbContext context, - out ComparableIntStructKeyPrincipalShadow[] principals, - out ComparableIntStructKeyOptionalDependentShadow[] dependents) + async Task RunQueries(DbContext context) { var two = 2; var three = new ComparableIntStructKey(3); principals = [ - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new ComparableIntStructKey(1))), - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new ComparableIntStructKey(two))), - context.Set().Include(e => e.OptionalDependents).Single(e => e.Id.Equals(three)), - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new ComparableIntStructKey(4))) + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new ComparableIntStructKey(1))), + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new ComparableIntStructKey(two))), + await context.Set().Include(e => e.OptionalDependents).SingleAsync(e => e.Id.Equals(three)), + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new ComparableIntStructKey(4))) ]; var oneOhTwo = 102; @@ -2556,29 +2536,29 @@ void RunQueries( dependents = [ - context.Set() - .Single(e => e.Id.Equals(new ComparableIntStructKey(101))), - context.Set() - .Single(e => e.Id.Equals(new ComparableIntStructKey(oneOhTwo))), - context.Set().Single(e => e.Id.Equals(oneOhThree)), - context.Set() - .Single(e => e.Id.Equals(new ComparableIntStructKey(104))), - context.Set() - .Single(e => e.Id.Equals(new ComparableIntStructKey(oneOhFive))), - context.Set().Single(e => e.Id.Equals(oneOhSix)) + await context.Set() + .SingleAsync(e => e.Id.Equals(new ComparableIntStructKey(101))), + await context.Set() + .SingleAsync(e => e.Id.Equals(new ComparableIntStructKey(oneOhTwo))), + await context.Set().SingleAsync(e => e.Id.Equals(oneOhThree)), + await context.Set() + .SingleAsync(e => e.Id.Equals(new ComparableIntStructKey(104))), + await context.Set() + .SingleAsync(e => e.Id.Equals(new ComparableIntStructKey(oneOhFive))), + await context.Set().SingleAsync(e => e.Id.Equals(oneOhSix)) ]; Assert.Same( - dependents[0], context.Set().Find(new ComparableIntStructKey(101))); + dependents[0], await context.Set().FindAsync(new ComparableIntStructKey(101))); Assert.Same( - dependents[1], context.Set().Find(new ComparableIntStructKey(oneOhTwo))); - Assert.Same(dependents[2], context.Set().Find(oneOhThree)); + dependents[1], await context.Set().FindAsync(new ComparableIntStructKey(oneOhTwo))); + Assert.Same(dependents[2], await context.Set().FindAsync(oneOhThree)); Assert.Same( - dependents[3], context.Find(typeof(ComparableIntStructKeyOptionalDependentShadow), new ComparableIntStructKey(104))); + dependents[3], await context.FindAsync(typeof(ComparableIntStructKeyOptionalDependentShadow), new ComparableIntStructKey(104))); Assert.Same( dependents[4], - context.Find(typeof(ComparableIntStructKeyOptionalDependentShadow), new ComparableIntStructKey(oneOhFive))); - Assert.Same(dependents[5], context.Find(typeof(ComparableIntStructKeyOptionalDependentShadow), oneOhSix)); + await context.FindAsync(typeof(ComparableIntStructKeyOptionalDependentShadow), new ComparableIntStructKey(oneOhFive))); + Assert.Same(dependents[5], await context.FindAsync(typeof(ComparableIntStructKeyOptionalDependentShadow), oneOhSix)); } void Validate( @@ -2623,11 +2603,13 @@ void Validate( } [ConditionalFact] - public virtual void Can_insert_and_read_back_with_generic_comparable_struct_key_and_optional_dependents_with_shadow_FK() + public virtual async Task Can_insert_and_read_back_with_generic_comparable_struct_key_and_optional_dependents_with_shadow_FK() { + GenericComparableIntStructKeyPrincipalShadow[] principals = null; + GenericComparableIntStructKeyOptionalDependentShadow[] dependents = null; using (var context = CreateContext()) { - var principals = new GenericComparableIntStructKeyPrincipalShadow[] + var principals0 = new GenericComparableIntStructKeyPrincipalShadow[] { new() { Id = new GenericComparableIntStructKey(1), Foo = "X1" }, new() { Id = new GenericComparableIntStructKey(2), Foo = "X2" }, @@ -2635,37 +2617,37 @@ public virtual void Can_insert_and_read_back_with_generic_comparable_struct_key_ new() { Id = new GenericComparableIntStructKey(4), Foo = "X4" } }; - context.Set().AddRange(principals); + context.Set().AddRange(principals0); context.Set().AddRange( new GenericComparableIntStructKeyOptionalDependentShadow { - Id = new GenericComparableIntStructKey(101), Principal = principals[0] + Id = new GenericComparableIntStructKey(101), Principal = principals0[0] }, new GenericComparableIntStructKeyOptionalDependentShadow { - Id = new GenericComparableIntStructKey(102), Principal = principals[1] + Id = new GenericComparableIntStructKey(102), Principal = principals0[1] }, new GenericComparableIntStructKeyOptionalDependentShadow { - Id = new GenericComparableIntStructKey(103), Principal = principals[2] + Id = new GenericComparableIntStructKey(103), Principal = principals0[2] }, new GenericComparableIntStructKeyOptionalDependentShadow { - Id = new GenericComparableIntStructKey(104), Principal = principals[2] + Id = new GenericComparableIntStructKey(104), Principal = principals0[2] }, new GenericComparableIntStructKeyOptionalDependentShadow { - Id = new GenericComparableIntStructKey(105), Principal = principals[2] + Id = new GenericComparableIntStructKey(105), Principal = principals0[2] }, new GenericComparableIntStructKeyOptionalDependentShadow { Id = new GenericComparableIntStructKey(106) }); - Assert.Equal(10, context.SaveChanges()); + Assert.Equal(10, await context.SaveChangesAsync()); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -2687,12 +2669,12 @@ public virtual void Can_insert_and_read_back_with_generic_comparable_struct_key_ principals[0].OptionalDependents.Add( new GenericComparableIntStructKeyOptionalDependentShadow { Id = new GenericComparableIntStructKey(dependents[0].Id.Id), }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -2701,24 +2683,21 @@ public virtual void Can_insert_and_read_back_with_generic_comparable_struct_key_ [(0, 0), (1, null), (2, 2), (3, 0), (4, null), (5, 0)]); } - void RunQueries( - DbContext context, - out GenericComparableIntStructKeyPrincipalShadow[] principals, - out GenericComparableIntStructKeyOptionalDependentShadow[] dependents) + async Task RunQueries(DbContext context) { var two = 2; var three = new GenericComparableIntStructKey(3); principals = [ - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new GenericComparableIntStructKey(1))), - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new GenericComparableIntStructKey(two))), - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(three)), - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new GenericComparableIntStructKey(4))) + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new GenericComparableIntStructKey(1))), + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new GenericComparableIntStructKey(two))), + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(three)), + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new GenericComparableIntStructKey(4))) ]; var oneOhTwo = 102; @@ -2728,33 +2707,33 @@ void RunQueries( dependents = [ - context.Set() - .Single(e => e.Id.Equals(new GenericComparableIntStructKey(101))), - context.Set() - .Single(e => e.Id.Equals(new GenericComparableIntStructKey(oneOhTwo))), - context.Set().Single(e => e.Id.Equals(oneOhThree)), - context.Set() - .Single(e => e.Id.Equals(new GenericComparableIntStructKey(104))), - context.Set() - .Single(e => e.Id.Equals(new GenericComparableIntStructKey(oneOhFive))), - context.Set().Single(e => e.Id.Equals(oneOhSix)) + await context.Set() + .SingleAsync(e => e.Id.Equals(new GenericComparableIntStructKey(101))), + await context.Set() + .SingleAsync(e => e.Id.Equals(new GenericComparableIntStructKey(oneOhTwo))), + await context.Set().SingleAsync(e => e.Id.Equals(oneOhThree)), + await context.Set() + .SingleAsync(e => e.Id.Equals(new GenericComparableIntStructKey(104))), + await context.Set() + .SingleAsync(e => e.Id.Equals(new GenericComparableIntStructKey(oneOhFive))), + await context.Set().SingleAsync(e => e.Id.Equals(oneOhSix)) ]; Assert.Same( dependents[0], - context.Set().Find(new GenericComparableIntStructKey(101))); + await context.Set().FindAsync(new GenericComparableIntStructKey(101))); Assert.Same( dependents[1], - context.Set().Find(new GenericComparableIntStructKey(oneOhTwo))); - Assert.Same(dependents[2], context.Set().Find(oneOhThree)); + await context.Set().FindAsync(new GenericComparableIntStructKey(oneOhTwo))); + Assert.Same(dependents[2], await context.Set().FindAsync(oneOhThree)); Assert.Same( dependents[3], - context.Find(typeof(GenericComparableIntStructKeyOptionalDependentShadow), new GenericComparableIntStructKey(104))); + await context.FindAsync(typeof(GenericComparableIntStructKeyOptionalDependentShadow), new GenericComparableIntStructKey(104))); Assert.Same( dependents[4], - context.Find( + await context.FindAsync( typeof(GenericComparableIntStructKeyOptionalDependentShadow), new GenericComparableIntStructKey(oneOhFive))); - Assert.Same(dependents[5], context.Find(typeof(GenericComparableIntStructKeyOptionalDependentShadow), oneOhSix)); + Assert.Same(dependents[5], await context.FindAsync(typeof(GenericComparableIntStructKeyOptionalDependentShadow), oneOhSix)); } void Validate( @@ -2799,11 +2778,13 @@ void Validate( } [ConditionalFact] - public virtual void Can_insert_and_read_back_with_struct_key_and_required_dependents_with_shadow_FK() + public virtual async Task Can_insert_and_read_back_with_struct_key_and_required_dependents_with_shadow_FK() { + IntStructKeyPrincipalShadow[] principals = null; + IntStructKeyRequiredDependentShadow[] dependents = null; using (var context = CreateContext()) { - var principals = new IntStructKeyPrincipalShadow[] + var principals0 = new IntStructKeyPrincipalShadow[] { new() { Id = new IntStructKey(11), Foo = "X1" }, new() { Id = new IntStructKey(12), Foo = "X2" }, @@ -2811,22 +2792,22 @@ public virtual void Can_insert_and_read_back_with_struct_key_and_required_depend new() { Id = new IntStructKey(14), Foo = "X4" } }; - context.Set().AddRange(principals); + context.Set().AddRange(principals0); context.Set().AddRange( - new IntStructKeyRequiredDependentShadow { Id = new IntStructKey(111), Principal = principals[0] }, - new IntStructKeyRequiredDependentShadow { Id = new IntStructKey(112), Principal = principals[1] }, - new IntStructKeyRequiredDependentShadow { Id = new IntStructKey(113), Principal = principals[2] }, - new IntStructKeyRequiredDependentShadow { Id = new IntStructKey(114), Principal = principals[2] }, - new IntStructKeyRequiredDependentShadow { Id = new IntStructKey(115), Principal = principals[2] }, - new IntStructKeyRequiredDependentShadow { Id = new IntStructKey(116), Principal = principals[2] }); + new IntStructKeyRequiredDependentShadow { Id = new IntStructKey(111), Principal = principals0[0] }, + new IntStructKeyRequiredDependentShadow { Id = new IntStructKey(112), Principal = principals0[1] }, + new IntStructKeyRequiredDependentShadow { Id = new IntStructKey(113), Principal = principals0[2] }, + new IntStructKeyRequiredDependentShadow { Id = new IntStructKey(114), Principal = principals0[2] }, + new IntStructKeyRequiredDependentShadow { Id = new IntStructKey(115), Principal = principals0[2] }, + new IntStructKeyRequiredDependentShadow { Id = new IntStructKey(116), Principal = principals0[2] }); - Assert.Equal(10, context.SaveChanges()); + Assert.Equal(10, await context.SaveChangesAsync()); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -2848,12 +2829,12 @@ public virtual void Can_insert_and_read_back_with_struct_key_and_required_depend principals[0].RequiredDependents.Add( new IntStructKeyRequiredDependentShadow { Id = new IntStructKey(dependents[0].Id.Id), }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -2862,23 +2843,20 @@ public virtual void Can_insert_and_read_back_with_struct_key_and_required_depend [(0, 0), (2, 2), (3, 0), (5, 0)]); } - void RunQueries( - DbContext context, - out IntStructKeyPrincipalShadow[] principals, - out IntStructKeyRequiredDependentShadow[] dependents) + async Task RunQueries(DbContext context) { var twelve = 12; var thirteen = new IntStructKey { Id = 13 }; principals = [ - context.Set().Include(e => e.RequiredDependents) - .Single(e => e.Id.Equals(new IntStructKey { Id = 11 })), - context.Set().Include(e => e.RequiredDependents) - .Single(e => e.Id.Equals(new IntStructKey { Id = twelve })), - context.Set().Include(e => e.RequiredDependents).Single(e => e.Id.Equals(thirteen)), - context.Set().Include(e => e.RequiredDependents) - .Single(e => e.Id.Equals(new IntStructKey { Id = 14 })) + await context.Set().Include(e => e.RequiredDependents) + .SingleAsync(e => e.Id.Equals(new IntStructKey { Id = 11 })), + await context.Set().Include(e => e.RequiredDependents) + .SingleAsync(e => e.Id.Equals(new IntStructKey { Id = twelve })), + await context.Set().Include(e => e.RequiredDependents).SingleAsync(e => e.Id.Equals(thirteen)), + await context.Set().Include(e => e.RequiredDependents) + .SingleAsync(e => e.Id.Equals(new IntStructKey { Id = 14 })) ]; var oneTwelve = 112; @@ -2888,23 +2866,23 @@ void RunQueries( dependents = [ - context.Set().FirstOrDefault(e => e.Id.Equals(new IntStructKey { Id = 111 })), - context.Set() - .FirstOrDefault(e => e.Id.Equals(new IntStructKey { Id = oneTwelve })), - context.Set().FirstOrDefault(e => e.Id.Equals(oneThirteen)), - context.Set().FirstOrDefault(e => e.Id.Equals(new IntStructKey { Id = 114 })), - context.Set() - .FirstOrDefault(e => e.Id.Equals(new IntStructKey { Id = oneFifteeen })), - context.Set().FirstOrDefault(e => e.Id.Equals(oneSixteen)) + await context.Set().FirstOrDefaultAsync(e => e.Id.Equals(new IntStructKey { Id = 111 })), + await context.Set() + .FirstOrDefaultAsync(e => e.Id.Equals(new IntStructKey { Id = oneTwelve })), + await context.Set().FirstOrDefaultAsync(e => e.Id.Equals(oneThirteen)), + await context.Set().FirstOrDefaultAsync(e => e.Id.Equals(new IntStructKey { Id = 114 })), + await context.Set() + .FirstOrDefaultAsync(e => e.Id.Equals(new IntStructKey { Id = oneFifteeen })), + await context.Set().FirstOrDefaultAsync(e => e.Id.Equals(oneSixteen)) ]; - Assert.Same(dependents[0], context.Set().Find(new IntStructKey { Id = 111 })); - Assert.Same(dependents[1], context.Set().Find(new IntStructKey { Id = oneTwelve })); - Assert.Same(dependents[2], context.Set().Find(oneThirteen)); - Assert.Same(dependents[3], context.Find(typeof(IntStructKeyRequiredDependentShadow), new IntStructKey { Id = 114 })); + Assert.Same(dependents[0], await context.Set().FindAsync(new IntStructKey { Id = 111 })); + Assert.Same(dependents[1], await context.Set().FindAsync(new IntStructKey { Id = oneTwelve })); + Assert.Same(dependents[2], await context.Set().FindAsync(oneThirteen)); + Assert.Same(dependents[3], await context.FindAsync(typeof(IntStructKeyRequiredDependentShadow), new IntStructKey { Id = 114 })); Assert.Same( - dependents[4], context.Find(typeof(IntStructKeyRequiredDependentShadow), new IntStructKey { Id = oneFifteeen })); - Assert.Same(dependents[5], context.Find(typeof(IntStructKeyRequiredDependentShadow), oneSixteen)); + dependents[4], await context.FindAsync(typeof(IntStructKeyRequiredDependentShadow), new IntStructKey { Id = oneFifteeen })); + Assert.Same(dependents[5], await context.FindAsync(typeof(IntStructKeyRequiredDependentShadow), oneSixteen)); } void Validate( @@ -2945,11 +2923,13 @@ void Validate( } [ConditionalFact] - public virtual void Can_insert_and_read_back_with_comparable_struct_key_and_required_dependents_with_shadow_FK() + public virtual async Task Can_insert_and_read_back_with_comparable_struct_key_and_required_dependents_with_shadow_FK() { + ComparableIntStructKeyPrincipalShadow[] principals = null; + ComparableIntStructKeyRequiredDependentShadow[] dependents = null; using (var context = CreateContext()) { - var principals = new ComparableIntStructKeyPrincipalShadow[] + var principals0 = new ComparableIntStructKeyPrincipalShadow[] { new() { Id = new ComparableIntStructKey(11), Foo = "X1" }, new() { Id = new ComparableIntStructKey(12), Foo = "X2" }, @@ -2957,22 +2937,22 @@ public virtual void Can_insert_and_read_back_with_comparable_struct_key_and_requ new() { Id = new ComparableIntStructKey(14), Foo = "X4" } }; - context.Set().AddRange(principals); + context.Set().AddRange(principals0); context.Set().AddRange( - new ComparableIntStructKeyRequiredDependentShadow { Id = new ComparableIntStructKey(111), Principal = principals[0] }, - new ComparableIntStructKeyRequiredDependentShadow { Id = new ComparableIntStructKey(112), Principal = principals[1] }, - new ComparableIntStructKeyRequiredDependentShadow { Id = new ComparableIntStructKey(113), Principal = principals[2] }, - new ComparableIntStructKeyRequiredDependentShadow { Id = new ComparableIntStructKey(114), Principal = principals[2] }, - new ComparableIntStructKeyRequiredDependentShadow { Id = new ComparableIntStructKey(115), Principal = principals[2] }, - new ComparableIntStructKeyRequiredDependentShadow { Id = new ComparableIntStructKey(116), Principal = principals[2] }); + new ComparableIntStructKeyRequiredDependentShadow { Id = new ComparableIntStructKey(111), Principal = principals0[0] }, + new ComparableIntStructKeyRequiredDependentShadow { Id = new ComparableIntStructKey(112), Principal = principals0[1] }, + new ComparableIntStructKeyRequiredDependentShadow { Id = new ComparableIntStructKey(113), Principal = principals0[2] }, + new ComparableIntStructKeyRequiredDependentShadow { Id = new ComparableIntStructKey(114), Principal = principals0[2] }, + new ComparableIntStructKeyRequiredDependentShadow { Id = new ComparableIntStructKey(115), Principal = principals0[2] }, + new ComparableIntStructKeyRequiredDependentShadow { Id = new ComparableIntStructKey(116), Principal = principals0[2] }); - Assert.Equal(10, context.SaveChanges()); + Assert.Equal(10, await context.SaveChangesAsync()); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -2994,12 +2974,12 @@ public virtual void Can_insert_and_read_back_with_comparable_struct_key_and_requ principals[0].RequiredDependents.Add( new ComparableIntStructKeyRequiredDependentShadow { Id = new ComparableIntStructKey(dependents[0].Id.Id), }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -3008,24 +2988,21 @@ public virtual void Can_insert_and_read_back_with_comparable_struct_key_and_requ [(0, 0), (2, 2), (3, 0), (5, 0)]); } - void RunQueries( - DbContext context, - out ComparableIntStructKeyPrincipalShadow[] principals, - out ComparableIntStructKeyRequiredDependentShadow[] dependents) + async Task RunQueries(DbContext context) { var twelve = 12; var thirteen = new ComparableIntStructKey { Id = 13 }; principals = [ - context.Set().Include(e => e.RequiredDependents) - .Single(e => e.Id.Equals(new ComparableIntStructKey { Id = 11 })), - context.Set().Include(e => e.RequiredDependents) - .Single(e => e.Id.Equals(new ComparableIntStructKey { Id = twelve })), - context.Set().Include(e => e.RequiredDependents) - .Single(e => e.Id.Equals(thirteen)), - context.Set().Include(e => e.RequiredDependents) - .Single(e => e.Id.Equals(new ComparableIntStructKey { Id = 14 })) + await context.Set().Include(e => e.RequiredDependents) + .SingleAsync(e => e.Id.Equals(new ComparableIntStructKey { Id = 11 })), + await context.Set().Include(e => e.RequiredDependents) + .SingleAsync(e => e.Id.Equals(new ComparableIntStructKey { Id = twelve })), + await context.Set().Include(e => e.RequiredDependents) + .SingleAsync(e => e.Id.Equals(thirteen)), + await context.Set().Include(e => e.RequiredDependents) + .SingleAsync(e => e.Id.Equals(new ComparableIntStructKey { Id = 14 })) ]; var oneTwelve = 112; @@ -3035,32 +3012,32 @@ void RunQueries( dependents = [ - context.Set() - .FirstOrDefault(e => e.Id.Equals(new ComparableIntStructKey { Id = 111 })), - context.Set() - .FirstOrDefault(e => e.Id.Equals(new ComparableIntStructKey { Id = oneTwelve })), - context.Set().FirstOrDefault(e => e.Id.Equals(oneThirteen)), - context.Set() - .FirstOrDefault(e => e.Id.Equals(new ComparableIntStructKey { Id = 114 })), - context.Set() - .FirstOrDefault(e => e.Id.Equals(new ComparableIntStructKey { Id = oneFifteeen })), - context.Set().FirstOrDefault(e => e.Id.Equals(oneSixteen)) + await context.Set() + .FirstOrDefaultAsync(e => e.Id.Equals(new ComparableIntStructKey { Id = 111 })), + await context.Set() + .FirstOrDefaultAsync(e => e.Id.Equals(new ComparableIntStructKey { Id = oneTwelve })), + await context.Set().FirstOrDefaultAsync(e => e.Id.Equals(oneThirteen)), + await context.Set() + .FirstOrDefaultAsync(e => e.Id.Equals(new ComparableIntStructKey { Id = 114 })), + await context.Set() + .FirstOrDefaultAsync(e => e.Id.Equals(new ComparableIntStructKey { Id = oneFifteeen })), + await context.Set().FirstOrDefaultAsync(e => e.Id.Equals(oneSixteen)) ]; Assert.Same( dependents[0], - context.Set().Find(new ComparableIntStructKey { Id = 111 })); + await context.Set().FindAsync(new ComparableIntStructKey { Id = 111 })); Assert.Same( dependents[1], - context.Set().Find(new ComparableIntStructKey { Id = oneTwelve })); - Assert.Same(dependents[2], context.Set().Find(oneThirteen)); + await context.Set().FindAsync(new ComparableIntStructKey { Id = oneTwelve })); + Assert.Same(dependents[2], await context.Set().FindAsync(oneThirteen)); Assert.Same( dependents[3], - context.Find(typeof(ComparableIntStructKeyRequiredDependentShadow), new ComparableIntStructKey { Id = 114 })); + await context.FindAsync(typeof(ComparableIntStructKeyRequiredDependentShadow), new ComparableIntStructKey { Id = 114 })); Assert.Same( dependents[4], - context.Find(typeof(ComparableIntStructKeyRequiredDependentShadow), new ComparableIntStructKey { Id = oneFifteeen })); - Assert.Same(dependents[5], context.Find(typeof(ComparableIntStructKeyRequiredDependentShadow), oneSixteen)); + await context.FindAsync(typeof(ComparableIntStructKeyRequiredDependentShadow), new ComparableIntStructKey { Id = oneFifteeen })); + Assert.Same(dependents[5], await context.FindAsync(typeof(ComparableIntStructKeyRequiredDependentShadow), oneSixteen)); } void Validate( @@ -3101,11 +3078,13 @@ void Validate( } [ConditionalFact] - public virtual void Can_insert_and_read_back_with_generic_comparable_struct_key_and_required_dependents_with_shadow_FK() + public virtual async Task Can_insert_and_read_back_with_generic_comparable_struct_key_and_required_dependents_with_shadow_FK() { + GenericComparableIntStructKeyPrincipalShadow[] principals = null; + GenericComparableIntStructKeyRequiredDependentShadow[] dependents = null; using (var context = CreateContext()) { - var principals = new GenericComparableIntStructKeyPrincipalShadow[] + var principals0 = new GenericComparableIntStructKeyPrincipalShadow[] { new() { Id = new GenericComparableIntStructKey(11), Foo = "X1" }, new() { Id = new GenericComparableIntStructKey(12), Foo = "X2" }, @@ -3113,40 +3092,40 @@ public virtual void Can_insert_and_read_back_with_generic_comparable_struct_key_ new() { Id = new GenericComparableIntStructKey(14), Foo = "X4" } }; - context.Set().AddRange(principals); + context.Set().AddRange(principals0); context.Set().AddRange( new GenericComparableIntStructKeyRequiredDependentShadow { - Id = new GenericComparableIntStructKey(111), Principal = principals[0] + Id = new GenericComparableIntStructKey(111), Principal = principals0[0] }, new GenericComparableIntStructKeyRequiredDependentShadow { - Id = new GenericComparableIntStructKey(112), Principal = principals[1] + Id = new GenericComparableIntStructKey(112), Principal = principals0[1] }, new GenericComparableIntStructKeyRequiredDependentShadow { - Id = new GenericComparableIntStructKey(113), Principal = principals[2] + Id = new GenericComparableIntStructKey(113), Principal = principals0[2] }, new GenericComparableIntStructKeyRequiredDependentShadow { - Id = new GenericComparableIntStructKey(114), Principal = principals[2] + Id = new GenericComparableIntStructKey(114), Principal = principals0[2] }, new GenericComparableIntStructKeyRequiredDependentShadow { - Id = new GenericComparableIntStructKey(115), Principal = principals[2] + Id = new GenericComparableIntStructKey(115), Principal = principals0[2] }, new GenericComparableIntStructKeyRequiredDependentShadow { - Id = new GenericComparableIntStructKey(116), Principal = principals[2] + Id = new GenericComparableIntStructKey(116), Principal = principals0[2] }); - Assert.Equal(10, context.SaveChanges()); + Assert.Equal(10, await context.SaveChangesAsync()); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -3168,12 +3147,12 @@ public virtual void Can_insert_and_read_back_with_generic_comparable_struct_key_ principals[0].RequiredDependents.Add( new GenericComparableIntStructKeyRequiredDependentShadow { Id = new GenericComparableIntStructKey(dependents[0].Id.Id), }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -3182,24 +3161,21 @@ public virtual void Can_insert_and_read_back_with_generic_comparable_struct_key_ [(0, 0), (2, 2), (3, 0), (5, 0)]); } - void RunQueries( - DbContext context, - out GenericComparableIntStructKeyPrincipalShadow[] principals, - out GenericComparableIntStructKeyRequiredDependentShadow[] dependents) + async Task RunQueries(DbContext context) { var twelve = 12; var thirteen = new GenericComparableIntStructKey { Id = 13 }; principals = [ - context.Set().Include(e => e.RequiredDependents) - .Single(e => e.Id.Equals(new GenericComparableIntStructKey { Id = 11 })), - context.Set().Include(e => e.RequiredDependents) - .Single(e => e.Id.Equals(new GenericComparableIntStructKey { Id = twelve })), - context.Set().Include(e => e.RequiredDependents) - .Single(e => e.Id.Equals(thirteen)), - context.Set().Include(e => e.RequiredDependents) - .Single(e => e.Id.Equals(new GenericComparableIntStructKey { Id = 14 })) + await context.Set().Include(e => e.RequiredDependents) + .SingleAsync(e => e.Id.Equals(new GenericComparableIntStructKey { Id = 11 })), + await context.Set().Include(e => e.RequiredDependents) + .SingleAsync(e => e.Id.Equals(new GenericComparableIntStructKey { Id = twelve })), + await context.Set().Include(e => e.RequiredDependents) + .SingleAsync(e => e.Id.Equals(thirteen)), + await context.Set().Include(e => e.RequiredDependents) + .SingleAsync(e => e.Id.Equals(new GenericComparableIntStructKey { Id = 14 })) ]; var oneTwelve = 112; @@ -3209,37 +3185,37 @@ void RunQueries( dependents = [ - context.Set() - .FirstOrDefault(e => e.Id.Equals(new GenericComparableIntStructKey { Id = 111 })), - context.Set() - .FirstOrDefault(e => e.Id.Equals(new GenericComparableIntStructKey { Id = oneTwelve })), - context.Set().FirstOrDefault(e => e.Id.Equals(oneThirteen)), - context.Set() - .FirstOrDefault(e => e.Id.Equals(new GenericComparableIntStructKey { Id = 114 })), - context.Set() - .FirstOrDefault(e => e.Id.Equals(new GenericComparableIntStructKey { Id = oneFifteeen })), - context.Set().FirstOrDefault(e => e.Id.Equals(oneSixteen)) + await context.Set() + .FirstOrDefaultAsync(e => e.Id.Equals(new GenericComparableIntStructKey { Id = 111 })), + await context.Set() + .FirstOrDefaultAsync(e => e.Id.Equals(new GenericComparableIntStructKey { Id = oneTwelve })), + await context.Set().FirstOrDefaultAsync(e => e.Id.Equals(oneThirteen)), + await context.Set() + .FirstOrDefaultAsync(e => e.Id.Equals(new GenericComparableIntStructKey { Id = 114 })), + await context.Set() + .FirstOrDefaultAsync(e => e.Id.Equals(new GenericComparableIntStructKey { Id = oneFifteeen })), + await context.Set().FirstOrDefaultAsync(e => e.Id.Equals(oneSixteen)) ]; Assert.Same( dependents[0], - context.Set() - .Find(new GenericComparableIntStructKey { Id = 111 })); + await context.Set() + .FindAsync(new GenericComparableIntStructKey { Id = 111 })); Assert.Same( dependents[1], - context.Set() - .Find(new GenericComparableIntStructKey { Id = oneTwelve })); - Assert.Same(dependents[2], context.Set().Find(oneThirteen)); + await context.Set() + .FindAsync(new GenericComparableIntStructKey { Id = oneTwelve })); + Assert.Same(dependents[2], await context.Set().FindAsync(oneThirteen)); Assert.Same( dependents[3], - context.Find( + await context.FindAsync( typeof(GenericComparableIntStructKeyRequiredDependentShadow), new GenericComparableIntStructKey { Id = 114 })); Assert.Same( dependents[4], - context.Find( + await context.FindAsync( typeof(GenericComparableIntStructKeyRequiredDependentShadow), new GenericComparableIntStructKey { Id = oneFifteeen })); - Assert.Same(dependents[5], context.Find(typeof(GenericComparableIntStructKeyRequiredDependentShadow), oneSixteen)); + Assert.Same(dependents[5], await context.FindAsync(typeof(GenericComparableIntStructKeyRequiredDependentShadow), oneSixteen)); } void Validate( @@ -3280,11 +3256,13 @@ void Validate( } [ConditionalFact] - public virtual void Can_insert_and_read_back_with_class_key_and_optional_dependents_with_shadow_FK() + public virtual async Task Can_insert_and_read_back_with_class_key_and_optional_dependents_with_shadow_FK() { + IntClassKeyPrincipalShadow[] principals = null; + IntClassKeyOptionalDependentShadow[] dependents = null; using (var context = CreateContext()) { - var principals = new IntClassKeyPrincipalShadow[] + var principals0 = new IntClassKeyPrincipalShadow[] { new() { Id = new IntClassKey(1), Foo = "X1" }, new() { Id = new IntClassKey(2), Foo = "X2" }, @@ -3292,22 +3270,22 @@ public virtual void Can_insert_and_read_back_with_class_key_and_optional_depende new() { Id = new IntClassKey(4), Foo = "X4" } }; - context.Set().AddRange(principals); + context.Set().AddRange(principals0); context.Set().AddRange( - new IntClassKeyOptionalDependentShadow { Id = new IntClassKey(101), Principal = principals[0] }, - new IntClassKeyOptionalDependentShadow { Id = new IntClassKey(102), Principal = principals[1] }, - new IntClassKeyOptionalDependentShadow { Id = new IntClassKey(103), Principal = principals[2] }, - new IntClassKeyOptionalDependentShadow { Id = new IntClassKey(104), Principal = principals[2] }, - new IntClassKeyOptionalDependentShadow { Id = new IntClassKey(105), Principal = principals[2] }, + new IntClassKeyOptionalDependentShadow { Id = new IntClassKey(101), Principal = principals0[0] }, + new IntClassKeyOptionalDependentShadow { Id = new IntClassKey(102), Principal = principals0[1] }, + new IntClassKeyOptionalDependentShadow { Id = new IntClassKey(103), Principal = principals0[2] }, + new IntClassKeyOptionalDependentShadow { Id = new IntClassKey(104), Principal = principals0[2] }, + new IntClassKeyOptionalDependentShadow { Id = new IntClassKey(105), Principal = principals0[2] }, new IntClassKeyOptionalDependentShadow { Id = new IntClassKey(106) }); - Assert.Equal(10, context.SaveChanges()); + Assert.Equal(10, await context.SaveChangesAsync()); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -3329,12 +3307,12 @@ public virtual void Can_insert_and_read_back_with_class_key_and_optional_depende principals[0].OptionalDependents.Add( new IntClassKeyOptionalDependentShadow { Id = new IntClassKey(dependents[0].Id.Id), }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -3343,23 +3321,20 @@ public virtual void Can_insert_and_read_back_with_class_key_and_optional_depende [(0, 0), (1, null), (2, 2), (3, 0), (4, null), (5, 0)]); } - void RunQueries( - DbContext context, - out IntClassKeyPrincipalShadow[] principals, - out IntClassKeyOptionalDependentShadow[] dependents) + async Task RunQueries(DbContext context) { var two = 2; var three = new IntClassKey(3); principals = [ - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new IntClassKey(1))), - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new IntClassKey(two))), - context.Set().Include(e => e.OptionalDependents).Single(e => e.Id.Equals(three)), - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new IntClassKey(4))) + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new IntClassKey(1))), + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new IntClassKey(two))), + await context.Set().Include(e => e.OptionalDependents).SingleAsync(e => e.Id.Equals(three)), + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new IntClassKey(4))) ]; var oneOhTwo = 102; @@ -3369,20 +3344,20 @@ void RunQueries( dependents = [ - context.Set().Single(e => e.Id.Equals(new IntClassKey(101))), - context.Set().Single(e => e.Id.Equals(new IntClassKey(oneOhTwo))), - context.Set().Single(e => e.Id.Equals(oneOhThree)), - context.Set().Single(e => e.Id == new IntClassKey(104)), - context.Set().Single(e => e.Id == new IntClassKey(oneOhFive)), - context.Set().Single(e => e.Id == oneOhSix) + await context.Set().SingleAsync(e => e.Id.Equals(new IntClassKey(101))), + await context.Set().SingleAsync(e => e.Id.Equals(new IntClassKey(oneOhTwo))), + await context.Set().SingleAsync(e => e.Id.Equals(oneOhThree)), + await context.Set().SingleAsync(e => e.Id == new IntClassKey(104)), + await context.Set().SingleAsync(e => e.Id == new IntClassKey(oneOhFive)), + await context.Set().SingleAsync(e => e.Id == oneOhSix) ]; - Assert.Same(dependents[0], context.Set().Find(new IntClassKey(101))); - Assert.Same(dependents[1], context.Set().Find(new IntClassKey(oneOhTwo))); - Assert.Same(dependents[2], context.Set().Find(oneOhThree)); - Assert.Same(dependents[3], context.Find(new IntClassKey(104))); - Assert.Same(dependents[4], context.Find(new IntClassKey(oneOhFive))); - Assert.Same(dependents[5], context.Find(oneOhSix)); + Assert.Same(dependents[0], await context.Set().FindAsync(new IntClassKey(101))); + Assert.Same(dependents[1], await context.Set().FindAsync(new IntClassKey(oneOhTwo))); + Assert.Same(dependents[2], await context.Set().FindAsync(oneOhThree)); + Assert.Same(dependents[3], await context.FindAsync(new IntClassKey(104))); + Assert.Same(dependents[4], await context.FindAsync(new IntClassKey(oneOhFive))); + Assert.Same(dependents[5], await context.FindAsync(oneOhSix)); } void Validate( @@ -3427,11 +3402,13 @@ void Validate( } [ConditionalFact] - public virtual void Can_insert_and_read_back_with_bare_class_key_and_optional_dependents_with_shadow_FK() + public virtual async Task Can_insert_and_read_back_with_bare_class_key_and_optional_dependents_with_shadow_FK() { + BareIntClassKeyPrincipalShadow[] principals = null; + BareIntClassKeyOptionalDependentShadow[] dependents = null; using (var context = CreateContext()) { - var principals = new BareIntClassKeyPrincipalShadow[] + var principals0 = new BareIntClassKeyPrincipalShadow[] { new() { Id = new BareIntClassKey(1), Foo = "X1" }, new() { Id = new BareIntClassKey(2), Foo = "X2" }, @@ -3439,22 +3416,22 @@ public virtual void Can_insert_and_read_back_with_bare_class_key_and_optional_de new() { Id = new BareIntClassKey(4), Foo = "X4" } }; - context.Set().AddRange(principals); + context.Set().AddRange(principals0); context.Set().AddRange( - new BareIntClassKeyOptionalDependentShadow { Id = new BareIntClassKey(101), Principal = principals[0] }, - new BareIntClassKeyOptionalDependentShadow { Id = new BareIntClassKey(102), Principal = principals[1] }, - new BareIntClassKeyOptionalDependentShadow { Id = new BareIntClassKey(103), Principal = principals[2] }, - new BareIntClassKeyOptionalDependentShadow { Id = new BareIntClassKey(104), Principal = principals[2] }, - new BareIntClassKeyOptionalDependentShadow { Id = new BareIntClassKey(105), Principal = principals[2] }, + new BareIntClassKeyOptionalDependentShadow { Id = new BareIntClassKey(101), Principal = principals0[0] }, + new BareIntClassKeyOptionalDependentShadow { Id = new BareIntClassKey(102), Principal = principals0[1] }, + new BareIntClassKeyOptionalDependentShadow { Id = new BareIntClassKey(103), Principal = principals0[2] }, + new BareIntClassKeyOptionalDependentShadow { Id = new BareIntClassKey(104), Principal = principals0[2] }, + new BareIntClassKeyOptionalDependentShadow { Id = new BareIntClassKey(105), Principal = principals0[2] }, new BareIntClassKeyOptionalDependentShadow { Id = new BareIntClassKey(106) }); - Assert.Equal(10, context.SaveChanges()); + Assert.Equal(10, await context.SaveChangesAsync()); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -3476,12 +3453,12 @@ public virtual void Can_insert_and_read_back_with_bare_class_key_and_optional_de principals[0].OptionalDependents.Add( new BareIntClassKeyOptionalDependentShadow { Id = new BareIntClassKey(dependents[0].Id.Id), }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -3490,23 +3467,20 @@ public virtual void Can_insert_and_read_back_with_bare_class_key_and_optional_de [(0, 0), (1, null), (2, 2), (3, 0), (4, null), (5, 0)]); } - void RunQueries( - DbContext context, - out BareIntClassKeyPrincipalShadow[] principals, - out BareIntClassKeyOptionalDependentShadow[] dependents) + async Task RunQueries(DbContext context) { var two = 2; var three = new BareIntClassKey(3); principals = [ - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new BareIntClassKey(1))), - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new BareIntClassKey(two))), - context.Set().Include(e => e.OptionalDependents).Single(e => e.Id.Equals(three)), - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new BareIntClassKey(4))) + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new BareIntClassKey(1))), + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new BareIntClassKey(two))), + await context.Set().Include(e => e.OptionalDependents).SingleAsync(e => e.Id.Equals(three)), + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new BareIntClassKey(4))) ]; var oneOhTwo = 102; @@ -3516,20 +3490,20 @@ void RunQueries( dependents = [ - context.Set().Single(e => e.Id.Equals(new BareIntClassKey(101))), - context.Set().Single(e => e.Id.Equals(new BareIntClassKey(oneOhTwo))), - context.Set().Single(e => e.Id.Equals(oneOhThree)), - context.Set().Single(e => e.Id == new BareIntClassKey(104)), - context.Set().Single(e => e.Id == new BareIntClassKey(oneOhFive)), - context.Set().Single(e => e.Id == oneOhSix) + await context.Set().SingleAsync(e => e.Id.Equals(new BareIntClassKey(101))), + await context.Set().SingleAsync(e => e.Id.Equals(new BareIntClassKey(oneOhTwo))), + await context.Set().SingleAsync(e => e.Id.Equals(oneOhThree)), + await context.Set().SingleAsync(e => e.Id == new BareIntClassKey(104)), + await context.Set().SingleAsync(e => e.Id == new BareIntClassKey(oneOhFive)), + await context.Set().SingleAsync(e => e.Id == oneOhSix) ]; - Assert.Same(dependents[0], context.Set().Find(new BareIntClassKey(101))); - Assert.Same(dependents[1], context.Set().Find(new BareIntClassKey(oneOhTwo))); - Assert.Same(dependents[2], context.Set().Find(oneOhThree)); - Assert.Same(dependents[3], context.Find(new BareIntClassKey(104))); - Assert.Same(dependents[4], context.Find(new BareIntClassKey(oneOhFive))); - Assert.Same(dependents[5], context.Find(oneOhSix)); + Assert.Same(dependents[0], await context.Set().FindAsync(new BareIntClassKey(101))); + Assert.Same(dependents[1], await context.Set().FindAsync(new BareIntClassKey(oneOhTwo))); + Assert.Same(dependents[2], await context.Set().FindAsync(oneOhThree)); + Assert.Same(dependents[3], await context.FindAsync(new BareIntClassKey(104))); + Assert.Same(dependents[4], await context.FindAsync(new BareIntClassKey(oneOhFive))); + Assert.Same(dependents[5], await context.FindAsync(oneOhSix)); } void Validate( @@ -3574,11 +3548,13 @@ void Validate( } [ConditionalFact] - public virtual void Can_insert_and_read_back_with_comparable_class_key_and_optional_dependents_with_shadow_FK() + public virtual async Task Can_insert_and_read_back_with_comparable_class_key_and_optional_dependents_with_shadow_FK() { + ComparableIntClassKeyPrincipalShadow[] principals = null; + ComparableIntClassKeyOptionalDependentShadow[] dependents = null; using (var context = CreateContext()) { - var principals = new ComparableIntClassKeyPrincipalShadow[] + var principals0 = new ComparableIntClassKeyPrincipalShadow[] { new() { Id = new ComparableIntClassKey(1), Foo = "X1" }, new() { Id = new ComparableIntClassKey(2), Foo = "X2" }, @@ -3586,22 +3562,22 @@ public virtual void Can_insert_and_read_back_with_comparable_class_key_and_optio new() { Id = new ComparableIntClassKey(4), Foo = "X4" } }; - context.Set().AddRange(principals); + context.Set().AddRange(principals0); context.Set().AddRange( - new ComparableIntClassKeyOptionalDependentShadow { Id = new ComparableIntClassKey(101), Principal = principals[0] }, - new ComparableIntClassKeyOptionalDependentShadow { Id = new ComparableIntClassKey(102), Principal = principals[1] }, - new ComparableIntClassKeyOptionalDependentShadow { Id = new ComparableIntClassKey(103), Principal = principals[2] }, - new ComparableIntClassKeyOptionalDependentShadow { Id = new ComparableIntClassKey(104), Principal = principals[2] }, - new ComparableIntClassKeyOptionalDependentShadow { Id = new ComparableIntClassKey(105), Principal = principals[2] }, + new ComparableIntClassKeyOptionalDependentShadow { Id = new ComparableIntClassKey(101), Principal = principals0[0] }, + new ComparableIntClassKeyOptionalDependentShadow { Id = new ComparableIntClassKey(102), Principal = principals0[1] }, + new ComparableIntClassKeyOptionalDependentShadow { Id = new ComparableIntClassKey(103), Principal = principals0[2] }, + new ComparableIntClassKeyOptionalDependentShadow { Id = new ComparableIntClassKey(104), Principal = principals0[2] }, + new ComparableIntClassKeyOptionalDependentShadow { Id = new ComparableIntClassKey(105), Principal = principals0[2] }, new ComparableIntClassKeyOptionalDependentShadow { Id = new ComparableIntClassKey(106) }); - Assert.Equal(10, context.SaveChanges()); + Assert.Equal(10, await context.SaveChangesAsync()); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -3623,12 +3599,12 @@ public virtual void Can_insert_and_read_back_with_comparable_class_key_and_optio principals[0].OptionalDependents.Add( new ComparableIntClassKeyOptionalDependentShadow { Id = new ComparableIntClassKey(dependents[0].Id.Id), }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -3637,23 +3613,20 @@ public virtual void Can_insert_and_read_back_with_comparable_class_key_and_optio [(0, 0), (1, null), (2, 2), (3, 0), (4, null), (5, 0)]); } - void RunQueries( - DbContext context, - out ComparableIntClassKeyPrincipalShadow[] principals, - out ComparableIntClassKeyOptionalDependentShadow[] dependents) + async Task RunQueries(DbContext context) { var two = 2; var three = new ComparableIntClassKey(3); principals = [ - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new ComparableIntClassKey(1))), - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new ComparableIntClassKey(two))), - context.Set().Include(e => e.OptionalDependents).Single(e => e.Id.Equals(three)), - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new ComparableIntClassKey(4))) + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new ComparableIntClassKey(1))), + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new ComparableIntClassKey(two))), + await context.Set().Include(e => e.OptionalDependents).SingleAsync(e => e.Id.Equals(three)), + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new ComparableIntClassKey(4))) ]; var oneOhTwo = 102; @@ -3663,26 +3636,26 @@ void RunQueries( dependents = [ - context.Set() - .Single(e => e.Id.Equals(new ComparableIntClassKey(101))), - context.Set() - .Single(e => e.Id.Equals(new ComparableIntClassKey(oneOhTwo))), - context.Set().Single(e => e.Id.Equals(oneOhThree)), - context.Set().Single(e => e.Id == new ComparableIntClassKey(104)), - context.Set() - .Single(e => e.Id == new ComparableIntClassKey(oneOhFive)), - context.Set().Single(e => e.Id == oneOhSix) + await context.Set() + .SingleAsync(e => e.Id.Equals(new ComparableIntClassKey(101))), + await context.Set() + .SingleAsync(e => e.Id.Equals(new ComparableIntClassKey(oneOhTwo))), + await context.Set().SingleAsync(e => e.Id.Equals(oneOhThree)), + await context.Set().SingleAsync(e => e.Id == new ComparableIntClassKey(104)), + await context.Set() + .SingleAsync(e => e.Id == new ComparableIntClassKey(oneOhFive)), + await context.Set().SingleAsync(e => e.Id == oneOhSix) ]; Assert.Same( - dependents[0], context.Set().Find(new ComparableIntClassKey(101))); + dependents[0], await context.Set().FindAsync(new ComparableIntClassKey(101))); Assert.Same( - dependents[1], context.Set().Find(new ComparableIntClassKey(oneOhTwo))); - Assert.Same(dependents[2], context.Set().Find(oneOhThree)); - Assert.Same(dependents[3], context.Find(new ComparableIntClassKey(104))); + dependents[1], await context.Set().FindAsync(new ComparableIntClassKey(oneOhTwo))); + Assert.Same(dependents[2], await context.Set().FindAsync(oneOhThree)); + Assert.Same(dependents[3], await context.FindAsync(new ComparableIntClassKey(104))); Assert.Same( - dependents[4], context.Find(new ComparableIntClassKey(oneOhFive))); - Assert.Same(dependents[5], context.Find(oneOhSix)); + dependents[4], await context.FindAsync(new ComparableIntClassKey(oneOhFive))); + Assert.Same(dependents[5], await context.FindAsync(oneOhSix)); } void Validate( @@ -3727,11 +3700,13 @@ void Validate( } [ConditionalFact] - public virtual void Can_insert_and_read_back_with_struct_binary_key_and_optional_dependents_with_shadow_FK() + public virtual async Task Can_insert_and_read_back_with_struct_binary_key_and_optional_dependents_with_shadow_FK() { + BytesStructKeyPrincipalShadow[] principals = null; + BytesStructKeyOptionalDependentShadow[] dependents = null; using (var context = CreateContext()) { - var principals = new BytesStructKeyPrincipalShadow[] + var principals0 = new BytesStructKeyPrincipalShadow[] { new() { Id = new BytesStructKey([1]), Foo = "X1" }, new() { Id = new BytesStructKey([2, 2]), Foo = "X2" }, @@ -3739,22 +3714,22 @@ public virtual void Can_insert_and_read_back_with_struct_binary_key_and_optional new() { Id = new BytesStructKey([4, 4, 4, 4]), Foo = "X4" } }; - context.Set().AddRange(principals); + context.Set().AddRange(principals0); context.Set().AddRange( - new BytesStructKeyOptionalDependentShadow { Id = new BytesStructKey([101]), Principal = principals[0] }, - new BytesStructKeyOptionalDependentShadow { Id = new BytesStructKey([102]), Principal = principals[1] }, - new BytesStructKeyOptionalDependentShadow { Id = new BytesStructKey([103]), Principal = principals[2] }, - new BytesStructKeyOptionalDependentShadow { Id = new BytesStructKey([104]), Principal = principals[2] }, - new BytesStructKeyOptionalDependentShadow { Id = new BytesStructKey([105]), Principal = principals[2] }, + new BytesStructKeyOptionalDependentShadow { Id = new BytesStructKey([101]), Principal = principals0[0] }, + new BytesStructKeyOptionalDependentShadow { Id = new BytesStructKey([102]), Principal = principals0[1] }, + new BytesStructKeyOptionalDependentShadow { Id = new BytesStructKey([103]), Principal = principals0[2] }, + new BytesStructKeyOptionalDependentShadow { Id = new BytesStructKey([104]), Principal = principals0[2] }, + new BytesStructKeyOptionalDependentShadow { Id = new BytesStructKey([105]), Principal = principals0[2] }, new BytesStructKeyOptionalDependentShadow { Id = new BytesStructKey([106]) }); - Assert.Equal(10, context.SaveChanges()); + Assert.Equal(10, await context.SaveChangesAsync()); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -3776,12 +3751,12 @@ public virtual void Can_insert_and_read_back_with_struct_binary_key_and_optional principals[0].OptionalDependents.Add( new BytesStructKeyOptionalDependentShadow { Id = new BytesStructKey(dependents[0].Id.Id), }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -3790,23 +3765,20 @@ public virtual void Can_insert_and_read_back_with_struct_binary_key_and_optional [(0, 0), (1, null), (2, 2), (3, 0), (4, null), (5, 0)]); } - void RunQueries( - DbContext context, - out BytesStructKeyPrincipalShadow[] principals, - out BytesStructKeyOptionalDependentShadow[] dependents) + async Task RunQueries(DbContext context) { var two = new byte[] { 2, 2 }; var three = new BytesStructKey { Id = [3, 3, 3] }; principals = [ - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new BytesStructKey { Id = new byte[] { 1 } })), - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new BytesStructKey(two))), - context.Set().Include(e => e.OptionalDependents).Where(e => e.Id.Equals(three)).ToList() + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new BytesStructKey { Id = new byte[] { 1 } })), + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new BytesStructKey(two))), + (await context.Set().Include(e => e.OptionalDependents).Where(e => e.Id.Equals(three)).ToListAsync()) .Single(), - context.Set().Include(e => e.OptionalDependents).Single( + await context.Set().Include(e => e.OptionalDependents).SingleAsync( e => e.Id.Equals(new BytesStructKey { Id = new byte[] { 4, 4, 4, 4 } })) ]; @@ -3817,26 +3789,26 @@ void RunQueries( dependents = [ - context.Set() - .Single(e => e.Id.Equals(new BytesStructKey { Id = new byte[] { 101 } })), - context.Set().Single(e => e.Id.Equals(new BytesStructKey(oneOhTwo))), - context.Set().Single(e => e.Id.Equals(oneOhThree)), - context.Set() - .Single(e => e.Id.Equals(new BytesStructKey { Id = new byte[] { 104 } })), - context.Set().Single(e => e.Id.Equals(new BytesStructKey(oneOhFive))), - context.Set().Single(e => e.Id.Equals(oneOhSix)) + await context.Set() + .SingleAsync(e => e.Id.Equals(new BytesStructKey { Id = new byte[] { 101 } })), + await context.Set().SingleAsync(e => e.Id.Equals(new BytesStructKey(oneOhTwo))), + await context.Set().SingleAsync(e => e.Id.Equals(oneOhThree)), + await context.Set() + .SingleAsync(e => e.Id.Equals(new BytesStructKey { Id = new byte[] { 104 } })), + await context.Set().SingleAsync(e => e.Id.Equals(new BytesStructKey(oneOhFive))), + await context.Set().SingleAsync(e => e.Id.Equals(oneOhSix)) ]; Assert.Same( dependents[0], - context.Set().Find(new BytesStructKey { Id = [101] })); - Assert.Same(dependents[1], context.Set().Find(new BytesStructKey(oneOhTwo))); - Assert.Same(dependents[2], context.Set().Find(oneOhThree)); + await context.Set().FindAsync(new BytesStructKey { Id = [101] })); + Assert.Same(dependents[1], await context.Set().FindAsync(new BytesStructKey(oneOhTwo))); + Assert.Same(dependents[2], await context.Set().FindAsync(oneOhThree)); Assert.Same( dependents[3], - context.Find(typeof(BytesStructKeyOptionalDependentShadow), new BytesStructKey { Id = [104] })); - Assert.Same(dependents[4], context.Find(typeof(BytesStructKeyOptionalDependentShadow), new BytesStructKey(oneOhFive))); - Assert.Same(dependents[5], context.Find(typeof(BytesStructKeyOptionalDependentShadow), oneOhSix)); + await context.FindAsync(typeof(BytesStructKeyOptionalDependentShadow), new BytesStructKey { Id = [104] })); + Assert.Same(dependents[4], await context.FindAsync(typeof(BytesStructKeyOptionalDependentShadow), new BytesStructKey(oneOhFive))); + Assert.Same(dependents[5], await context.FindAsync(typeof(BytesStructKeyOptionalDependentShadow), oneOhSix)); } void Validate( @@ -3883,11 +3855,13 @@ void Validate( } [ConditionalFact] - public virtual void Can_insert_and_read_back_with_structural_struct_binary_key_and_optional_dependents_with_shadow_FK() + public virtual async Task Can_insert_and_read_back_with_structural_struct_binary_key_and_optional_dependents_with_shadow_FK() { + StructuralComparableBytesStructKeyPrincipalShadow[] principals = null; + StructuralComparableBytesStructKeyOptionalDependentShadow[] dependents = null; using (var context = CreateContext()) { - var principals = new StructuralComparableBytesStructKeyPrincipalShadow[] + var principals0 = new StructuralComparableBytesStructKeyPrincipalShadow[] { new() { Id = new StructuralComparableBytesStructKey([1]), Foo = "X1" }, new() { Id = new StructuralComparableBytesStructKey([2, 2]), Foo = "X2" }, @@ -3895,40 +3869,40 @@ public virtual void Can_insert_and_read_back_with_structural_struct_binary_key_a new() { Id = new StructuralComparableBytesStructKey([4, 4, 4, 4]), Foo = "X4" } }; - context.Set().AddRange(principals); + context.Set().AddRange(principals0); context.Set().AddRange( new StructuralComparableBytesStructKeyOptionalDependentShadow { - Id = new StructuralComparableBytesStructKey([101]), Principal = principals[0] + Id = new StructuralComparableBytesStructKey([101]), Principal = principals0[0] }, new StructuralComparableBytesStructKeyOptionalDependentShadow { - Id = new StructuralComparableBytesStructKey([102]), Principal = principals[1] + Id = new StructuralComparableBytesStructKey([102]), Principal = principals0[1] }, new StructuralComparableBytesStructKeyOptionalDependentShadow { - Id = new StructuralComparableBytesStructKey([103]), Principal = principals[2] + Id = new StructuralComparableBytesStructKey([103]), Principal = principals0[2] }, new StructuralComparableBytesStructKeyOptionalDependentShadow { - Id = new StructuralComparableBytesStructKey([104]), Principal = principals[2] + Id = new StructuralComparableBytesStructKey([104]), Principal = principals0[2] }, new StructuralComparableBytesStructKeyOptionalDependentShadow { - Id = new StructuralComparableBytesStructKey([105]), Principal = principals[2] + Id = new StructuralComparableBytesStructKey([105]), Principal = principals0[2] }, new StructuralComparableBytesStructKeyOptionalDependentShadow { Id = new StructuralComparableBytesStructKey([106]) }); - Assert.Equal(10, context.SaveChanges()); + Assert.Equal(10, await context.SaveChangesAsync()); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -3953,12 +3927,12 @@ public virtual void Can_insert_and_read_back_with_structural_struct_binary_key_a Id = new StructuralComparableBytesStructKey(dependents[0].Id.Id), }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -3967,24 +3941,21 @@ public virtual void Can_insert_and_read_back_with_structural_struct_binary_key_a [(0, 0), (1, null), (2, 2), (3, 0), (4, null), (5, 0)]); } - void RunQueries( - DbContext context, - out StructuralComparableBytesStructKeyPrincipalShadow[] principals, - out StructuralComparableBytesStructKeyOptionalDependentShadow[] dependents) + async Task RunQueries(DbContext context) { var two = new byte[] { 2, 2 }; var three = new StructuralComparableBytesStructKey { Id = [3, 3, 3] }; principals = [ - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new StructuralComparableBytesStructKey { Id = new byte[] { 1 } })), - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new StructuralComparableBytesStructKey(two))), - context.Set().Include(e => e.OptionalDependents) - .Where(e => e.Id.Equals(three)).ToList() + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new StructuralComparableBytesStructKey { Id = new byte[] { 1 } })), + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new StructuralComparableBytesStructKey(two))), + (await context.Set().Include(e => e.OptionalDependents) + .Where(e => e.Id.Equals(three)).ToListAsync()) .Single(), - context.Set().Include(e => e.OptionalDependents).Single( + await context.Set().Include(e => e.OptionalDependents).SingleAsync( e => e.Id.Equals(new StructuralComparableBytesStructKey { Id = new byte[] { 4, 4, 4, 4 } })) ]; @@ -3995,38 +3966,38 @@ void RunQueries( dependents = [ - context.Set() - .Single(e => e.Id.Equals(new StructuralComparableBytesStructKey { Id = new byte[] { 101 } })), - context.Set() - .Single(e => e.Id.Equals(new StructuralComparableBytesStructKey(oneOhTwo))), - context.Set().Single(e => e.Id.Equals(oneOhThree)), - context.Set() - .Single(e => e.Id.Equals(new StructuralComparableBytesStructKey { Id = new byte[] { 104 } })), - context.Set() - .Single(e => e.Id.Equals(new StructuralComparableBytesStructKey(oneOhFive))), - context.Set().Single(e => e.Id.Equals(oneOhSix)) + await context.Set() + .SingleAsync(e => e.Id.Equals(new StructuralComparableBytesStructKey { Id = new byte[] { 101 } })), + await context.Set() + .SingleAsync(e => e.Id.Equals(new StructuralComparableBytesStructKey(oneOhTwo))), + await context.Set().SingleAsync(e => e.Id.Equals(oneOhThree)), + await context.Set() + .SingleAsync(e => e.Id.Equals(new StructuralComparableBytesStructKey { Id = new byte[] { 104 } })), + await context.Set() + .SingleAsync(e => e.Id.Equals(new StructuralComparableBytesStructKey(oneOhFive))), + await context.Set().SingleAsync(e => e.Id.Equals(oneOhSix)) ]; Assert.Same( dependents[0], - context.Set() - .Find(new StructuralComparableBytesStructKey { Id = [101] })); + await context.Set() + .FindAsync(new StructuralComparableBytesStructKey { Id = [101] })); Assert.Same( dependents[1], - context.Set() - .Find(new StructuralComparableBytesStructKey(oneOhTwo))); - Assert.Same(dependents[2], context.Set().Find(oneOhThree)); + await context.Set() + .FindAsync(new StructuralComparableBytesStructKey(oneOhTwo))); + Assert.Same(dependents[2], await context.Set().FindAsync(oneOhThree)); Assert.Same( dependents[3], - context.Find( + await context.FindAsync( typeof(StructuralComparableBytesStructKeyOptionalDependentShadow), new StructuralComparableBytesStructKey { Id = [104] })); Assert.Same( dependents[4], - context.Find( + await context.FindAsync( typeof(StructuralComparableBytesStructKeyOptionalDependentShadow), new StructuralComparableBytesStructKey(oneOhFive))); - Assert.Same(dependents[5], context.Find(typeof(StructuralComparableBytesStructKeyOptionalDependentShadow), oneOhSix)); + Assert.Same(dependents[5], await context.FindAsync(typeof(StructuralComparableBytesStructKeyOptionalDependentShadow), oneOhSix)); } void Validate( @@ -4073,11 +4044,13 @@ void Validate( } [ConditionalFact] - public virtual void Can_insert_and_read_back_with_comparable_struct_binary_key_and_optional_dependents_with_shadow_FK() + public virtual async Task Can_insert_and_read_back_with_comparable_struct_binary_key_and_optional_dependents_with_shadow_FK() { + ComparableBytesStructKeyPrincipalShadow[] principals = null; + ComparableBytesStructKeyOptionalDependentShadow[] dependents = null; using (var context = CreateContext()) { - var principals = new ComparableBytesStructKeyPrincipalShadow[] + var principals0 = new ComparableBytesStructKeyPrincipalShadow[] { new() { Id = new ComparableBytesStructKey([1]), Foo = "X1" }, new() { Id = new ComparableBytesStructKey([2, 2]), Foo = "X2" }, @@ -4085,37 +4058,37 @@ public virtual void Can_insert_and_read_back_with_comparable_struct_binary_key_a new() { Id = new ComparableBytesStructKey([4, 4, 4, 4]), Foo = "X4" } }; - context.Set().AddRange(principals); + context.Set().AddRange(principals0); context.Set().AddRange( new ComparableBytesStructKeyOptionalDependentShadow { - Id = new ComparableBytesStructKey([101]), Principal = principals[0] + Id = new ComparableBytesStructKey([101]), Principal = principals0[0] }, new ComparableBytesStructKeyOptionalDependentShadow { - Id = new ComparableBytesStructKey([102]), Principal = principals[1] + Id = new ComparableBytesStructKey([102]), Principal = principals0[1] }, new ComparableBytesStructKeyOptionalDependentShadow { - Id = new ComparableBytesStructKey([103]), Principal = principals[2] + Id = new ComparableBytesStructKey([103]), Principal = principals0[2] }, new ComparableBytesStructKeyOptionalDependentShadow { - Id = new ComparableBytesStructKey([104]), Principal = principals[2] + Id = new ComparableBytesStructKey([104]), Principal = principals0[2] }, new ComparableBytesStructKeyOptionalDependentShadow { - Id = new ComparableBytesStructKey([105]), Principal = principals[2] + Id = new ComparableBytesStructKey([105]), Principal = principals0[2] }, new ComparableBytesStructKeyOptionalDependentShadow { Id = new ComparableBytesStructKey([106]) }); - Assert.Equal(10, context.SaveChanges()); + Assert.Equal(10, await context.SaveChangesAsync()); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -4137,12 +4110,12 @@ public virtual void Can_insert_and_read_back_with_comparable_struct_binary_key_a principals[0].OptionalDependents.Add( new ComparableBytesStructKeyOptionalDependentShadow { Id = new ComparableBytesStructKey(dependents[0].Id.Id), }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -4151,24 +4124,21 @@ public virtual void Can_insert_and_read_back_with_comparable_struct_binary_key_a [(0, 0), (1, null), (2, 2), (3, 0), (4, null), (5, 0)]); } - void RunQueries( - DbContext context, - out ComparableBytesStructKeyPrincipalShadow[] principals, - out ComparableBytesStructKeyOptionalDependentShadow[] dependents) + async Task RunQueries(DbContext context) { var two = new byte[] { 2, 2 }; var three = new ComparableBytesStructKey { Id = [3, 3, 3] }; principals = [ - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new ComparableBytesStructKey { Id = new byte[] { 1 } })), - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new ComparableBytesStructKey(two))), - context.Set().Include(e => e.OptionalDependents).Where(e => e.Id.Equals(three)) - .ToList() + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new ComparableBytesStructKey { Id = new byte[] { 1 } })), + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new ComparableBytesStructKey(two))), + (await context.Set().Include(e => e.OptionalDependents).Where(e => e.Id.Equals(three)) + .ToListAsync()) .Single(), - context.Set().Include(e => e.OptionalDependents).Single( + await context.Set().Include(e => e.OptionalDependents).SingleAsync( e => e.Id.Equals(new ComparableBytesStructKey { Id = new byte[] { 4, 4, 4, 4 } })) ]; @@ -4179,34 +4149,34 @@ void RunQueries( dependents = [ - context.Set() - .Single(e => e.Id.Equals(new ComparableBytesStructKey { Id = new byte[] { 101 } })), - context.Set() - .Single(e => e.Id.Equals(new ComparableBytesStructKey(oneOhTwo))), - context.Set().Single(e => e.Id.Equals(oneOhThree)), - context.Set() - .Single(e => e.Id.Equals(new ComparableBytesStructKey { Id = new byte[] { 104 } })), - context.Set() - .Single(e => e.Id.Equals(new ComparableBytesStructKey(oneOhFive))), - context.Set().Single(e => e.Id.Equals(oneOhSix)) + await context.Set() + .SingleAsync(e => e.Id.Equals(new ComparableBytesStructKey { Id = new byte[] { 101 } })), + await context.Set() + .SingleAsync(e => e.Id.Equals(new ComparableBytesStructKey(oneOhTwo))), + await context.Set().SingleAsync(e => e.Id.Equals(oneOhThree)), + await context.Set() + .SingleAsync(e => e.Id.Equals(new ComparableBytesStructKey { Id = new byte[] { 104 } })), + await context.Set() + .SingleAsync(e => e.Id.Equals(new ComparableBytesStructKey(oneOhFive))), + await context.Set().SingleAsync(e => e.Id.Equals(oneOhSix)) ]; Assert.Same( dependents[0], - context.Set() - .Find(new ComparableBytesStructKey { Id = [101] })); + await context.Set() + .FindAsync(new ComparableBytesStructKey { Id = [101] })); Assert.Same( dependents[1], - context.Set().Find(new ComparableBytesStructKey(oneOhTwo))); - Assert.Same(dependents[2], context.Set().Find(oneOhThree)); + await context.Set().FindAsync(new ComparableBytesStructKey(oneOhTwo))); + Assert.Same(dependents[2], await context.Set().FindAsync(oneOhThree)); Assert.Same( dependents[3], - context.Find( + await context.FindAsync( typeof(ComparableBytesStructKeyOptionalDependentShadow), new ComparableBytesStructKey { Id = [104] })); Assert.Same( dependents[4], - context.Find(typeof(ComparableBytesStructKeyOptionalDependentShadow), new ComparableBytesStructKey(oneOhFive))); - Assert.Same(dependents[5], context.Find(typeof(ComparableBytesStructKeyOptionalDependentShadow), oneOhSix)); + await context.FindAsync(typeof(ComparableBytesStructKeyOptionalDependentShadow), new ComparableBytesStructKey(oneOhFive))); + Assert.Same(dependents[5], await context.FindAsync(typeof(ComparableBytesStructKeyOptionalDependentShadow), oneOhSix)); } void Validate( @@ -4253,11 +4223,13 @@ void Validate( } [ConditionalFact] - public virtual void Can_insert_and_read_back_with_generic_comparable_struct_binary_key_and_optional_dependents_with_shadow_FK() + public virtual async Task Can_insert_and_read_back_with_generic_comparable_struct_binary_key_and_optional_dependents_with_shadow_FK() { + GenericComparableBytesStructKeyPrincipalShadow[] principals = null; + GenericComparableBytesStructKeyOptionalDependentShadow[] dependents = null; using (var context = CreateContext()) { - var principals = new GenericComparableBytesStructKeyPrincipalShadow[] + var principals0 = new GenericComparableBytesStructKeyPrincipalShadow[] { new() { Id = new GenericComparableBytesStructKey([1]), Foo = "X1" }, new() { Id = new GenericComparableBytesStructKey([2, 2]), Foo = "X2" }, @@ -4265,40 +4237,40 @@ public virtual void Can_insert_and_read_back_with_generic_comparable_struct_bina new() { Id = new GenericComparableBytesStructKey([4, 4, 4, 4]), Foo = "X4" } }; - context.Set().AddRange(principals); + context.Set().AddRange(principals0); context.Set().AddRange( new GenericComparableBytesStructKeyOptionalDependentShadow { - Id = new GenericComparableBytesStructKey([101]), Principal = principals[0] + Id = new GenericComparableBytesStructKey([101]), Principal = principals0[0] }, new GenericComparableBytesStructKeyOptionalDependentShadow { - Id = new GenericComparableBytesStructKey([102]), Principal = principals[1] + Id = new GenericComparableBytesStructKey([102]), Principal = principals0[1] }, new GenericComparableBytesStructKeyOptionalDependentShadow { - Id = new GenericComparableBytesStructKey([103]), Principal = principals[2] + Id = new GenericComparableBytesStructKey([103]), Principal = principals0[2] }, new GenericComparableBytesStructKeyOptionalDependentShadow { - Id = new GenericComparableBytesStructKey([104]), Principal = principals[2] + Id = new GenericComparableBytesStructKey([104]), Principal = principals0[2] }, new GenericComparableBytesStructKeyOptionalDependentShadow { - Id = new GenericComparableBytesStructKey([105]), Principal = principals[2] + Id = new GenericComparableBytesStructKey([105]), Principal = principals0[2] }, new GenericComparableBytesStructKeyOptionalDependentShadow { Id = new GenericComparableBytesStructKey([106]) }); - Assert.Equal(10, context.SaveChanges()); + Assert.Equal(10, await context.SaveChangesAsync()); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -4323,12 +4295,12 @@ public virtual void Can_insert_and_read_back_with_generic_comparable_struct_bina Id = new GenericComparableBytesStructKey(dependents[0].Id.Id), }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -4337,24 +4309,21 @@ public virtual void Can_insert_and_read_back_with_generic_comparable_struct_bina [(0, 0), (1, null), (2, 2), (3, 0), (4, null), (5, 0)]); } - void RunQueries( - DbContext context, - out GenericComparableBytesStructKeyPrincipalShadow[] principals, - out GenericComparableBytesStructKeyOptionalDependentShadow[] dependents) + async Task RunQueries(DbContext context) { var two = new byte[] { 2, 2 }; var three = new GenericComparableBytesStructKey { Id = [3, 3, 3] }; principals = [ - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new GenericComparableBytesStructKey { Id = new byte[] { 1 } })), - context.Set().Include(e => e.OptionalDependents) - .Single(e => e.Id.Equals(new GenericComparableBytesStructKey(two))), - context.Set().Include(e => e.OptionalDependents) - .Where(e => e.Id.Equals(three)).ToList() + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new GenericComparableBytesStructKey { Id = new byte[] { 1 } })), + await context.Set().Include(e => e.OptionalDependents) + .SingleAsync(e => e.Id.Equals(new GenericComparableBytesStructKey(two))), + (await context.Set().Include(e => e.OptionalDependents) + .Where(e => e.Id.Equals(three)).ToListAsync()) .Single(), - context.Set().Include(e => e.OptionalDependents).Single( + await context.Set().Include(e => e.OptionalDependents).SingleAsync( e => e.Id.Equals(new GenericComparableBytesStructKey { Id = new byte[] { 4, 4, 4, 4 } })) ]; @@ -4365,37 +4334,37 @@ void RunQueries( dependents = [ - context.Set() - .Single(e => e.Id.Equals(new GenericComparableBytesStructKey { Id = new byte[] { 101 } })), - context.Set() - .Single(e => e.Id.Equals(new GenericComparableBytesStructKey(oneOhTwo))), - context.Set().Single(e => e.Id.Equals(oneOhThree)), - context.Set() - .Single(e => e.Id.Equals(new GenericComparableBytesStructKey { Id = new byte[] { 104 } })), - context.Set() - .Single(e => e.Id.Equals(new GenericComparableBytesStructKey(oneOhFive))), - context.Set().Single(e => e.Id.Equals(oneOhSix)) + await context.Set() + .SingleAsync(e => e.Id.Equals(new GenericComparableBytesStructKey { Id = new byte[] { 101 } })), + await context.Set() + .SingleAsync(e => e.Id.Equals(new GenericComparableBytesStructKey(oneOhTwo))), + await context.Set().SingleAsync(e => e.Id.Equals(oneOhThree)), + await context.Set() + .SingleAsync(e => e.Id.Equals(new GenericComparableBytesStructKey { Id = new byte[] { 104 } })), + await context.Set() + .SingleAsync(e => e.Id.Equals(new GenericComparableBytesStructKey(oneOhFive))), + await context.Set().SingleAsync(e => e.Id.Equals(oneOhSix)) ]; Assert.Same( dependents[0], - context.Set() - .Find(new GenericComparableBytesStructKey { Id = [101] })); + await context.Set() + .FindAsync(new GenericComparableBytesStructKey { Id = [101] })); Assert.Same( dependents[1], - context.Set() - .Find(new GenericComparableBytesStructKey(oneOhTwo))); - Assert.Same(dependents[2], context.Set().Find(oneOhThree)); + await context.Set() + .FindAsync(new GenericComparableBytesStructKey(oneOhTwo))); + Assert.Same(dependents[2], await context.Set().FindAsync(oneOhThree)); Assert.Same( dependents[3], - context.Find( + await context.FindAsync( typeof(GenericComparableBytesStructKeyOptionalDependentShadow), new GenericComparableBytesStructKey { Id = [104] })); Assert.Same( dependents[4], - context.Find( + await context.FindAsync( typeof(GenericComparableBytesStructKeyOptionalDependentShadow), new GenericComparableBytesStructKey(oneOhFive))); - Assert.Same(dependents[5], context.Find(typeof(GenericComparableBytesStructKeyOptionalDependentShadow), oneOhSix)); + Assert.Same(dependents[5], await context.FindAsync(typeof(GenericComparableBytesStructKeyOptionalDependentShadow), oneOhSix)); } void Validate( @@ -4442,11 +4411,13 @@ void Validate( } [ConditionalFact] - public virtual void Can_insert_and_read_back_with_struct_binary_key_and_required_dependents_with_shadow_FK() + public virtual async Task Can_insert_and_read_back_with_struct_binary_key_and_required_dependents_with_shadow_FK() { + BytesStructKeyPrincipalShadow[] principals = null; + BytesStructKeyRequiredDependentShadow[] dependents = null; using (var context = CreateContext()) { - var principals = new BytesStructKeyPrincipalShadow[] + var principals0 = new BytesStructKeyPrincipalShadow[] { new() { Id = new BytesStructKey([11]), Foo = "X1" }, new() { Id = new BytesStructKey([12, 12]), Foo = "X2" }, @@ -4454,22 +4425,22 @@ public virtual void Can_insert_and_read_back_with_struct_binary_key_and_required new() { Id = new BytesStructKey([14, 14, 14, 14]), Foo = "X4" } }; - context.Set().AddRange(principals); + context.Set().AddRange(principals0); context.Set().AddRange( - new BytesStructKeyRequiredDependentShadow { Id = new BytesStructKey([111]), Principal = principals[0] }, - new BytesStructKeyRequiredDependentShadow { Id = new BytesStructKey([112]), Principal = principals[1] }, - new BytesStructKeyRequiredDependentShadow { Id = new BytesStructKey([113]), Principal = principals[2] }, - new BytesStructKeyRequiredDependentShadow { Id = new BytesStructKey([114]), Principal = principals[2] }, - new BytesStructKeyRequiredDependentShadow { Id = new BytesStructKey([115]), Principal = principals[2] }, - new BytesStructKeyRequiredDependentShadow { Id = new BytesStructKey([116]), Principal = principals[2] }); + new BytesStructKeyRequiredDependentShadow { Id = new BytesStructKey([111]), Principal = principals0[0] }, + new BytesStructKeyRequiredDependentShadow { Id = new BytesStructKey([112]), Principal = principals0[1] }, + new BytesStructKeyRequiredDependentShadow { Id = new BytesStructKey([113]), Principal = principals0[2] }, + new BytesStructKeyRequiredDependentShadow { Id = new BytesStructKey([114]), Principal = principals0[2] }, + new BytesStructKeyRequiredDependentShadow { Id = new BytesStructKey([115]), Principal = principals0[2] }, + new BytesStructKeyRequiredDependentShadow { Id = new BytesStructKey([116]), Principal = principals0[2] }); - Assert.Equal(10, context.SaveChanges()); + Assert.Equal(10, await context.SaveChangesAsync()); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -4491,12 +4462,12 @@ public virtual void Can_insert_and_read_back_with_struct_binary_key_and_required principals[0].RequiredDependents.Add( new BytesStructKeyRequiredDependentShadow { Id = new BytesStructKey(dependents[0].Id.Id), }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -4505,22 +4476,19 @@ public virtual void Can_insert_and_read_back_with_struct_binary_key_and_required [(0, 0), (2, 2), (3, 0), (5, 0)]); } - void RunQueries( - DbContext context, - out BytesStructKeyPrincipalShadow[] principals, - out BytesStructKeyRequiredDependentShadow[] dependents) + async Task RunQueries(DbContext context) { var twelve = new byte[] { 12, 12 }; var thirteen = new BytesStructKey { Id = [13, 13, 13] }; principals = [ - context.Set().Include(e => e.RequiredDependents) - .Single(e => e.Id.Equals(new BytesStructKey { Id = new byte[] { 11 } })), - context.Set().Include(e => e.RequiredDependents) - .Single(e => e.Id.Equals(new BytesStructKey { Id = twelve })), - context.Set().Include(e => e.RequiredDependents).Single(e => e.Id.Equals(thirteen)), - context.Set().Include(e => e.RequiredDependents).Single( + await context.Set().Include(e => e.RequiredDependents) + .SingleAsync(e => e.Id.Equals(new BytesStructKey { Id = new byte[] { 11 } })), + await context.Set().Include(e => e.RequiredDependents) + .SingleAsync(e => e.Id.Equals(new BytesStructKey { Id = twelve })), + await context.Set().Include(e => e.RequiredDependents).SingleAsync(e => e.Id.Equals(thirteen)), + await context.Set().Include(e => e.RequiredDependents).SingleAsync( e => e.Id.Equals(new BytesStructKey { Id = new byte[] { 14, 14, 14, 14 } })) ]; @@ -4531,30 +4499,30 @@ void RunQueries( dependents = [ - context.Set() - .FirstOrDefault(e => e.Id.Equals(new BytesStructKey { Id = new byte[] { 111 } })), - context.Set() - .FirstOrDefault(e => e.Id.Equals(new BytesStructKey { Id = oneTwelve })), - context.Set().FirstOrDefault(e => e.Id.Equals(oneThirteen)), - context.Set() - .FirstOrDefault(e => e.Id.Equals(new BytesStructKey { Id = new byte[] { 114 } })), - context.Set() - .FirstOrDefault(e => e.Id.Equals(new BytesStructKey { Id = oneFifteeen })), - context.Set().FirstOrDefault(e => e.Id.Equals(oneSixteen)) + await context.Set() + .FirstOrDefaultAsync(e => e.Id.Equals(new BytesStructKey { Id = new byte[] { 111 } })), + await context.Set() + .FirstOrDefaultAsync(e => e.Id.Equals(new BytesStructKey { Id = oneTwelve })), + await context.Set().FirstOrDefaultAsync(e => e.Id.Equals(oneThirteen)), + await context.Set() + .FirstOrDefaultAsync(e => e.Id.Equals(new BytesStructKey { Id = new byte[] { 114 } })), + await context.Set() + .FirstOrDefaultAsync(e => e.Id.Equals(new BytesStructKey { Id = oneFifteeen })), + await context.Set().FirstOrDefaultAsync(e => e.Id.Equals(oneSixteen)) ]; Assert.Same( dependents[0], - context.Set().Find(new BytesStructKey { Id = [111] })); + await context.Set().FindAsync(new BytesStructKey { Id = [111] })); Assert.Same( - dependents[1], context.Set().Find(new BytesStructKey { Id = oneTwelve })); - Assert.Same(dependents[2], context.Set().Find(oneThirteen)); + dependents[1], await context.Set().FindAsync(new BytesStructKey { Id = oneTwelve })); + Assert.Same(dependents[2], await context.Set().FindAsync(oneThirteen)); Assert.Same( dependents[3], - context.Find(typeof(BytesStructKeyRequiredDependentShadow), new BytesStructKey { Id = [114] })); + await context.FindAsync(typeof(BytesStructKeyRequiredDependentShadow), new BytesStructKey { Id = [114] })); Assert.Same( - dependents[4], context.Find(typeof(BytesStructKeyRequiredDependentShadow), new BytesStructKey { Id = oneFifteeen })); - Assert.Same(dependents[5], context.Find(typeof(BytesStructKeyRequiredDependentShadow), oneSixteen)); + dependents[4], await context.FindAsync(typeof(BytesStructKeyRequiredDependentShadow), new BytesStructKey { Id = oneFifteeen })); + Assert.Same(dependents[5], await context.FindAsync(typeof(BytesStructKeyRequiredDependentShadow), oneSixteen)); } void Validate( @@ -4602,11 +4570,13 @@ void Validate( } [ConditionalFact] - public virtual void Can_insert_and_read_back_with_comparable_struct_binary_key_and_required_dependents_with_shadow_FK() + public virtual async Task Can_insert_and_read_back_with_comparable_struct_binary_key_and_required_dependents_with_shadow_FK() { + ComparableBytesStructKeyPrincipalShadow[] principals = null; + ComparableBytesStructKeyRequiredDependentShadow[] dependents = null; using (var context = CreateContext()) { - var principals = new ComparableBytesStructKeyPrincipalShadow[] + var principals0 = new ComparableBytesStructKeyPrincipalShadow[] { new() { Id = new ComparableBytesStructKey([11]), Foo = "X1" }, new() { Id = new ComparableBytesStructKey([12, 12]), Foo = "X2" }, @@ -4614,40 +4584,40 @@ public virtual void Can_insert_and_read_back_with_comparable_struct_binary_key_a new() { Id = new ComparableBytesStructKey([14, 14, 14, 14]), Foo = "X4" } }; - context.Set().AddRange(principals); + context.Set().AddRange(principals0); context.Set().AddRange( new ComparableBytesStructKeyRequiredDependentShadow { - Id = new ComparableBytesStructKey([111]), Principal = principals[0] + Id = new ComparableBytesStructKey([111]), Principal = principals0[0] }, new ComparableBytesStructKeyRequiredDependentShadow { - Id = new ComparableBytesStructKey([112]), Principal = principals[1] + Id = new ComparableBytesStructKey([112]), Principal = principals0[1] }, new ComparableBytesStructKeyRequiredDependentShadow { - Id = new ComparableBytesStructKey([113]), Principal = principals[2] + Id = new ComparableBytesStructKey([113]), Principal = principals0[2] }, new ComparableBytesStructKeyRequiredDependentShadow { - Id = new ComparableBytesStructKey([114]), Principal = principals[2] + Id = new ComparableBytesStructKey([114]), Principal = principals0[2] }, new ComparableBytesStructKeyRequiredDependentShadow { - Id = new ComparableBytesStructKey([115]), Principal = principals[2] + Id = new ComparableBytesStructKey([115]), Principal = principals0[2] }, new ComparableBytesStructKeyRequiredDependentShadow { - Id = new ComparableBytesStructKey([116]), Principal = principals[2] + Id = new ComparableBytesStructKey([116]), Principal = principals0[2] }); - Assert.Equal(10, context.SaveChanges()); + Assert.Equal(10, await context.SaveChangesAsync()); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -4669,12 +4639,12 @@ public virtual void Can_insert_and_read_back_with_comparable_struct_binary_key_a principals[0].RequiredDependents.Add( new ComparableBytesStructKeyRequiredDependentShadow { Id = new ComparableBytesStructKey(dependents[0].Id.Id), }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -4683,23 +4653,20 @@ public virtual void Can_insert_and_read_back_with_comparable_struct_binary_key_a [(0, 0), (2, 2), (3, 0), (5, 0)]); } - void RunQueries( - DbContext context, - out ComparableBytesStructKeyPrincipalShadow[] principals, - out ComparableBytesStructKeyRequiredDependentShadow[] dependents) + async Task RunQueries(DbContext context) { var twelve = new byte[] { 12, 12 }; var thirteen = new ComparableBytesStructKey { Id = [13, 13, 13] }; principals = [ - context.Set().Include(e => e.RequiredDependents) - .Single(e => e.Id.Equals(new ComparableBytesStructKey { Id = new byte[] { 11 } })), - context.Set().Include(e => e.RequiredDependents) - .Single(e => e.Id.Equals(new ComparableBytesStructKey { Id = twelve })), - context.Set().Include(e => e.RequiredDependents) - .Single(e => e.Id.Equals(thirteen)), - context.Set().Include(e => e.RequiredDependents).Single( + await context.Set().Include(e => e.RequiredDependents) + .SingleAsync(e => e.Id.Equals(new ComparableBytesStructKey { Id = new byte[] { 11 } })), + await context.Set().Include(e => e.RequiredDependents) + .SingleAsync(e => e.Id.Equals(new ComparableBytesStructKey { Id = twelve })), + await context.Set().Include(e => e.RequiredDependents) + .SingleAsync(e => e.Id.Equals(thirteen)), + await context.Set().Include(e => e.RequiredDependents).SingleAsync( e => e.Id.Equals(new ComparableBytesStructKey { Id = new byte[] { 14, 14, 14, 14 } })) ]; @@ -4710,35 +4677,35 @@ void RunQueries( dependents = [ - context.Set() - .FirstOrDefault(e => e.Id.Equals(new ComparableBytesStructKey { Id = new byte[] { 111 } })), - context.Set() - .FirstOrDefault(e => e.Id.Equals(new ComparableBytesStructKey { Id = oneTwelve })), - context.Set().FirstOrDefault(e => e.Id.Equals(oneThirteen)), - context.Set() - .FirstOrDefault(e => e.Id.Equals(new ComparableBytesStructKey { Id = new byte[] { 114 } })), - context.Set() - .FirstOrDefault(e => e.Id.Equals(new ComparableBytesStructKey { Id = oneFifteeen })), - context.Set().FirstOrDefault(e => e.Id.Equals(oneSixteen)) + await context.Set() + .FirstOrDefaultAsync(e => e.Id.Equals(new ComparableBytesStructKey { Id = new byte[] { 111 } })), + await context.Set() + .FirstOrDefaultAsync(e => e.Id.Equals(new ComparableBytesStructKey { Id = oneTwelve })), + await context.Set().FirstOrDefaultAsync(e => e.Id.Equals(oneThirteen)), + await context.Set() + .FirstOrDefaultAsync(e => e.Id.Equals(new ComparableBytesStructKey { Id = new byte[] { 114 } })), + await context.Set() + .FirstOrDefaultAsync(e => e.Id.Equals(new ComparableBytesStructKey { Id = oneFifteeen })), + await context.Set().FirstOrDefaultAsync(e => e.Id.Equals(oneSixteen)) ]; Assert.Same( dependents[0], - context.Set() - .Find(new ComparableBytesStructKey { Id = [111] })); + await context.Set() + .FindAsync(new ComparableBytesStructKey { Id = [111] })); Assert.Same( dependents[1], - context.Set().Find(new ComparableBytesStructKey { Id = oneTwelve })); - Assert.Same(dependents[2], context.Set().Find(oneThirteen)); + await context.Set().FindAsync(new ComparableBytesStructKey { Id = oneTwelve })); + Assert.Same(dependents[2], await context.Set().FindAsync(oneThirteen)); Assert.Same( dependents[3], - context.Find( + await context.FindAsync( typeof(ComparableBytesStructKeyRequiredDependentShadow), new ComparableBytesStructKey { Id = [114] })); Assert.Same( dependents[4], - context.Find( + await context.FindAsync( typeof(ComparableBytesStructKeyRequiredDependentShadow), new ComparableBytesStructKey { Id = oneFifteeen })); - Assert.Same(dependents[5], context.Find(typeof(ComparableBytesStructKeyRequiredDependentShadow), oneSixteen)); + Assert.Same(dependents[5], await context.FindAsync(typeof(ComparableBytesStructKeyRequiredDependentShadow), oneSixteen)); } void Validate( @@ -4786,11 +4753,13 @@ void Validate( } [ConditionalFact] - public virtual void Can_insert_and_read_back_with_structural_struct_binary_key_and_required_dependents_with_shadow_FK() + public virtual async Task Can_insert_and_read_back_with_structural_struct_binary_key_and_required_dependents_with_shadow_FK() { + StructuralComparableBytesStructKeyPrincipalShadow[] principals = null; + StructuralComparableBytesStructKeyRequiredDependentShadow[] dependents = null; using (var context = CreateContext()) { - var principals = new StructuralComparableBytesStructKeyPrincipalShadow[] + var principals0 = new StructuralComparableBytesStructKeyPrincipalShadow[] { new() { Id = new StructuralComparableBytesStructKey([11]), Foo = "X1" }, new() { Id = new StructuralComparableBytesStructKey([12, 12]), Foo = "X2" }, @@ -4798,40 +4767,40 @@ public virtual void Can_insert_and_read_back_with_structural_struct_binary_key_a new() { Id = new StructuralComparableBytesStructKey([14, 14, 14, 14]), Foo = "X4" } }; - context.Set().AddRange(principals); + context.Set().AddRange(principals0); context.Set().AddRange( new StructuralComparableBytesStructKeyRequiredDependentShadow { - Id = new StructuralComparableBytesStructKey([111]), Principal = principals[0] + Id = new StructuralComparableBytesStructKey([111]), Principal = principals0[0] }, new StructuralComparableBytesStructKeyRequiredDependentShadow { - Id = new StructuralComparableBytesStructKey([112]), Principal = principals[1] + Id = new StructuralComparableBytesStructKey([112]), Principal = principals0[1] }, new StructuralComparableBytesStructKeyRequiredDependentShadow { - Id = new StructuralComparableBytesStructKey([113]), Principal = principals[2] + Id = new StructuralComparableBytesStructKey([113]), Principal = principals0[2] }, new StructuralComparableBytesStructKeyRequiredDependentShadow { - Id = new StructuralComparableBytesStructKey([114]), Principal = principals[2] + Id = new StructuralComparableBytesStructKey([114]), Principal = principals0[2] }, new StructuralComparableBytesStructKeyRequiredDependentShadow { - Id = new StructuralComparableBytesStructKey([115]), Principal = principals[2] + Id = new StructuralComparableBytesStructKey([115]), Principal = principals0[2] }, new StructuralComparableBytesStructKeyRequiredDependentShadow { - Id = new StructuralComparableBytesStructKey([116]), Principal = principals[2] + Id = new StructuralComparableBytesStructKey([116]), Principal = principals0[2] }); - Assert.Equal(10, context.SaveChanges()); + Assert.Equal(10, await context.SaveChangesAsync()); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -4856,12 +4825,12 @@ public virtual void Can_insert_and_read_back_with_structural_struct_binary_key_a Id = new StructuralComparableBytesStructKey(dependents[0].Id.Id), }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -4870,23 +4839,20 @@ public virtual void Can_insert_and_read_back_with_structural_struct_binary_key_a [(0, 0), (2, 2), (3, 0), (5, 0)]); } - void RunQueries( - DbContext context, - out StructuralComparableBytesStructKeyPrincipalShadow[] principals, - out StructuralComparableBytesStructKeyRequiredDependentShadow[] dependents) + async Task RunQueries(DbContext context) { var twelve = new byte[] { 12, 12 }; var thirteen = new StructuralComparableBytesStructKey { Id = [13, 13, 13] }; principals = [ - context.Set().Include(e => e.RequiredDependents) - .Single(e => e.Id.Equals(new StructuralComparableBytesStructKey { Id = new byte[] { 11 } })), - context.Set().Include(e => e.RequiredDependents) - .Single(e => e.Id.Equals(new StructuralComparableBytesStructKey { Id = twelve })), - context.Set().Include(e => e.RequiredDependents) - .Single(e => e.Id.Equals(thirteen)), - context.Set().Include(e => e.RequiredDependents).Single( + await context.Set().Include(e => e.RequiredDependents) + .SingleAsync(e => e.Id.Equals(new StructuralComparableBytesStructKey { Id = new byte[] { 11 } })), + await context.Set().Include(e => e.RequiredDependents) + .SingleAsync(e => e.Id.Equals(new StructuralComparableBytesStructKey { Id = twelve })), + await context.Set().Include(e => e.RequiredDependents) + .SingleAsync(e => e.Id.Equals(thirteen)), + await context.Set().Include(e => e.RequiredDependents).SingleAsync( e => e.Id.Equals(new StructuralComparableBytesStructKey { Id = new byte[] { 14, 14, 14, 14 } })) ]; @@ -4897,38 +4863,38 @@ void RunQueries( dependents = [ - context.Set() - .FirstOrDefault(e => e.Id.Equals(new StructuralComparableBytesStructKey { Id = new byte[] { 111 } })), - context.Set() - .FirstOrDefault(e => e.Id.Equals(new StructuralComparableBytesStructKey { Id = oneTwelve })), - context.Set().FirstOrDefault(e => e.Id.Equals(oneThirteen)), - context.Set() - .FirstOrDefault(e => e.Id.Equals(new StructuralComparableBytesStructKey { Id = new byte[] { 114 } })), - context.Set() - .FirstOrDefault(e => e.Id.Equals(new StructuralComparableBytesStructKey { Id = oneFifteeen })), - context.Set().FirstOrDefault(e => e.Id.Equals(oneSixteen)) + await context.Set() + .FirstOrDefaultAsync(e => e.Id.Equals(new StructuralComparableBytesStructKey { Id = new byte[] { 111 } })), + await context.Set() + .FirstOrDefaultAsync(e => e.Id.Equals(new StructuralComparableBytesStructKey { Id = oneTwelve })), + await context.Set().FirstOrDefaultAsync(e => e.Id.Equals(oneThirteen)), + await context.Set() + .FirstOrDefaultAsync(e => e.Id.Equals(new StructuralComparableBytesStructKey { Id = new byte[] { 114 } })), + await context.Set() + .FirstOrDefaultAsync(e => e.Id.Equals(new StructuralComparableBytesStructKey { Id = oneFifteeen })), + await context.Set().FirstOrDefaultAsync(e => e.Id.Equals(oneSixteen)) ]; Assert.Same( dependents[0], - context.Set() - .Find(new StructuralComparableBytesStructKey { Id = [111] })); + await context.Set() + .FindAsync(new StructuralComparableBytesStructKey { Id = [111] })); Assert.Same( dependents[1], - context.Set() - .Find(new StructuralComparableBytesStructKey { Id = oneTwelve })); - Assert.Same(dependents[2], context.Set().Find(oneThirteen)); + await context.Set() + .FindAsync(new StructuralComparableBytesStructKey { Id = oneTwelve })); + Assert.Same(dependents[2], await context.Set().FindAsync(oneThirteen)); Assert.Same( dependents[3], - context.Find( + await context.FindAsync( typeof(StructuralComparableBytesStructKeyRequiredDependentShadow), new StructuralComparableBytesStructKey { Id = [114] })); Assert.Same( dependents[4], - context.Find( + await context.FindAsync( typeof(StructuralComparableBytesStructKeyRequiredDependentShadow), new StructuralComparableBytesStructKey { Id = oneFifteeen })); - Assert.Same(dependents[5], context.Find(typeof(StructuralComparableBytesStructKeyRequiredDependentShadow), oneSixteen)); + Assert.Same(dependents[5], await context.FindAsync(typeof(StructuralComparableBytesStructKeyRequiredDependentShadow), oneSixteen)); } void Validate( @@ -4976,11 +4942,13 @@ void Validate( } [ConditionalFact] - public virtual void Can_insert_and_read_back_with_generic_comparable_struct_binary_key_and_required_dependents_with_shadow_FK() + public virtual async Task Can_insert_and_read_back_with_generic_comparable_struct_binary_key_and_required_dependents_with_shadow_FK() { + GenericComparableBytesStructKeyPrincipalShadow[] principals = null; + GenericComparableBytesStructKeyRequiredDependentShadow[] dependents = null; using (var context = CreateContext()) { - var principals = new GenericComparableBytesStructKeyPrincipalShadow[] + var principals0 = new GenericComparableBytesStructKeyPrincipalShadow[] { new() { Id = new GenericComparableBytesStructKey([11]), Foo = "X1" }, new() { Id = new GenericComparableBytesStructKey([12, 12]), Foo = "X2" }, @@ -4988,40 +4956,40 @@ public virtual void Can_insert_and_read_back_with_generic_comparable_struct_bina new() { Id = new GenericComparableBytesStructKey([14, 14, 14, 14]), Foo = "X4" } }; - context.Set().AddRange(principals); + context.Set().AddRange(principals0); context.Set().AddRange( new GenericComparableBytesStructKeyRequiredDependentShadow { - Id = new GenericComparableBytesStructKey([111]), Principal = principals[0] + Id = new GenericComparableBytesStructKey([111]), Principal = principals0[0] }, new GenericComparableBytesStructKeyRequiredDependentShadow { - Id = new GenericComparableBytesStructKey([112]), Principal = principals[1] + Id = new GenericComparableBytesStructKey([112]), Principal = principals0[1] }, new GenericComparableBytesStructKeyRequiredDependentShadow { - Id = new GenericComparableBytesStructKey([113]), Principal = principals[2] + Id = new GenericComparableBytesStructKey([113]), Principal = principals0[2] }, new GenericComparableBytesStructKeyRequiredDependentShadow { - Id = new GenericComparableBytesStructKey([114]), Principal = principals[2] + Id = new GenericComparableBytesStructKey([114]), Principal = principals0[2] }, new GenericComparableBytesStructKeyRequiredDependentShadow { - Id = new GenericComparableBytesStructKey([115]), Principal = principals[2] + Id = new GenericComparableBytesStructKey([115]), Principal = principals0[2] }, new GenericComparableBytesStructKeyRequiredDependentShadow { - Id = new GenericComparableBytesStructKey([116]), Principal = principals[2] + Id = new GenericComparableBytesStructKey([116]), Principal = principals0[2] }); - Assert.Equal(10, context.SaveChanges()); + Assert.Equal(10, await context.SaveChangesAsync()); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -5046,12 +5014,12 @@ public virtual void Can_insert_and_read_back_with_generic_comparable_struct_bina Id = new GenericComparableBytesStructKey(dependents[0].Id.Id), }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - RunQueries(context, out var principals, out var dependents); + await RunQueries(context); Validate( principals, @@ -5060,23 +5028,20 @@ public virtual void Can_insert_and_read_back_with_generic_comparable_struct_bina [(0, 0), (2, 2), (3, 0), (5, 0)]); } - void RunQueries( - DbContext context, - out GenericComparableBytesStructKeyPrincipalShadow[] principals, - out GenericComparableBytesStructKeyRequiredDependentShadow[] dependents) + async Task RunQueries(DbContext context) { var twelve = new byte[] { 12, 12 }; var thirteen = new GenericComparableBytesStructKey { Id = [13, 13, 13] }; principals = [ - context.Set().Include(e => e.RequiredDependents) - .Single(e => e.Id.Equals(new GenericComparableBytesStructKey { Id = new byte[] { 11 } })), - context.Set().Include(e => e.RequiredDependents) - .Single(e => e.Id.Equals(new GenericComparableBytesStructKey { Id = twelve })), - context.Set().Include(e => e.RequiredDependents) - .Single(e => e.Id.Equals(thirteen)), - context.Set().Include(e => e.RequiredDependents).Single( + await context.Set().Include(e => e.RequiredDependents) + .SingleAsync(e => e.Id.Equals(new GenericComparableBytesStructKey { Id = new byte[] { 11 } })), + await context.Set().Include(e => e.RequiredDependents) + .SingleAsync(e => e.Id.Equals(new GenericComparableBytesStructKey { Id = twelve })), + await context.Set().Include(e => e.RequiredDependents) + .SingleAsync(e => e.Id.Equals(thirteen)), + await context.Set().Include(e => e.RequiredDependents).SingleAsync( e => e.Id.Equals(new GenericComparableBytesStructKey { Id = new byte[] { 14, 14, 14, 14 } })) ]; @@ -5087,38 +5052,38 @@ void RunQueries( dependents = [ - context.Set() - .FirstOrDefault(e => e.Id.Equals(new GenericComparableBytesStructKey { Id = new byte[] { 111 } })), - context.Set() - .FirstOrDefault(e => e.Id.Equals(new GenericComparableBytesStructKey { Id = oneTwelve })), - context.Set().FirstOrDefault(e => e.Id.Equals(oneThirteen)), - context.Set() - .FirstOrDefault(e => e.Id.Equals(new GenericComparableBytesStructKey { Id = new byte[] { 114 } })), - context.Set() - .FirstOrDefault(e => e.Id.Equals(new GenericComparableBytesStructKey { Id = oneFifteeen })), - context.Set().FirstOrDefault(e => e.Id.Equals(oneSixteen)) + await context.Set() + .FirstOrDefaultAsync(e => e.Id.Equals(new GenericComparableBytesStructKey { Id = new byte[] { 111 } })), + await context.Set() + .FirstOrDefaultAsync(e => e.Id.Equals(new GenericComparableBytesStructKey { Id = oneTwelve })), + await context.Set().FirstOrDefaultAsync(e => e.Id.Equals(oneThirteen)), + await context.Set() + .FirstOrDefaultAsync(e => e.Id.Equals(new GenericComparableBytesStructKey { Id = new byte[] { 114 } })), + await context.Set() + .FirstOrDefaultAsync(e => e.Id.Equals(new GenericComparableBytesStructKey { Id = oneFifteeen })), + await context.Set().FirstOrDefaultAsync(e => e.Id.Equals(oneSixteen)) ]; Assert.Same( dependents[0], - context.Set() - .Find(new GenericComparableBytesStructKey { Id = [111] })); + await context.Set() + .FindAsync(new GenericComparableBytesStructKey { Id = [111] })); Assert.Same( dependents[1], - context.Set() - .Find(new GenericComparableBytesStructKey { Id = oneTwelve })); - Assert.Same(dependents[2], context.Set().Find(oneThirteen)); + await context.Set() + .FindAsync(new GenericComparableBytesStructKey { Id = oneTwelve })); + Assert.Same(dependents[2], await context.Set().FindAsync(oneThirteen)); Assert.Same( dependents[3], - context.Find( + await context.FindAsync( typeof(GenericComparableBytesStructKeyRequiredDependentShadow), new GenericComparableBytesStructKey { Id = [114] })); Assert.Same( dependents[4], - context.Find( + await context.FindAsync( typeof(GenericComparableBytesStructKeyRequiredDependentShadow), new GenericComparableBytesStructKey { Id = oneFifteeen })); - Assert.Same(dependents[5], context.Find(typeof(GenericComparableBytesStructKeyRequiredDependentShadow), oneSixteen)); + Assert.Same(dependents[5], await context.FindAsync(typeof(GenericComparableBytesStructKeyRequiredDependentShadow), oneSixteen)); } void Validate( @@ -5165,7 +5130,7 @@ void Validate( } } - private void InsertOptionalGraph() + private async Task InsertOptionalGraph() where TPrincipal : class, IIntPrincipal, new() where TDependent : class, IIntOptionalDependent, new() { @@ -5185,10 +5150,10 @@ private void InsertOptionalGraph() new TDependent { BackingId = 105, BackingPrincipalId = 3 }, new TDependent { BackingId = 106 }); - Assert.Equal(10, context.SaveChanges()); + Assert.Equal(10, await context.SaveChangesAsync()); } - private void InsertRequiredGraph() + private async Task InsertRequiredGraph() where TPrincipal : class, IIntPrincipal, new() where TDependent : class, IIntRequiredDependent, new() { @@ -5208,7 +5173,7 @@ private void InsertRequiredGraph() new TDependent { BackingId = 115, BackingPrincipalId = 13 }, new TDependent { BackingId = 116, BackingPrincipalId = 13 }); - Assert.Equal(10, context.SaveChanges()); + Assert.Equal(10, await context.SaveChangesAsync()); } protected void ValidateOptional( @@ -5296,7 +5261,7 @@ protected void ValidateRequired( } } - private void InsertOptionalBytesGraph() + private async Task InsertOptionalBytesGraph() where TPrincipal : class, IBytesPrincipal, new() where TDependent : class, IBytesOptionalDependent, new() { @@ -5315,10 +5280,10 @@ private void InsertOptionalBytesGraph() new TDependent { BackingId = [105], BackingPrincipalId = [3, 3, 3] }, new TDependent { BackingId = [106] }); - Assert.Equal(10, context.SaveChanges()); + Assert.Equal(10, await context.SaveChangesAsync()); } - private void InsertRequiredBytesGraph() + private async Task InsertRequiredBytesGraph() where TPrincipal : class, IBytesPrincipal, new() where TDependent : class, IBytesRequiredDependent, new() { @@ -5337,7 +5302,7 @@ private void InsertRequiredBytesGraph() new TDependent { BackingId = [115], BackingPrincipalId = [13, 13, 13] }, new TDependent { BackingId = [116], BackingPrincipalId = [13, 13, 13] }); - Assert.Equal(10, context.SaveChanges()); + Assert.Equal(10, await context.SaveChangesAsync()); } protected void ValidateOptionalBytes( diff --git a/test/EFCore.Specification.Tests/LazyLoadProxyTestBase.cs b/test/EFCore.Specification.Tests/LazyLoadProxyTestBase.cs index a29f5fc4606..e05b1ae5b21 100644 --- a/test/EFCore.Specification.Tests/LazyLoadProxyTestBase.cs +++ b/test/EFCore.Specification.Tests/LazyLoadProxyTestBase.cs @@ -5228,7 +5228,7 @@ protected override void ConfigureConventions(ModelConfigurationBuilder configura configurationBuilder.ComplexProperties(); } - protected override void Seed(DbContext context) + protected override Task SeedAsync(DbContext context) { context.Add( new Quest @@ -5579,7 +5579,7 @@ protected override void Seed(DbContext context) Milk = CreateMilk() }); - context.SaveChanges(); + return context.SaveChangesAsync(); } protected static Culture CreateCulture() diff --git a/test/EFCore.Specification.Tests/LoadTestBase.cs b/test/EFCore.Specification.Tests/LoadTestBase.cs index ade224f8c5f..ec9e20eec38 100644 --- a/test/EFCore.Specification.Tests/LoadTestBase.cs +++ b/test/EFCore.Specification.Tests/LoadTestBase.cs @@ -6059,7 +6059,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con modelBuilder.Entity().HasNoKey(); } - protected override void Seed(PoolableDbContext context) + protected override Task SeedAsync(PoolableDbContext context) { context.Add( new Parent @@ -6113,7 +6113,7 @@ protected override void Seed(PoolableDbContext context) context.Add( new SimpleProduct { Deposit = new Deposit() }); - context.SaveChanges(); + return context.SaveChangesAsync(); } } } diff --git a/test/EFCore.Specification.Tests/ManyToManyTrackingTestBase.cs b/test/EFCore.Specification.Tests/ManyToManyTrackingTestBase.cs index d170b4760cf..0bc6a1473bd 100644 --- a/test/EFCore.Specification.Tests/ManyToManyTrackingTestBase.cs +++ b/test/EFCore.Specification.Tests/ManyToManyTrackingTestBase.cs @@ -140,13 +140,13 @@ void ValidateFixup(DbContext context, IList leftEntities, IL } [ConditionalFact] - public virtual void Can_update_many_to_many_composite_with_navs() + public virtual Task Can_update_many_to_many_composite_with_navs() { - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var leftEntities = context.Set().Include(e => e.LeafSkipFull).OrderBy(e => e.Key2).ToList(); - var rightEntities = context.Set().Include(e => e.CompositeKeySkipFull).OrderBy(e => e.Name).ToList(); + var leftEntities = await context.Set().Include(e => e.LeafSkipFull).OrderBy(e => e.Key2).ToListAsync(); + var rightEntities = await context.Set().Include(e => e.CompositeKeySkipFull).OrderBy(e => e.Name).ToListAsync(); leftEntities[0].LeafSkipFull.Add( context.Set().CreateInstance( @@ -228,14 +228,13 @@ public virtual void Can_update_many_to_many_composite_with_navs() ValidateFixup(context, leftEntities, rightEntities, 24, 8, 39); - context.SaveChanges(); + await context.SaveChangesAsync(); ValidateFixup(context, leftEntities, rightEntities, 24, 8, 39 - 4); - }, - context => + }, async context => { - var leftEntities = context.Set().Include(e => e.LeafSkipFull).OrderBy(e => e.Key2).ToList(); - var rightEntities = context.Set().Include(e => e.CompositeKeySkipFull).OrderBy(e => e.Name).ToList(); + var leftEntities = await context.Set().Include(e => e.LeafSkipFull).OrderBy(e => e.Key2).ToListAsync(); + var rightEntities = await context.Set().Include(e => e.CompositeKeySkipFull).OrderBy(e => e.Name).ToListAsync(); ValidateFixup(context, leftEntities, rightEntities, 24, 8, 39 - 4); }); @@ -316,21 +315,21 @@ void ValidateFixup( } [ConditionalFact] - public virtual void Can_delete_with_many_to_many_composite_with_navs() + public virtual Task Can_delete_with_many_to_many_composite_with_navs() { var key1 = 0; var key2 = ""; var key3 = default(DateTime); var id = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var ones = context.Set().Include(e => e.RootSkipShared).OrderBy(e => e.Key2).ToList(); - var threes = context.Set().Include(e => e.CompositeKeySkipFull).OrderBy(e => e.Name).ToList(); + var ones = await context.Set().Include(e => e.RootSkipShared).OrderBy(e => e.Key2).ToListAsync(); + var threes = await context.Set().Include(e => e.CompositeKeySkipFull).OrderBy(e => e.Name).ToListAsync(); // Make sure other related entities are loaded for delete fixup - context.Set().Load(); + await context.Set().LoadAsync(); var toRemoveOne = context.EntityCompositeKeys.Single(e => e.Name == "Composite 6"); key1 = toRemoveOne.Key1; @@ -379,7 +378,7 @@ public virtual void Can_delete_with_many_to_many_composite_with_navs() ? EntityState.Deleted : EntityState.Unchanged, e.State)); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.Equal(0, threes.SelectMany(e => e.CompositeKeySkipFull).Count(e => e == toRemoveOne)); Assert.Equal(0, ones.SelectMany(e => e.RootSkipShared).Count(e => e == toRemoveThree)); @@ -398,11 +397,10 @@ public virtual void Can_delete_with_many_to_many_composite_with_navs() && e.Entity.CompositeId2 == key2 && e.Entity.CompositeId3 == key3) || e.Entity.LeafId == id); - }, - context => + }, async context => { - var ones = context.Set().Include(e => e.RootSkipShared).OrderBy(e => e.Key2).ToList(); - var threes = context.Set().Include(e => e.CompositeKeySkipFull).OrderBy(e => e.Name).ToList(); + var ones = await context.Set().Include(e => e.RootSkipShared).OrderBy(e => e.Key2).ToListAsync(); + var threes = await context.Set().Include(e => e.CompositeKeySkipFull).OrderBy(e => e.Name).ToListAsync(); ValidateNavigations(ones, threes); @@ -589,15 +587,15 @@ void ValidateFixup(DbContext context, IList leftEntities, IL } [ConditionalFact] - public virtual void Can_update_many_to_many_composite_shared_with_navs() + public virtual Task Can_update_many_to_many_composite_shared_with_navs() { List rootKeys = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var leftEntities = context.Set().Include(e => e.RootSkipShared).OrderBy(e => e.Key2).ToList(); - var rightEntities = context.Set().Include(e => e.CompositeKeySkipShared).OrderBy(e => e.Name).ToList(); + var leftEntities = await context.Set().Include(e => e.RootSkipShared).OrderBy(e => e.Key2).ToListAsync(); + var rightEntities = await context.Set().Include(e => e.CompositeKeySkipShared).OrderBy(e => e.Name).ToListAsync(); var roots = new[] { @@ -682,16 +680,15 @@ public virtual void Can_update_many_to_many_composite_shared_with_navs() ValidateFixup(context, leftEntities, rightEntities, 24, 24, 47); - context.SaveChanges(); + await context.SaveChangesAsync(); rootKeys = roots.Select(e => e.Id).ToList(); ValidateFixup(context, leftEntities, rightEntities, 24, 24, 47 - 4); - }, - context => + }, async context => { - var leftEntities = context.Set().Include(e => e.RootSkipShared).OrderBy(e => e.Key2).ToList(); - var rightEntities = context.Set().Include(e => e.CompositeKeySkipShared).OrderBy(e => e.Name).ToList(); + var leftEntities = await context.Set().Include(e => e.RootSkipShared).OrderBy(e => e.Key2).ToListAsync(); + var rightEntities = await context.Set().Include(e => e.CompositeKeySkipShared).OrderBy(e => e.Name).ToListAsync(); ValidateFixup(context, leftEntities, rightEntities, 24, 24, 47 - 4); }); @@ -757,18 +754,18 @@ void ValidateFixup( } [ConditionalFact] - public virtual void Can_delete_with_many_to_many_composite_shared_with_navs() + public virtual Task Can_delete_with_many_to_many_composite_shared_with_navs() { var key1 = 0; var key2 = ""; var key3 = default(DateTime); var id = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var ones = context.Set().Include(e => e.RootSkipShared).OrderBy(e => e.Key2).ToList(); - var threes = context.Set().Include(e => e.CompositeKeySkipShared).OrderBy(e => e.Name).ToList(); + var ones = await context.Set().Include(e => e.RootSkipShared).OrderBy(e => e.Key2).ToListAsync(); + var threes = await context.Set().Include(e => e.CompositeKeySkipShared).OrderBy(e => e.Name).ToListAsync(); // Make sure other related entities are loaded for delete fixup context.Set().Load(); @@ -806,7 +803,7 @@ public virtual void Can_delete_with_many_to_many_composite_shared_with_navs() ? EntityState.Deleted : EntityState.Unchanged, e.State)); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.Equal(0, threes.SelectMany(e => e.CompositeKeySkipShared).Count(e => e == toRemoveOne)); Assert.Equal(0, ones.SelectMany(e => e.RootSkipShared).Count(e => e == toRemoveThree)); @@ -823,11 +820,10 @@ public virtual void Can_delete_with_many_to_many_composite_shared_with_navs() && (string)e.Entity["CompositeKeySkipSharedKey2"] == key2 && (DateTime)e.Entity["CompositeKeySkipSharedKey3"] == key3) || (int)e.Entity["RootSkipSharedId"] == id); - }, - context => + }, async context => { - var ones = context.Set().Include(e => e.RootSkipShared).OrderBy(e => e.Key2).ToList(); - var threes = context.Set().Include(e => e.CompositeKeySkipShared).OrderBy(e => e.Name).ToList(); + var ones = await context.Set().Include(e => e.RootSkipShared).OrderBy(e => e.Key2).ToListAsync(); + var threes = await context.Set().Include(e => e.CompositeKeySkipShared).OrderBy(e => e.Name).ToListAsync(); ValidateNavigations(ones, threes); @@ -1014,15 +1010,15 @@ void ValidateFixup(DbContext context, IList leftEntities, IL } [ConditionalFact] - public virtual void Can_update_many_to_many_composite_additional_pk_with_navs() + public virtual Task Can_update_many_to_many_composite_additional_pk_with_navs() { List threeIds = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var leftEntities = context.Set().Include(e => e.ThreeSkipFull).OrderBy(e => e.Key2).ToList(); - var rightEntities = context.Set().Include(e => e.CompositeKeySkipFull).OrderBy(e => e.Name).ToList(); + var leftEntities = await context.Set().Include(e => e.ThreeSkipFull).OrderBy(e => e.Key2).ToListAsync(); + var rightEntities = await context.Set().Include(e => e.CompositeKeySkipFull).OrderBy(e => e.Name).ToListAsync(); var threes = new[] { @@ -1112,16 +1108,15 @@ public virtual void Can_update_many_to_many_composite_additional_pk_with_navs() ValidateFixup(context, leftEntities, rightEntities, 24, 24, 53); - context.SaveChanges(); + await context.SaveChangesAsync(); threeIds = threes.Select(e => e.Id).ToList(); ValidateFixup(context, leftEntities, rightEntities, 24, 24, 53 - 4); - }, - context => + }, async context => { - var leftEntities = context.Set().Include(e => e.ThreeSkipFull).OrderBy(e => e.Key2).ToList(); - var rightEntities = context.Set().Include(e => e.CompositeKeySkipFull).OrderBy(e => e.Name).ToList(); + var leftEntities = await context.Set().Include(e => e.ThreeSkipFull).OrderBy(e => e.Key2).ToListAsync(); + var rightEntities = await context.Set().Include(e => e.CompositeKeySkipFull).OrderBy(e => e.Name).ToListAsync(); ValidateFixup(context, leftEntities, rightEntities, 24, 24, 53 - 4); }); @@ -1202,18 +1197,18 @@ void ValidateFixup( } [ConditionalFact] - public virtual void Can_delete_with_many_to_many_composite_additional_pk_with_navs() + public virtual Task Can_delete_with_many_to_many_composite_additional_pk_with_navs() { var threeId = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var ones = context.Set().Include(e => e.ThreeSkipFull).OrderBy(e => e.Key2).ToList(); - var threes = context.Set().Include(e => e.CompositeKeySkipFull).OrderBy(e => e.Name).ToList(); + var ones = await context.Set().Include(e => e.ThreeSkipFull).OrderBy(e => e.Key2).ToListAsync(); + var threes = await context.Set().Include(e => e.CompositeKeySkipFull).OrderBy(e => e.Name).ToListAsync(); // Make sure other related entities are loaded for delete fixup - context.Set().Load(); + await context.Set().LoadAsync(); var toRemoveOne = context.EntityCompositeKeys.Single(e => e.Name == "Composite 6"); var refCountOnes = threes.SelectMany(e => e.CompositeKeySkipFull).Count(e => e == toRemoveOne); @@ -1258,7 +1253,7 @@ public virtual void Can_delete_with_many_to_many_composite_additional_pk_with_na ? EntityState.Deleted : EntityState.Unchanged, e.State)); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.Equal(0, threes.SelectMany(e => e.CompositeKeySkipFull).Count(e => e == toRemoveOne)); Assert.Equal(0, ones.SelectMany(e => e.ThreeSkipFull).Count(e => e == toRemoveThree)); @@ -1276,11 +1271,10 @@ public virtual void Can_delete_with_many_to_many_composite_additional_pk_with_na e => (e.Entity.CompositeId2 == "6_1" && e.Entity.CompositeId3 == new DateTime(2006, 1, 1)) || e.Entity.ThreeId == threeId); - }, - context => + }, async context => { - var ones = context.Set().Include(e => e.ThreeSkipFull).OrderBy(e => e.Key2).ToList(); - var threes = context.Set().Include(e => e.CompositeKeySkipFull).OrderBy(e => e.Name).ToList(); + var ones = await context.Set().Include(e => e.ThreeSkipFull).OrderBy(e => e.Key2).ToListAsync(); + var threes = await context.Set().Include(e => e.CompositeKeySkipFull).OrderBy(e => e.Name).ToListAsync(); ValidateNavigations(ones, threes); @@ -1455,15 +1449,15 @@ void ValidateFixup(DbContext context, IList leftEntities, IList ids = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var leftEntities = context.Set().Include(e => e.SelfSkipSharedRight).OrderBy(e => e.Name).ToList(); - var rightEntities = context.Set().Include(e => e.SelfSkipSharedLeft).OrderBy(e => e.Name).ToList(); + var leftEntities = await context.Set().Include(e => e.SelfSkipSharedRight).OrderBy(e => e.Name).ToListAsync(); + var rightEntities = await context.Set().Include(e => e.SelfSkipSharedLeft).OrderBy(e => e.Name).ToListAsync(); var twos = new[] { @@ -1543,16 +1537,15 @@ public virtual void Can_update_many_to_many_self() ValidateFixup(context, leftEntities, rightEntities, 28, 42); - context.SaveChanges(); + await context.SaveChangesAsync(); ids = twos.Select(e => e.Id).ToList(); ValidateFixup(context, leftEntities, rightEntities, 28, 42 - 4); - }, - context => + }, async context => { - var leftEntities = context.Set().Include(e => e.SelfSkipSharedRight).OrderBy(e => e.Name).ToList(); - var rightEntities = context.Set().Include(e => e.SelfSkipSharedLeft).OrderBy(e => e.Name).ToList(); + var leftEntities = await context.Set().Include(e => e.SelfSkipSharedRight).OrderBy(e => e.Name).ToListAsync(); + var rightEntities = await context.Set().Include(e => e.SelfSkipSharedLeft).OrderBy(e => e.Name).ToListAsync(); ValidateFixup(context, leftEntities, rightEntities, 28, 42 - 4); }); @@ -1719,13 +1712,13 @@ void ValidateFixup(DbContext context, IList leftEntities, IList + return ExecuteWithStrategyInTransactionAsync( + async context => { - var leftEntities = context.Set().Include(e => e.ThreeSkipFull).OrderBy(e => e.Name).ToList(); - var rightEntities = context.Set().Include(e => e.TwoSkipFull).OrderBy(e => e.Name).ToList(); + var leftEntities = await context.Set().Include(e => e.ThreeSkipFull).OrderBy(e => e.Name).ToListAsync(); + var rightEntities = await context.Set().Include(e => e.TwoSkipFull).OrderBy(e => e.Name).ToListAsync(); leftEntities[0].ThreeSkipFull.Add( context.EntityThrees.CreateInstance( @@ -1799,14 +1792,13 @@ public virtual void Can_update_many_to_many_with_navs() ValidateFixup(context, leftEntities, rightEntities, 24, 24, 60); - context.SaveChanges(); + await context.SaveChangesAsync(); ValidateFixup(context, leftEntities, rightEntities, 24, 24, 60 - 4); - }, - context => + }, async context => { - var leftEntities = context.Set().Include(e => e.ThreeSkipFull).OrderBy(e => e.Name).ToList(); - var rightEntities = context.Set().Include(e => e.TwoSkipFull).OrderBy(e => e.Name).ToList(); + var leftEntities = await context.Set().Include(e => e.ThreeSkipFull).OrderBy(e => e.Name).ToListAsync(); + var rightEntities = await context.Set().Include(e => e.TwoSkipFull).OrderBy(e => e.Name).ToListAsync(); ValidateFixup(context, leftEntities, rightEntities, 24, 24, 60 - 4); }); @@ -1976,13 +1968,13 @@ void ValidateFixup(DbContext context, IList leftEntities, IList + return ExecuteWithStrategyInTransactionAsync( + async context => { - var leftEntities = context.Set().Include(e => e.BranchSkip).OrderBy(e => e.Name).ToList(); - var rightEntities = context.Set().Include(e => e.OneSkip).OrderBy(e => e.Name).ToList(); + var leftEntities = await context.Set().Include(e => e.BranchSkip).OrderBy(e => e.Name).ToListAsync(); + var rightEntities = await context.Set().Include(e => e.OneSkip).OrderBy(e => e.Name).ToListAsync(); leftEntities[0].BranchSkip.Add( context.Set().CreateInstance( @@ -2056,14 +2048,13 @@ public virtual void Can_update_many_to_many_with_inheritance() ValidateFixup(context, leftEntities, rightEntities, 24, 14, 55); - context.SaveChanges(); + await context.SaveChangesAsync(); ValidateFixup(context, leftEntities, rightEntities, 24, 14, 55 - 4); - }, - context => + }, async context => { - var leftEntities = context.Set().Include(e => e.BranchSkip).OrderBy(e => e.Name).ToList(); - var rightEntities = context.Set().Include(e => e.OneSkip).OrderBy(e => e.Name).ToList(); + var leftEntities = await context.Set().Include(e => e.BranchSkip).OrderBy(e => e.Name).ToListAsync(); + var rightEntities = await context.Set().Include(e => e.OneSkip).OrderBy(e => e.Name).ToListAsync(); ValidateFixup(context, leftEntities, rightEntities, 24, 14, 55 - 4); }); @@ -2255,15 +2246,15 @@ void ValidateFixup(DbContext context, IList leftEntities, IList keys = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var leftEntities = context.Set().Include(e => e.SelfSkipPayloadRight).OrderBy(e => e.Name).ToList(); - var rightEntities = context.Set().Include(e => e.SelfSkipPayloadLeft).OrderBy(e => e.Name).ToList(); + var leftEntities = await context.Set().Include(e => e.SelfSkipPayloadRight).OrderBy(e => e.Name).ToListAsync(); + var rightEntities = await context.Set().Include(e => e.SelfSkipPayloadLeft).OrderBy(e => e.Name).ToListAsync(); var ones = new[] { @@ -2342,28 +2333,27 @@ public virtual void Can_update_many_to_many_self_with_payload() keys = ones.Select(e => context.Entry(e).Property(e => e.Id).CurrentValue).ToList(); - context.Find( + (await context.FindAsync( keys[5], - context.Entry(context.EntityOnes.Local.Single(e => e.Name == "EntityOne 1")).Property(e => e.Id).CurrentValue) + context.Entry(context.EntityOnes.Local.Single(e => e.Name == "EntityOne 1")).Property(e => e.Id).CurrentValue))! .Payload = new DateTime(1973, 9, 3); - context.Find( + (await context.FindAsync( context.Entry(context.EntityOnes.Local.Single(e => e.Name == "EntityOne 20")).Property(e => e.Id).CurrentValue, - context.Entry(context.EntityOnes.Local.Single(e => e.Name == "EntityOne 16")).Property(e => e.Id).CurrentValue) + context.Entry(context.EntityOnes.Local.Single(e => e.Name == "EntityOne 16")).Property(e => e.Id).CurrentValue))! .Payload = new DateTime(1969, 8, 3); ValidateFixup(context, leftEntities, rightEntities, 28, 37, postSave: false); - context.SaveChanges(); + await context.SaveChangesAsync(); keys = ones.Select(e => e.Id).ToList(); ValidateFixup(context, leftEntities, rightEntities, 28, 37 - 4, postSave: true); - }, - context => + }, async context => { - var leftEntities = context.Set().Include(e => e.SelfSkipPayloadRight).OrderBy(e => e.Name).ToList(); - var rightEntities = context.Set().Include(e => e.SelfSkipPayloadLeft).OrderBy(e => e.Name).ToList(); + var leftEntities = await context.Set().Include(e => e.SelfSkipPayloadRight).OrderBy(e => e.Name).ToListAsync(); + var rightEntities = await context.Set().Include(e => e.SelfSkipPayloadLeft).OrderBy(e => e.Name).ToListAsync(); ValidateFixup(context, leftEntities, rightEntities, 28, 37 - 4, postSave: true); }); @@ -2556,13 +2546,13 @@ void ValidateFixup(DbContext context, IList leftEntities, IList + return ExecuteWithStrategyInTransactionAsync( + async context => { - var leftEntities = context.Set().Include(e => e.ThreeSkipPayloadFullShared).OrderBy(e => e.Name).ToList(); - var rightEntities = context.Set().Include(e => e.OneSkipPayloadFullShared).OrderBy(e => e.Name).ToList(); + var leftEntities = await context.Set().Include(e => e.ThreeSkipPayloadFullShared).OrderBy(e => e.Name).ToListAsync(); + var rightEntities = await context.Set().Include(e => e.OneSkipPayloadFullShared).OrderBy(e => e.Name).ToListAsync(); leftEntities[0].ThreeSkipPayloadFullShared.Add( context.EntityThrees.CreateInstance( @@ -2641,21 +2631,20 @@ public virtual void Can_update_many_to_many_shared_with_payload() } var joinSet = context.Set>("JoinOneToThreePayloadFullShared"); - joinSet.Find( - GetEntityOneId(context, "Z7712"), GetEntityThreeId(context, "EntityThree 1"))["Payload"] = "Set!"; - joinSet.Find( - GetEntityOneId(context, "EntityOne 20"), GetEntityThreeId(context, "EntityThree 16"))["Payload"] = "Changed!"; + (await joinSet.FindAsync( + GetEntityOneId(context, "Z7712"), GetEntityThreeId(context, "EntityThree 1")))!["Payload"] = "Set!"; + (await joinSet.FindAsync( + GetEntityOneId(context, "EntityOne 20"), GetEntityThreeId(context, "EntityThree 16")))!["Payload"] = "Changed!"; ValidateFixup(context, leftEntities, rightEntities, 24, 24, 48, postSave: false); - context.SaveChanges(); + await context.SaveChangesAsync(); ValidateFixup(context, leftEntities, rightEntities, 24, 24, 48 - 4, postSave: true); - }, - context => + }, async context => { - var leftEntities = context.Set().Include(e => e.ThreeSkipPayloadFullShared).OrderBy(e => e.Name).ToList(); - var rightEntities = context.Set().Include(e => e.OneSkipPayloadFullShared).OrderBy(e => e.Name).ToList(); + var leftEntities = await context.Set().Include(e => e.ThreeSkipPayloadFullShared).OrderBy(e => e.Name).ToListAsync(); + var rightEntities = await context.Set().Include(e => e.OneSkipPayloadFullShared).OrderBy(e => e.Name).ToListAsync(); ValidateFixup(context, leftEntities, rightEntities, 24, 24, 48 - 4, postSave: true); }); @@ -2847,13 +2836,13 @@ void ValidateFixup(DbContext context, IList leftEntities, IList + return ExecuteWithStrategyInTransactionAsync( + async context => { - var leftEntities = context.Set().Include(e => e.TwoSkipShared).OrderBy(e => e.Name).ToList(); - var rightEntities = context.Set().Include(e => e.OneSkipShared).OrderBy(e => e.Name).ToList(); + var leftEntities = await context.Set().Include(e => e.TwoSkipShared).OrderBy(e => e.Name).ToListAsync(); + var rightEntities = await context.Set().Include(e => e.OneSkipShared).OrderBy(e => e.Name).ToListAsync(); var twos = new[] { @@ -2935,14 +2924,13 @@ public virtual void Can_update_many_to_many_shared() ValidateFixup(context, leftEntities, rightEntities, 24, 24, 53); - context.SaveChanges(); + await context.SaveChangesAsync(); ValidateFixup(context, leftEntities, rightEntities, 24, 24, 49); - }, - context => + }, async context => { - var leftEntities = context.Set().Include(e => e.TwoSkipShared).OrderBy(e => e.Name).ToList(); - var rightEntities = context.Set().Include(e => e.OneSkipShared).OrderBy(e => e.Name).ToList(); + var leftEntities = await context.Set().Include(e => e.TwoSkipShared).OrderBy(e => e.Name).ToListAsync(); + var rightEntities = await context.Set().Include(e => e.OneSkipShared).OrderBy(e => e.Name).ToListAsync(); ValidateFixup(context, leftEntities, rightEntities, 24, 24, 49); }); @@ -3116,13 +3104,13 @@ void ValidateFixup(DbContext context, IList leftEntities, IList + return ExecuteWithStrategyInTransactionAsync( + async context => { - var leftEntities = context.Set().Include(e => e.ThreeSkipPayloadFull).OrderBy(e => e.Name).ToList(); - var rightEntities = context.Set().Include(e => e.OneSkipPayloadFull).OrderBy(e => e.Name).ToList(); + var leftEntities = await context.Set().Include(e => e.ThreeSkipPayloadFull).OrderBy(e => e.Name).ToListAsync(); + var rightEntities = await context.Set().Include(e => e.OneSkipPayloadFull).OrderBy(e => e.Name).ToListAsync(); leftEntities[0].ThreeSkipPayloadFull.Add( context.EntityThrees.CreateInstance( @@ -3196,13 +3184,13 @@ public virtual void Can_update_many_to_many_with_payload() context.ChangeTracker.DetectChanges(); } - context.Find( + (await context.FindAsync( GetEntityOneId(context, "Z7712"), - GetEntityThreeId(context, "EntityThree 1")).Payload = "Set!"; + GetEntityThreeId(context, "EntityThree 1")))!.Payload = "Set!"; - context.Find( + (await context.FindAsync( GetEntityOneId(context, "EntityOne 20"), - GetEntityThreeId(context, "EntityThree 20")).Payload = "Changed!"; + GetEntityThreeId(context, "EntityThree 20")))!.Payload = "Changed!"; if (RequiresDetectChanges) { @@ -3211,14 +3199,13 @@ public virtual void Can_update_many_to_many_with_payload() ValidateFixup(context, leftEntities, rightEntities, 24, 24, 123, postSave: false); - context.SaveChanges(); + await context.SaveChangesAsync(); ValidateFixup(context, leftEntities, rightEntities, 24, 24, 123 - 4, postSave: true); - }, - context => + }, async context => { - var leftEntities = context.Set().Include(e => e.ThreeSkipPayloadFull).OrderBy(e => e.Name).ToList(); - var rightEntities = context.Set().Include(e => e.OneSkipPayloadFull).OrderBy(e => e.Name).ToList(); + var leftEntities = await context.Set().Include(e => e.ThreeSkipPayloadFull).OrderBy(e => e.Name).ToListAsync(); + var rightEntities = await context.Set().Include(e => e.OneSkipPayloadFull).OrderBy(e => e.Name).ToListAsync(); ValidateFixup(context, leftEntities, rightEntities, 24, 24, 123 - 4, postSave: true); }); @@ -3321,18 +3308,18 @@ void ValidateFixup( } [ConditionalFact] - public virtual void Can_delete_with_many_to_many_with_navs() + public virtual Task Can_delete_with_many_to_many_with_navs() { - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var ones = context.Set().Include(e => e.ThreeSkipPayloadFull).OrderBy(e => e.Name).ToList(); - var threes = context.Set().Include(e => e.OneSkipPayloadFull).OrderBy(e => e.Name).ToList(); + var ones = await context.Set().Include(e => e.ThreeSkipPayloadFull).OrderBy(e => e.Name).ToListAsync(); + var threes = await context.Set().Include(e => e.OneSkipPayloadFull).OrderBy(e => e.Name).ToListAsync(); // Make sure other related entities are loaded for delete fixup - context.Set().Load(); - context.Set().Load(); - context.Set().Load(); + await context.Set().LoadAsync(); + await context.Set().LoadAsync(); + await context.Set().LoadAsync(); var toRemoveOne = context.EntityOnes.Single(e => e.Name == "EntityOne 1"); var refCountOnes = threes.SelectMany(e => e.OneSkipPayloadFull).Count(e => e == toRemoveOne); @@ -3373,7 +3360,7 @@ public virtual void Can_delete_with_many_to_many_with_navs() ? EntityState.Deleted : EntityState.Unchanged, e.State)); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.Equal(0, threes.SelectMany(e => e.OneSkipPayloadFull).Count(e => e == toRemoveOne)); Assert.Equal(0, ones.SelectMany(e => e.ThreeSkipPayloadFull).Count(e => e == toRemoveThree)); @@ -3389,11 +3376,10 @@ public virtual void Can_delete_with_many_to_many_with_navs() Assert.DoesNotContain( context.ChangeTracker.Entries(), e => e.Entity.OneId == 1 || e.Entity.ThreeId == 1); - }, - context => + }, async context => { - var ones = context.Set().Include(e => e.ThreeSkipPayloadFull).OrderBy(e => e.Name).ToList(); - var threes = context.Set().Include(e => e.OneSkipPayloadFull).OrderBy(e => e.Name).ToList(); + var ones = await context.Set().Include(e => e.ThreeSkipPayloadFull).OrderBy(e => e.Name).ToListAsync(); + var threes = await context.Set().Include(e => e.OneSkipPayloadFull).OrderBy(e => e.Name).ToListAsync(); ValidateNavigations(ones, threes); @@ -3860,16 +3846,16 @@ void ValidateFixup(DbContext context, IList leftEntities, IList oneIds = null; List twoIds = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var leftEntities = context.Set().Include(e => e.TwoSkip).OrderBy(e => e.Name).ToList(); - var rightEntities = context.Set().Include(e => e.OneSkip).OrderBy(e => e.Name).ToList(); + var leftEntities = await context.Set().Include(e => e.TwoSkip).OrderBy(e => e.Name).ToListAsync(); + var rightEntities = await context.Set().Include(e => e.OneSkip).OrderBy(e => e.Name).ToListAsync(); var twos = new[] { @@ -3954,17 +3940,16 @@ public virtual void Can_update_many_to_many() ValidateFixup(context, leftEntities, rightEntities, 24, 24, 120); - context.SaveChanges(); + await context.SaveChangesAsync(); oneIds = ones.Select(e => e.Id).ToList(); twoIds = twos.Select(e => e.Id).ToList(); ValidateFixup(context, leftEntities, rightEntities, 24, 24, 116); - }, - context => + }, async context => { - var leftEntities = context.Set().Include(e => e.TwoSkip).OrderBy(e => e.Name).ToList(); - var rightEntities = context.Set().Include(e => e.OneSkip).OrderBy(e => e.Name).ToList(); + var leftEntities = await context.Set().Include(e => e.TwoSkip).OrderBy(e => e.Name).ToListAsync(); + var rightEntities = await context.Set().Include(e => e.OneSkip).OrderBy(e => e.Name).ToListAsync(); ValidateFixup(context, leftEntities, rightEntities, 24, 24, 116); }); @@ -4030,27 +4015,27 @@ void ValidateFixup( } [ConditionalFact] - public virtual void Can_delete_with_many_to_many() + public virtual Task Can_delete_with_many_to_many() { var oneId = 0; var twoId = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var ones = context.Set().Include(e => e.TwoSkip).OrderBy(e => e.Name).ToList(); - var twos = context.Set().Include(e => e.OneSkip).OrderBy(e => e.Name).ToList(); + var ones = await context.Set().Include(e => e.TwoSkip).OrderBy(e => e.Name).ToListAsync(); + var twos = await context.Set().Include(e => e.OneSkip).OrderBy(e => e.Name).ToListAsync(); // Make sure other related entities are loaded for delete fixup context.Set().Load(); context.Set().Load(); context.Set().Load(); - var toRemoveOne = context.EntityOnes.Single(e => e.Name == "EntityOne 1"); + var toRemoveOne = await context.EntityOnes.SingleAsync(e => e.Name == "EntityOne 1"); oneId = toRemoveOne.Id; var refCountOnes = twos.SelectMany(e => e.OneSkip).Count(e => e == toRemoveOne); - var toRemoveTwo = context.EntityTwos.Single(e => e.Name == "EntityTwo 1"); + var toRemoveTwo = await context.EntityTwos.SingleAsync(e => e.Name == "EntityTwo 1"); twoId = toRemoveTwo.Id; var refCountTwos = ones.SelectMany(e => e.TwoSkip).Count(e => e == toRemoveTwo); @@ -4075,7 +4060,7 @@ public virtual void Can_delete_with_many_to_many() ? EntityState.Deleted : EntityState.Unchanged, e.State)); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.Equal(1, twos.SelectMany(e => e.OneSkip).Count(e => e == toRemoveOne)); Assert.Equal(1, ones.SelectMany(e => e.TwoSkip).Count(e => e == toRemoveTwo)); @@ -4090,11 +4075,10 @@ public virtual void Can_delete_with_many_to_many() Assert.DoesNotContain( context.ChangeTracker.Entries(), e => e.Entity.OneId == oneId || e.Entity.TwoId == twoId); - }, - context => + }, async context => { - var ones = context.Set().Include(e => e.TwoSkip).OrderBy(e => e.Name).ToList(); - var twos = context.Set().Include(e => e.OneSkip).OrderBy(e => e.Name).ToList(); + var ones = await context.Set().Include(e => e.TwoSkip).OrderBy(e => e.Name).ToListAsync(); + var twos = await context.Set().Include(e => e.OneSkip).OrderBy(e => e.Name).ToListAsync(); ValidateNavigations(ones, twos); Assert.DoesNotContain( @@ -4616,8 +4600,8 @@ public virtual void Can_load_entities_in_any_order(int[] order) } [ConditionalFact] - public virtual void Can_insert_update_delete_shared_type_entity_type() - => ExecuteWithStrategyInTransaction( + public virtual Task Can_insert_update_delete_shared_type_entity_type() + => ExecuteWithStrategyInTransactionAsync( context => { var entity = context.Set>("JoinOneToThreePayloadFullShared").CreateInstance( @@ -4629,12 +4613,11 @@ public virtual void Can_insert_update_delete_shared_type_entity_type() }); context.Set>("JoinOneToThreePayloadFullShared").Add(entity); - context.SaveChanges(); - }, - context => + return context.SaveChangesAsync(); + }, async context => { - var entity = context.Set>("JoinOneToThreePayloadFullShared") - .Single(e => (int)e["OneId"] == 1 && (int)e["ThreeId"] == 1); + var entity = await context.Set>("JoinOneToThreePayloadFullShared") + .SingleAsync(e => (int)e["OneId"] == 1 && (int)e["ThreeId"] == 1); Assert.Equal("NewlyAdded", (string)entity["Payload"]); @@ -4642,31 +4625,30 @@ public virtual void Can_insert_update_delete_shared_type_entity_type() context.Set>("JoinOneToThreePayloadFullShared").Update(entity); - context.SaveChanges(); - }, - context => + await context.SaveChangesAsync(); + }, async context => { - var entity = context.Set>("JoinOneToThreePayloadFullShared") - .Single(e => (int)e["OneId"] == 1 && (int)e["ThreeId"] == 1); + var entity = await context.Set>("JoinOneToThreePayloadFullShared") + .SingleAsync(e => (int)e["OneId"] == 1 && (int)e["ThreeId"] == 1); Assert.Equal("AlreadyUpdated", (string)entity["Payload"]); context.Set>("JoinOneToThreePayloadFullShared").Remove(entity); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False( - context.Set>("JoinOneToThreePayloadFullShared") - .Any(e => (int)e["OneId"] == 1 && (int)e["ThreeId"] == 1)); + await context.Set>("JoinOneToThreePayloadFullShared") + .AnyAsync(e => (int)e["OneId"] == 1 && (int)e["ThreeId"] == 1)); }); [ConditionalFact] - public virtual void Can_insert_update_delete_proxyable_shared_type_entity_type() + public virtual Task Can_insert_update_delete_proxyable_shared_type_entity_type() { var id = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var entity = context.Set("PST").CreateInstance( (e, p) => @@ -4677,13 +4659,12 @@ public virtual void Can_insert_update_delete_proxyable_shared_type_entity_type() context.Set("PST").Add(entity); - context.SaveChanges(); + await context.SaveChangesAsync(); id = (int)entity["Id"]; - }, - context => + }, async context => { - var entity = context.Set("PST").Single(e => (int)e["Id"] == id); + var entity = await context.Set("PST").SingleAsync(e => (int)e["Id"] == id); Assert.Equal("NewlyAdded", (string)entity["Payload"]); @@ -4694,19 +4675,18 @@ public virtual void Can_insert_update_delete_proxyable_shared_type_entity_type() context.ChangeTracker.DetectChanges(); } - context.SaveChanges(); - }, - context => + await context.SaveChangesAsync(); + }, async context => { - var entity = context.Set("PST").Single(e => (int)e["Id"] == id); + var entity = await context.Set("PST").SingleAsync(e => (int)e["Id"] == id); Assert.Equal("AlreadyUpdated", (string)entity["Payload"]); context.Set("PST").Remove(entity); - context.SaveChanges(); + await context.SaveChangesAsync(); - Assert.False(context.Set("PST").Any(e => (int)e["Id"] == id)); + Assert.False(await context.Set("PST").AnyAsync(e => (int)e["Id"] == id)); }); } @@ -4871,16 +4851,16 @@ static void ValidateFixup(DbContext context, IList leftEntities, ILis [InlineData(false, true, true, true)] [InlineData(true, false, true, true)] [InlineData(true, true, true, true)] - public virtual void Can_add_and_remove_a_new_relationship(bool modifyLeft, bool modifyRight, bool useJoin, bool useNavs) + public virtual Task Can_add_and_remove_a_new_relationship(bool modifyLeft, bool modifyRight, bool useJoin, bool useNavs) { var leftId = -1; var rightId = -1; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var left = context.Set().Where(e => !e.TwoSkip.Any()).OrderBy(e => e.Id).First(); - var right = context.Set().OrderBy(e => e.Id).First(); + var left = await context.Set().Where(e => !e.TwoSkip.Any()).OrderBy(e => e.Id).FirstAsync(); + var right = await context.Set().OrderBy(e => e.Id).FirstAsync(); if (modifyLeft) { @@ -4960,12 +4940,11 @@ public virtual void Can_add_and_remove_a_new_relationship(bool modifyLeft, bool Assert.Same(left, joinEntry.Entity.One); Assert.Same(right, joinEntry.Entity.Two); - context.SaveChanges(); - }, - context => + await context.SaveChangesAsync(); + }, async context => { - var left = context.Set().Where(e => !e.TwoSkip.Any()).OrderBy(e => e.Id).First(); - var right = context.Set().OrderBy(e => e.Id).First(); + var left = await context.Set().Where(e => !e.TwoSkip.Any()).OrderBy(e => e.Id).FirstAsync(); + var right = await context.Set().OrderBy(e => e.Id).FirstAsync(); Assert.Equal(leftId, left.Id); Assert.Equal(rightId, right.Id); @@ -4981,16 +4960,16 @@ public virtual void Can_add_and_remove_a_new_relationship(bool modifyLeft, bool [InlineData(false, true, true)] [InlineData(true, false, true)] [InlineData(true, true, true)] - public virtual void Can_add_and_remove_a_new_relationship_self(bool modifyLeft, bool modifyRight, bool useJoin) + public virtual Task Can_add_and_remove_a_new_relationship_self(bool modifyLeft, bool modifyRight, bool useJoin) { var leftId = -1; var rightId = -1; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var left = context.Set().Where(e => !e.SelfSkipSharedRight.Any()).OrderBy(e => e.Id).First(); - var right = context.Set().Where(e => !e.SelfSkipSharedLeft.Any()).OrderBy(e => e.Id).First(); + var left = await context.Set().Where(e => !e.SelfSkipSharedRight.Any()).OrderBy(e => e.Id).FirstAsync(); + var right = await context.Set().Where(e => !e.SelfSkipSharedLeft.Any()).OrderBy(e => e.Id).FirstAsync(); if (modifyLeft) { @@ -5050,12 +5029,11 @@ public virtual void Can_add_and_remove_a_new_relationship_self(bool modifyLeft, Assert.Equal(left.Id, joinEntry.Entity["SelfSkipSharedLeftId"]); Assert.Equal(right.Id, joinEntry.Entity["SelfSkipSharedRightId"]); - context.SaveChanges(); - }, - context => + await context.SaveChangesAsync(); + }, async context => { - var left = context.Set().Where(e => !e.SelfSkipSharedRight.Any()).OrderBy(e => e.Id).First(); - var right = context.Set().Where(e => !e.SelfSkipSharedLeft.Any()).OrderBy(e => e.Id).First(); + var left = await context.Set().Where(e => !e.SelfSkipSharedRight.Any()).OrderBy(e => e.Id).FirstAsync(); + var right = await context.Set().Where(e => !e.SelfSkipSharedLeft.Any()).OrderBy(e => e.Id).FirstAsync(); Assert.Equal(leftId, left.Id); Assert.Equal(rightId, right.Id); @@ -5075,7 +5053,7 @@ public virtual void Can_add_and_remove_a_new_relationship_self(bool modifyLeft, [InlineData(false, true, true, true)] [InlineData(true, false, true, true)] [InlineData(true, true, true, true)] - public virtual void Can_add_and_remove_a_new_relationship_composite_with_navs( + public virtual Task Can_add_and_remove_a_new_relationship_composite_with_navs( bool modifyLeft, bool modifyRight, bool useJoin, @@ -5086,17 +5064,17 @@ public virtual void Can_add_and_remove_a_new_relationship_composite_with_navs( var leftKey3 = new DateTime(); var rightId = -1; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var left = context.Set() + var left = await context.Set() .Where(e => !e.LeafSkipFull.Any()) .OrderBy(e => e.Key1) .ThenBy(e => e.Key2) .ThenBy(e => e.Key3) - .First(); + .FirstAsync(); - var right = context.Set().OrderBy(e => e.Id).First(); + var right = await context.Set().OrderBy(e => e.Id).FirstAsync(); if (modifyLeft) { @@ -5194,18 +5172,17 @@ public virtual void Can_add_and_remove_a_new_relationship_composite_with_navs( Assert.DoesNotContain(joinEntry.Entity, left.JoinLeafFull); Assert.DoesNotContain(joinEntry.Entity, right.JoinCompositeKeyFull); - context.SaveChanges(); - }, - context => + await context.SaveChangesAsync(); + }, async context => { - var left = context.Set() + var left = await context.Set() .Where(e => !e.LeafSkipFull.Any()) .OrderBy(e => e.Key1) .ThenBy(e => e.Key2) .ThenBy(e => e.Key3) - .First(); + .FirstAsync(); - var right = context.Set().OrderBy(e => e.Id).First(); + var right = await context.Set().OrderBy(e => e.Id).FirstAsync(); Assert.Equal(leftKey1, left.Key1); Assert.Equal(leftKey2, left.Key2); @@ -5227,7 +5204,7 @@ public virtual void Can_add_and_remove_a_new_relationship_composite_with_navs( [InlineData(false, true, true, true)] [InlineData(true, false, true, true)] [InlineData(true, true, true, true)] - public virtual void Can_add_and_remove_a_new_relationship_composite_additional_pk_with_navs( + public virtual Task Can_add_and_remove_a_new_relationship_composite_additional_pk_with_navs( bool modifyLeft, bool modifyRight, bool useJoin, @@ -5238,17 +5215,17 @@ public virtual void Can_add_and_remove_a_new_relationship_composite_additional_p var leftKey3 = new DateTime(); var rightId = -1; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var left = context.Set() + var left = await context.Set() .Where(e => !e.ThreeSkipFull.Any()) .OrderBy(e => e.Key1) .ThenBy(e => e.Key2) .ThenBy(e => e.Key3) - .First(); + .FirstAsync(); - var right = context.Set().OrderBy(e => e.Id).First(); + var right = await context.Set().OrderBy(e => e.Id).FirstAsync(); if (modifyLeft) { @@ -5346,18 +5323,17 @@ public virtual void Can_add_and_remove_a_new_relationship_composite_additional_p Assert.DoesNotContain(joinEntry.Entity, left.JoinThreeFull); Assert.DoesNotContain(joinEntry.Entity, right.JoinCompositeKeyFull); - context.SaveChanges(); - }, - context => + await context.SaveChangesAsync(); + }, async context => { - var left = context.Set() + var left = await context.Set() .Where(e => !e.ThreeSkipFull.Any()) .OrderBy(e => e.Key1) .ThenBy(e => e.Key2) .ThenBy(e => e.Key3) - .First(); + .FirstAsync(); - var right = context.Set().OrderBy(e => e.Id).First(); + var right = await context.Set().OrderBy(e => e.Id).FirstAsync(); Assert.Equal(leftKey1, left.Key1); Assert.Equal(leftKey2, left.Key2); @@ -5375,16 +5351,16 @@ public virtual void Can_add_and_remove_a_new_relationship_composite_additional_p [InlineData(false, true, true)] [InlineData(true, false, true)] [InlineData(true, true, true)] - public virtual void Can_add_and_remove_a_new_relationship_with_inheritance(bool modifyLeft, bool modifyRight, bool useJoin) + public virtual Task Can_add_and_remove_a_new_relationship_with_inheritance(bool modifyLeft, bool modifyRight, bool useJoin) { var leftId = -1; var rightId = -1; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var left = context.Set().Where(e => !e.BranchSkip.Any()).OrderBy(e => e.Id).First(); - var right = context.Set().OrderBy(e => e.Id).First(); + var left = await context.Set().Where(e => !e.BranchSkip.Any()).OrderBy(e => e.Id).FirstAsync(); + var right = await context.Set().OrderBy(e => e.Id).FirstAsync(); if (modifyLeft) { @@ -5451,12 +5427,11 @@ public virtual void Can_add_and_remove_a_new_relationship_with_inheritance(bool Assert.Equal(leftId, joinEntry.Entity.EntityOneId); Assert.Equal(rightId, joinEntry.Entity.EntityBranchId); - context.SaveChanges(); - }, - context => + await context.SaveChangesAsync(); + }, async context => { - var left = context.Set().Where(e => !e.BranchSkip.Any()).OrderBy(e => e.Id).First(); - var right = context.Set().OrderBy(e => e.Id).First(); + var left = await context.Set().Where(e => !e.BranchSkip.Any()).OrderBy(e => e.Id).FirstAsync(); + var right = await context.Set().OrderBy(e => e.Id).FirstAsync(); Assert.Equal(leftId, left.Id); Assert.Equal(rightId, right.Id); @@ -5472,16 +5447,16 @@ public virtual void Can_add_and_remove_a_new_relationship_with_inheritance(bool [InlineData(false, true, true)] [InlineData(true, false, true)] [InlineData(true, true, true)] - public virtual void Can_add_and_remove_a_new_relationship_shared_with_payload(bool modifyLeft, bool modifyRight, bool useJoin) + public virtual Task Can_add_and_remove_a_new_relationship_shared_with_payload(bool modifyLeft, bool modifyRight, bool useJoin) { var leftId = -1; var rightId = -1; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var left = context.Set().Where(e => !e.ThreeSkipPayloadFullShared.Any()).OrderBy(e => e.Id).First(); - var right = context.Set().OrderBy(e => e.Id).First(); + var left = await context.Set().Where(e => !e.ThreeSkipPayloadFullShared.Any()).OrderBy(e => e.Id).FirstAsync(); + var right = await context.Set().OrderBy(e => e.Id).FirstAsync(); if (modifyLeft) { @@ -5545,12 +5520,11 @@ public virtual void Can_add_and_remove_a_new_relationship_shared_with_payload(bo Assert.Equal(EntityState.Detached, joinEntry.State); - context.SaveChanges(); - }, - context => + await context.SaveChangesAsync(); + }, async context => { - var left = context.Set().Where(e => !e.ThreeSkipPayloadFullShared.Any()).OrderBy(e => e.Id).First(); - var right = context.Set().OrderBy(e => e.Id).First(); + var left = await context.Set().Where(e => !e.ThreeSkipPayloadFullShared.Any()).OrderBy(e => e.Id).FirstAsync(); + var right = await context.Set().OrderBy(e => e.Id).FirstAsync(); Assert.Equal(leftId, left.Id); Assert.Equal(rightId, right.Id); @@ -5566,16 +5540,16 @@ public virtual void Can_add_and_remove_a_new_relationship_shared_with_payload(bo [InlineData(false, true, true)] [InlineData(true, false, true)] [InlineData(true, true, true)] - public virtual void Can_add_and_remove_a_new_relationship_shared(bool modifyLeft, bool modifyRight, bool useJoin) + public virtual Task Can_add_and_remove_a_new_relationship_shared(bool modifyLeft, bool modifyRight, bool useJoin) { var leftId = -1; var rightId = -1; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var left = context.Set().Where(e => !e.TwoSkipShared.Any()).OrderBy(e => e.Id).First(); - var right = context.Set().OrderBy(e => e.Id).First(); + var left = await context.Set().Where(e => !e.TwoSkipShared.Any()).OrderBy(e => e.Id).FirstAsync(); + var right = await context.Set().OrderBy(e => e.Id).FirstAsync(); if (modifyLeft) { @@ -5635,12 +5609,11 @@ public virtual void Can_add_and_remove_a_new_relationship_shared(bool modifyLeft Assert.Equal(left.Id, (int)joinEntry.Entity["OneSkipSharedId"]); Assert.Equal(right.Id, (int)joinEntry.Entity["TwoSkipSharedId"]); - context.SaveChanges(); - }, - context => + await context.SaveChangesAsync(); + }, async context => { - var left = context.Set().Where(e => !e.TwoSkipShared.Any()).OrderBy(e => e.Id).First(); - var right = context.Set().OrderBy(e => e.Id).First(); + var left = await context.Set().Where(e => !e.TwoSkipShared.Any()).OrderBy(e => e.Id).FirstAsync(); + var right = await context.Set().OrderBy(e => e.Id).FirstAsync(); Assert.Equal(leftId, left.Id); Assert.Equal(rightId, right.Id); @@ -5660,7 +5633,7 @@ public virtual void Can_add_and_remove_a_new_relationship_shared(bool modifyLeft [InlineData(false, true, true, true)] [InlineData(true, false, true, true)] [InlineData(true, true, true, true)] - public virtual void Can_add_and_remove_a_new_relationship_with_payload( + public virtual Task Can_add_and_remove_a_new_relationship_with_payload( bool modifyLeft, bool modifyRight, bool useJoin, @@ -5669,11 +5642,11 @@ public virtual void Can_add_and_remove_a_new_relationship_with_payload( var leftId = -1; var rightId = -1; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var left = context.Set().Where(e => !e.ThreeSkipPayloadFull.Any()).OrderBy(e => e.Id).First(); - var right = context.Set().OrderBy(e => e.Id).First(); + var left = await context.Set().Where(e => !e.ThreeSkipPayloadFull.Any()).OrderBy(e => e.Id).FirstAsync(); + var right = await context.Set().OrderBy(e => e.Id).FirstAsync(); if (modifyLeft) { @@ -5757,12 +5730,11 @@ public virtual void Can_add_and_remove_a_new_relationship_with_payload( Assert.DoesNotContain(joinEntry.Entity, left.JoinThreePayloadFull); Assert.DoesNotContain(joinEntry.Entity, right.JoinOnePayloadFull); - context.SaveChanges(); - }, - context => + await context.SaveChangesAsync(); + }, async context => { - var left = context.Set().Where(e => !e.ThreeSkipPayloadFull.Any()).OrderBy(e => e.Id).First(); - var right = context.Set().OrderBy(e => e.Id).First(); + var left = await context.Set().Where(e => !e.ThreeSkipPayloadFull.Any()).OrderBy(e => e.Id).FirstAsync(); + var right = await context.Set().OrderBy(e => e.Id).FirstAsync(); Assert.Equal(leftId, left.Id); Assert.Equal(rightId, right.Id); @@ -5957,15 +5929,6 @@ protected ManyToManyTrackingTestBase(TFixture fixture) protected TFixture Fixture { get; } - protected virtual void ExecuteWithStrategyInTransaction( - Action testOperation, - Action nestedTestOperation1 = null, - Action nestedTestOperation2 = null, - Action nestedTestOperation3 = null) - => TestHelpers.ExecuteWithStrategyInTransaction( - CreateContext, UseTransaction, - testOperation, nestedTestOperation1, nestedTestOperation2, nestedTestOperation3); - protected virtual Task ExecuteWithStrategyInTransactionAsync( Func testOperation, Func nestedTestOperation1 = null, diff --git a/test/EFCore.Specification.Tests/MaterializationInterceptionTestBase.cs b/test/EFCore.Specification.Tests/MaterializationInterceptionTestBase.cs index 00c4aeda3d9..d40ab02d102 100644 --- a/test/EFCore.Specification.Tests/MaterializationInterceptionTestBase.cs +++ b/test/EFCore.Specification.Tests/MaterializationInterceptionTestBase.cs @@ -11,7 +11,7 @@ protected override string StoreName [ConditionalTheory] [ClassData(typeof(DataGenerator))] - public virtual void Binding_interceptors_are_used_by_queries(bool inject, bool usePooling) + public virtual async Task Binding_interceptors_are_used_by_queries(bool inject, bool usePooling) { var interceptors = new[] { @@ -21,23 +21,23 @@ public virtual void Binding_interceptors_are_used_by_queries(bool inject, bool u new TestBindingInterceptor("4") }; - using var context = CreateContext(interceptors, inject, usePooling); + using var context = await CreateContext(interceptors, inject, usePooling); context.AddRange( new Book { Title = "Amiga ROM Kernel Reference Manual" }, new Book { Title = "Amiga Hardware Reference Manual" }); - context.SaveChanges(); + await context.SaveChangesAsync(); context.ChangeTracker.Clear(); - var results = context.Set().ToList(); + var results = await context.Set().ToListAsync(); Assert.All(results, e => Assert.Equal("4", e.MaterializedBy)); Assert.All(interceptors, i => Assert.Equal(1, i.CalledCount)); } [ConditionalTheory] [ClassData(typeof(DataGenerator))] - public virtual void Binding_interceptors_are_used_when_creating_instances(bool inject, bool usePooling) + public virtual async Task Binding_interceptors_are_used_when_creating_instances(bool inject, bool usePooling) { var interceptors = new[] { @@ -47,7 +47,7 @@ public virtual void Binding_interceptors_are_used_when_creating_instances(bool i new TestBindingInterceptor("4") }; - using var context = CreateContext(interceptors, inject, usePooling); + using var context = await CreateContext(interceptors, inject, usePooling); var materializer = context.GetService(); var book = (Book)materializer.GetEmptyMaterializer(context.Model.FindEntityType(typeof(Book))!)( @@ -59,7 +59,7 @@ public virtual void Binding_interceptors_are_used_when_creating_instances(bool i [ConditionalTheory] [ClassData(typeof(DataGenerator))] - public virtual void Intercept_query_materialization_for_empty_constructor(bool inject, bool usePooling) + public virtual async Task Intercept_query_materialization_for_empty_constructor(bool inject, bool usePooling) { var creatingInstanceCount = 0; var createdInstanceCount = 0; @@ -128,7 +128,7 @@ public virtual void Intercept_query_materialization_for_empty_constructor(bool i }) }; - using (context = CreateContext(interceptors, inject, usePooling)) + using (context = await CreateContext(interceptors, inject, usePooling)) { var books = new[] { @@ -140,10 +140,10 @@ public virtual void Intercept_query_materialization_for_empty_constructor(bool i context.Entry(books[0]).Property("Author").CurrentValue = "Commodore Business Machines Inc."; context.Entry(books[1]).Property("Author").CurrentValue = "Agnes"; - context.SaveChanges(); + await context.SaveChangesAsync(); context.ChangeTracker.Clear(); - var results = context.Set().Where(e => books.Select(e => e.Id).Contains(e.Id)).ToList(); + var results = await context.Set().Where(e => books.Select(e => e.Id).Contains(e.Id)).ToListAsync(); Assert.Equal(2, results.Count); Assert.Equal(2, creatingInstanceCount); @@ -211,7 +211,7 @@ public virtual async Task Intercept_query_materialization_with_owned_types(bool }) }; - using (context = CreateContext(interceptors, inject: true, usePooling)) + using (context = await CreateContext(interceptors, inject: true, usePooling)) { context.Add( new TestEntity30244 @@ -299,7 +299,7 @@ public virtual async Task Intercept_query_materialization_with_owned_types_proje }) }; - using (context = CreateContext(interceptors, inject: true, usePooling)) + using (context = await CreateContext(interceptors, inject: true, usePooling)) { context.Add( new TestEntity30244 @@ -345,7 +345,7 @@ public virtual async Task Intercept_query_materialization_with_owned_types_proje [ConditionalTheory] [ClassData(typeof(DataGenerator))] - public virtual void Intercept_query_materialization_for_full_constructor(bool inject, bool usePooling) + public virtual async Task Intercept_query_materialization_for_full_constructor(bool inject, bool usePooling) { var creatingInstanceCount = 0; var createdInstanceCount = 0; @@ -414,7 +414,7 @@ public virtual void Intercept_query_materialization_for_full_constructor(bool in }) }; - using (context = CreateContext(interceptors, inject, usePooling)) + using (context = await CreateContext(interceptors, inject, usePooling)) { var pamphlets = new[] { new Pamphlet(Guid.Empty, "Rights of Man"), new Pamphlet(Guid.Empty, "Pamphlet des pamphlets") }; @@ -423,10 +423,10 @@ public virtual void Intercept_query_materialization_for_full_constructor(bool in context.Entry(pamphlets[0]).Property("Author").CurrentValue = "Thomas Paine"; context.Entry(pamphlets[1]).Property("Author").CurrentValue = "Paul-Louis Courier"; - context.SaveChanges(); + await context.SaveChangesAsync(); context.ChangeTracker.Clear(); - var results = context.Set().Where(e => pamphlets.Select(e => e.Id).Contains(e.Id)).ToList(); + var results = await context.Set().Where(e => pamphlets.Select(e => e.Id).Contains(e.Id)).ToListAsync(); Assert.Equal(2, results.Count); Assert.Equal(2, creatingInstanceCount); @@ -448,7 +448,7 @@ public virtual void Intercept_query_materialization_for_full_constructor(bool in [ConditionalTheory] [ClassData(typeof(DataGenerator))] - public virtual void Multiple_materialization_interceptors_can_be_used(bool inject, bool usePooling) + public virtual async Task Multiple_materialization_interceptors_can_be_used(bool inject, bool usePooling) { var interceptors = new ISingletonInterceptor[] { @@ -461,16 +461,16 @@ public virtual void Multiple_materialization_interceptors_can_be_used(bool injec new CountingMaterializationInterceptor("C") }; - using var context = CreateContext(interceptors, inject, usePooling); + using var context = await CreateContext(interceptors, inject, usePooling); context.AddRange( new Book { Title = "Amiga ROM Kernel Reference Manual" }, new Book { Title = "Amiga Hardware Reference Manual" }); - context.SaveChanges(); + await context.SaveChangesAsync(); context.ChangeTracker.Clear(); - var results = context.Set().ToList(); + var results = await context.Set().ToListAsync(); Assert.All(results, e => Assert.Equal("4", e.MaterializedBy)); Assert.All(interceptors.OfType(), i => Assert.Equal(1, i.CalledCount)); diff --git a/test/EFCore.Specification.Tests/MonsterFixupTestBase.cs b/test/EFCore.Specification.Tests/MonsterFixupTestBase.cs index 3beab647ee9..91244c56db7 100644 --- a/test/EFCore.Specification.Tests/MonsterFixupTestBase.cs +++ b/test/EFCore.Specification.Tests/MonsterFixupTestBase.cs @@ -25,9 +25,9 @@ protected MonsterFixupTestBase(TFixture fixture) protected DbContextOptions Options { get; } [ConditionalFact] - public virtual void Can_build_monster_model_and_seed_data_using_FKs() + public virtual async Task Can_build_monster_model_and_seed_data_using_FKs() { - CreateAndSeedDatabase(context => context.SeedUsingFKs()); + await CreateAndSeedDatabase(async context => await context.SeedUsingFKs()); SimpleVerification(); FkVerification(); @@ -35,9 +35,9 @@ public virtual void Can_build_monster_model_and_seed_data_using_FKs() } [ConditionalFact] - public virtual void Can_build_monster_model_and_seed_data_using_all_navigations() + public virtual async Task Can_build_monster_model_and_seed_data_using_all_navigations() { - CreateAndSeedDatabase(context => context.SeedUsingNavigations(dependentNavs: true, principalNavs: true)); + await CreateAndSeedDatabase(async context => await context.SeedUsingNavigations(dependentNavs: true, principalNavs: true)); SimpleVerification(); FkVerification(); @@ -45,9 +45,9 @@ public virtual void Can_build_monster_model_and_seed_data_using_all_navigations( } [ConditionalFact] - public virtual void Can_build_monster_model_and_seed_data_using_dependent_navigations() + public async Task Can_build_monster_model_and_seed_data_using_dependent_navigations() { - CreateAndSeedDatabase(context => context.SeedUsingNavigations(dependentNavs: true, principalNavs: false)); + await CreateAndSeedDatabase(async context => await context.SeedUsingNavigations(dependentNavs: true, principalNavs: false)); SimpleVerification(); FkVerification(); @@ -55,9 +55,9 @@ public virtual void Can_build_monster_model_and_seed_data_using_dependent_naviga } [ConditionalFact] - public virtual void Can_build_monster_model_and_seed_data_using_principal_navigations() + public async Task Can_build_monster_model_and_seed_data_using_principal_navigations() { - CreateAndSeedDatabase(context => context.SeedUsingNavigations(dependentNavs: false, principalNavs: true)); + await CreateAndSeedDatabase(async context => await context.SeedUsingNavigations(dependentNavs: false, principalNavs: true)); SimpleVerification(); FkVerification(); @@ -65,9 +65,9 @@ public virtual void Can_build_monster_model_and_seed_data_using_principal_naviga } [ConditionalFact] - public virtual void Can_build_monster_model_and_seed_data_using_navigations_with_deferred_add() + public async Task Can_build_monster_model_and_seed_data_using_navigations_with_deferred_add() { - CreateAndSeedDatabase(context => context.SeedUsingNavigationsWithDeferredAdd()); + await CreateAndSeedDatabase(async context => await context.SeedUsingNavigationsWithDeferredAdd()); SimpleVerification(); FkVerification(); @@ -75,9 +75,9 @@ public virtual void Can_build_monster_model_and_seed_data_using_navigations_with } [ConditionalFact] - public virtual void One_to_many_fixup_happens_when_FKs_change_test() + public async Task One_to_many_fixup_happens_when_FKs_change_test() { - CreateAndSeedDatabase(context => context.SeedUsingFKs()); + await CreateAndSeedDatabase(async context => await context.SeedUsingFKs()); using (var context = CreateContext()) { @@ -165,9 +165,9 @@ public virtual void One_to_many_fixup_happens_when_FKs_change_test() } [ConditionalFact] - public virtual void One_to_many_fixup_happens_when_reference_changes() + public async Task One_to_many_fixup_happens_when_reference_changes() { - CreateAndSeedDatabase(context => context.SeedUsingFKs()); + await CreateAndSeedDatabase(async context => await context.SeedUsingFKs()); using (var context = CreateContext()) { @@ -255,9 +255,9 @@ public virtual void One_to_many_fixup_happens_when_reference_changes() } [ConditionalFact] - public virtual void One_to_many_fixup_happens_when_collection_changes() + public async Task One_to_many_fixup_happens_when_collection_changes() { - CreateAndSeedDatabase(context => context.SeedUsingFKs()); + await CreateAndSeedDatabase(async context => await context.SeedUsingFKs()); using (var context = CreateContext()) { @@ -334,9 +334,9 @@ public virtual void One_to_many_fixup_happens_when_collection_changes() } [ConditionalFact] - public virtual void One_to_one_fixup_happens_when_FKs_change_test() + public async Task One_to_one_fixup_happens_when_FKs_change_test() { - CreateAndSeedDatabase(context => context.SeedUsingFKs()); + await CreateAndSeedDatabase(async context => await context.SeedUsingFKs()); using (var context = CreateContext()) { @@ -418,9 +418,9 @@ public virtual void One_to_one_fixup_happens_when_FKs_change_test() } [ConditionalFact] - public virtual void One_to_one_fixup_happens_when_reference_change_test() + public async Task One_to_one_fixup_happens_when_reference_change_test() { - CreateAndSeedDatabase(context => context.SeedUsingFKs()); + await CreateAndSeedDatabase(async context => await context.SeedUsingFKs()); using (var context = CreateContext()) { @@ -502,9 +502,9 @@ public virtual void One_to_one_fixup_happens_when_reference_change_test() } [ConditionalFact] - public virtual void Composite_fixup_happens_when_FKs_change_test() + public async Task Composite_fixup_happens_when_FKs_change_test() { - CreateAndSeedDatabase(context => context.SeedUsingFKs()); + await CreateAndSeedDatabase(async context => await context.SeedUsingFKs()); using (var context = CreateContext()) { @@ -605,9 +605,9 @@ public virtual void Composite_fixup_happens_when_FKs_change_test() } [ConditionalFact] - public virtual void Fixup_with_binary_keys_happens_when_FKs_or_navigations_change_test() + public async Task Fixup_with_binary_keys_happens_when_FKs_or_navigations_change_test() { - CreateAndSeedDatabase(context => context.SeedUsingFKs()); + await CreateAndSeedDatabase(async context => await context.SeedUsingFKs()); using (var context = CreateContext()) { @@ -1399,8 +1399,8 @@ protected void NavigationVerification() protected bool UseDetectChanges => Fixture.UseDetectChanges; - protected void CreateAndSeedDatabase(Action seed) - => TestStore.Initialize(Fixture.ServiceProvider, CreateContext, c => seed((MonsterContext)c)); + protected Task CreateAndSeedDatabase(Func seed) + => TestStore.InitializeAsync(Fixture.ServiceProvider, CreateContext, c => seed((MonsterContext)c)); protected MonsterContext CreateContext() => Fixture.CreateContext(Options); diff --git a/test/EFCore.Specification.Tests/NonSharedModelTestBase.cs b/test/EFCore.Specification.Tests/NonSharedModelTestBase.cs index 7e32ad8c683..ff738874eb2 100644 --- a/test/EFCore.Specification.Tests/NonSharedModelTestBase.cs +++ b/test/EFCore.Specification.Tests/NonSharedModelTestBase.cs @@ -4,7 +4,7 @@ // ReSharper disable VirtualMemberCallInConstructor namespace Microsoft.EntityFrameworkCore; -public abstract class NonSharedModelTestBase : IDisposable, IAsyncLifetime +public abstract class NonSharedModelTestBase : IAsyncLifetime { public static IEnumerable IsAsyncData = [[false], [true]]; @@ -33,68 +33,49 @@ protected ListLoggerFactory ListLoggerFactory public virtual Task InitializeAsync() => Task.CompletedTask; - protected virtual ContextFactory Initialize( + protected virtual async Task> InitializeAsync( Action? onModelCreating = null, Action? onConfiguring = null, Func? addServices = null, Action? configureConventions = null, - Action? seed = null, + Func? seed = null, Func? shouldLogCategory = null, - Func? createTestStore = null, + Func>? createTestStore = null, bool usePooling = true, bool useServiceProvider = true) where TContext : DbContext { - var contextFactory = CreateContextFactory( - onModelCreating, onConfiguring, addServices, configureConventions, shouldLogCategory, createTestStore, usePooling, useServiceProvider); + var contextFactory = await CreateContextFactory( + onModelCreating, onConfiguring, addServices, configureConventions, shouldLogCategory, createTestStore, usePooling, + useServiceProvider); - TestStore.Initialize(_serviceProvider, contextFactory.CreateContext, seed == null ? null : c => seed((TContext)c)); + await TestStore.InitializeAsync(_serviceProvider, contextFactory.CreateContext, seed == null ? null : c => seed((TContext)c)); ListLoggerFactory.Clear(); return contextFactory; } - protected virtual Task> InitializeAsync( + protected async Task> CreateContextFactory( Action? onModelCreating = null, Action? onConfiguring = null, Func? addServices = null, Action? configureConventions = null, - Action? seed = null, Func? shouldLogCategory = null, - Func? createTestStore = null, + Func>? createTestStore = null, bool usePooling = true, bool useServiceProvider = true) where TContext : DbContext { - var contextFactory = CreateContextFactory( - onModelCreating, onConfiguring, addServices, configureConventions, shouldLogCategory, createTestStore, usePooling, useServiceProvider); - - TestStore.Initialize(_serviceProvider, contextFactory.CreateContext, seed == null ? null : c => seed((TContext)c)); - - ListLoggerFactory.Clear(); - - return Task.FromResult(contextFactory); - } - - protected ContextFactory CreateContextFactory( - Action? onModelCreating = null, - Action? onConfiguring = null, - Func? addServices = null, - Action? configureConventions = null, - Func? shouldLogCategory = null, - Func? createTestStore = null, - bool usePooling = true, - bool useServiceProvider = true) - where TContext : DbContext - { - _testStore = createTestStore?.Invoke() ?? CreateTestStore(); + _testStore = createTestStore != null + ? await createTestStore() + : CreateTestStore(); shouldLogCategory ??= _ => false; var services = (useServiceProvider - ? TestStoreFactory.AddProviderServices(new ServiceCollection()) - : new ServiceCollection()) - .AddSingleton(TestStoreFactory.CreateListLoggerFactory(shouldLogCategory)); + ? TestStoreFactory.AddProviderServices(new ServiceCollection()) + : new ServiceCollection()) + .AddSingleton(TestStoreFactory.CreateListLoggerFactory(shouldLogCategory)); if (onModelCreating != null) { @@ -104,7 +85,8 @@ protected ContextFactory CreateContextFactory( addServices?.Invoke(services); services = usePooling - ? services.AddPooledDbContextFactory(typeof(TContext), (s, b) => ConfigureOptions(useServiceProvider ? s : null, b, onConfiguring)) + ? services.AddPooledDbContextFactory( + typeof(TContext), (s, b) => ConfigureOptions(useServiceProvider ? s : null, b, onConfiguring)) : services.AddDbContext( typeof(TContext), (s, b) => ConfigureOptions(useServiceProvider ? s : null, b, onConfiguring), diff --git a/test/EFCore.Specification.Tests/NotificationEntitiesTestBase.cs b/test/EFCore.Specification.Tests/NotificationEntitiesTestBase.cs index 3020c626672..af909edf4de 100644 --- a/test/EFCore.Specification.Tests/NotificationEntitiesTestBase.cs +++ b/test/EFCore.Specification.Tests/NotificationEntitiesTestBase.cs @@ -121,12 +121,12 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con modelBuilder.Entity().Property(e => e.Id).ValueGeneratedNever(); } - protected override void Seed(PoolableDbContext context) + protected override Task SeedAsync(PoolableDbContext context) { context.Add( new Blog { Id = 1, Posts = new List { new() { Id = 1 }, new() { Id = 2 } } }); - context.SaveChanges(); + return context.SaveChangesAsync(); } } } diff --git a/test/EFCore.Specification.Tests/OptimisticConcurrencyTestBase.cs b/test/EFCore.Specification.Tests/OptimisticConcurrencyTestBase.cs index ea148ff41c1..bf4c276d798 100644 --- a/test/EFCore.Specification.Tests/OptimisticConcurrencyTestBase.cs +++ b/test/EFCore.Specification.Tests/OptimisticConcurrencyTestBase.cs @@ -68,20 +68,20 @@ public virtual void Nullable_client_side_concurrency_token_can_be_used() [ConditionalFact] public virtual Task Simple_concurrency_exception_can_be_resolved_with_client_values() => ConcurrencyTestAsync( - ClientPodiums, (c, ex) => + ClientPodiums, async (_, ex) => { var driverEntry = ex.Entries.Single(); - driverEntry.OriginalValues.SetValues(driverEntry.GetDatabaseValues()); + driverEntry.OriginalValues.SetValues(await driverEntry.GetDatabaseValuesAsync()); ResolveConcurrencyTokens(driverEntry); }); [ConditionalFact] public virtual Task Simple_concurrency_exception_can_be_resolved_with_store_values() => ConcurrencyTestAsync( - StorePodiums, (c, ex) => + StorePodiums, async (_, ex) => { var driverEntry = ex.Entries.Single(); - var storeValues = driverEntry.GetDatabaseValues(); + var storeValues = await driverEntry.GetDatabaseValuesAsync(); driverEntry.CurrentValues.SetValues(storeValues); driverEntry.OriginalValues.SetValues(storeValues); ResolveConcurrencyTokens(driverEntry); @@ -90,10 +90,10 @@ public virtual Task Simple_concurrency_exception_can_be_resolved_with_store_valu [ConditionalFact] public virtual Task Simple_concurrency_exception_can_be_resolved_with_new_values() => ConcurrencyTestAsync( - 10, (c, ex) => + 10, async (_, ex) => { var driverEntry = ex.Entries.Single(); - driverEntry.OriginalValues.SetValues(driverEntry.GetDatabaseValues()); + driverEntry.OriginalValues.SetValues(await driverEntry.GetDatabaseValuesAsync()); ResolveConcurrencyTokens(driverEntry); ((Driver)driverEntry.Entity).Podiums = 10; }); @@ -101,10 +101,10 @@ public virtual Task Simple_concurrency_exception_can_be_resolved_with_new_values [ConditionalFact] public virtual Task Simple_concurrency_exception_can_be_resolved_with_store_values_using_equivalent_of_accept_changes() => ConcurrencyTestAsync( - StorePodiums, (c, ex) => + StorePodiums, async (_, ex) => { var driverEntry = ex.Entries.Single(); - var storeValues = driverEntry.GetDatabaseValues(); + var storeValues = await driverEntry.GetDatabaseValuesAsync(); driverEntry.CurrentValues.SetValues(storeValues); driverEntry.OriginalValues.SetValues(storeValues); driverEntry.State = EntityState.Unchanged; @@ -112,34 +112,34 @@ public virtual Task Simple_concurrency_exception_can_be_resolved_with_store_valu [ConditionalFact] public virtual Task Simple_concurrency_exception_can_be_resolved_with_store_values_using_Reload() - => ConcurrencyTestAsync(StorePodiums, (c, ex) => ex.Entries.Single().Reload()); + => ConcurrencyTestAsync(StorePodiums, (_, ex) => ex.Entries.Single().ReloadAsync()); [ConditionalFact] public virtual Task Two_concurrency_issues_in_one_to_one_related_entities_can_be_handled_by_dealing_with_dependent_first() => ConcurrencyTestAsync( - c => + async c => { - var chassis = c.Set().Single(c => c.Name == "MP4-25"); - var team = c.Teams.Single(t => t.Id == Team.McLaren); + var chassis = await c.Set().SingleAsync(c => c.Name == "MP4-25"); + var team = await c.Teams.SingleAsync(t => t.Id == Team.McLaren); chassis.Name = "MP4-25b"; team.Principal = "Larry David"; }, - c => + async c => { - var chassis = c.Set().Single(c => c.Name == "MP4-25"); - var team = c.Teams.Single(t => t.Id == Team.McLaren); + var chassis = await c.Set().SingleAsync(c => c.Name == "MP4-25"); + var team = await c.Teams.SingleAsync(t => t.Id == Team.McLaren); chassis.Name = "MP4-25c"; team.Principal = "Jerry Seinfeld"; }, - (c, ex) => + async (c, ex) => { var entry = ex.Entries.Single(); Assert.IsAssignableFrom(entry.Entity); - entry.Reload(); + await entry.ReloadAsync(); try { - c.SaveChanges(); + await c.SaveChangesAsync(); Assert.Fail("Expected second exception due to conflict in principals."); } catch (DbUpdateConcurrencyException ex2) @@ -151,12 +151,12 @@ public virtual Task Two_concurrency_issues_in_one_to_one_related_entities_can_be var entry2 = ex2.Entries.Single(); Assert.IsAssignableFrom(entry2.Entity); - entry2.Reload(); + await entry2.ReloadAsync(); } }, - c => + async c => { - var team = c.Teams.Single(t => t.Id == Team.McLaren); + var team = await c.Teams.SingleAsync(t => t.Id == Team.McLaren); Assert.Equal("MP4-25b", team.Chassis.Name); Assert.Equal("Larry David", team.Principal); }); @@ -164,29 +164,29 @@ public virtual Task Two_concurrency_issues_in_one_to_one_related_entities_can_be [ConditionalFact] public virtual Task Two_concurrency_issues_in_one_to_many_related_entities_can_be_handled_by_dealing_with_dependent_first() => ConcurrencyTestAsync( - c => + async c => { - var driver = c.Drivers.Single(d => d.Name == "Jenson Button"); - var team = c.Teams.Single(t => t.Id == Team.McLaren); + var driver = await c.Drivers.SingleAsync(d => d.Name == "Jenson Button"); + var team = await c.Teams.SingleAsync(t => t.Id == Team.McLaren); driver.Poles = 1; team.Principal = "Larry David"; }, - c => + async c => { - var driver = c.Drivers.Single(d => d.Name == "Jenson Button"); - var team = c.Teams.Single(t => t.Id == Team.McLaren); + var driver = await c.Drivers.SingleAsync(d => d.Name == "Jenson Button"); + var team = await c.Teams.SingleAsync(t => t.Id == Team.McLaren); driver.Poles = 2; team.Principal = "Jerry Seinfeld"; }, - (c, ex) => + async (c, ex) => { var entry = ex.Entries.Single(); Assert.IsAssignableFrom(entry.Entity); - entry.Reload(); + await entry.ReloadAsync(); try { - c.SaveChanges(); + await c.SaveChangesAsync(); Assert.Fail("Expected second exception due to conflict in principals."); } catch (DbUpdateConcurrencyException ex2) @@ -198,12 +198,12 @@ public virtual Task Two_concurrency_issues_in_one_to_many_related_entities_can_b var entry2 = ex2.Entries.Single(); Assert.IsAssignableFrom(entry2.Entity); - entry2.Reload(); + await entry2.ReloadAsync(); } }, - c => + async c => { - var team = c.Teams.Single(t => t.Id == Team.McLaren); + var team = await c.Teams.SingleAsync(t => t.Id == Team.McLaren); Assert.Equal(1, team.Drivers.Single(d => d.Name == "Jenson Button").Poles); Assert.Equal("Larry David", team.Principal); }); @@ -211,20 +211,20 @@ public virtual Task Two_concurrency_issues_in_one_to_many_related_entities_can_b [ConditionalFact] public virtual Task Concurrency_issue_where_the_FK_is_the_concurrency_token_can_be_handled() => ConcurrencyTestAsync( - c => c.Engines.Single(e => e.Name == "056").EngineSupplierId = - c.EngineSuppliers.Single(s => s.Name == "Cosworth").Name, - c => c.Engines.Single(e => e.Name == "056").EngineSupplier = - c.EngineSuppliers.Single(s => s.Name == "Renault"), - (c, ex) => + async c => (await c.Engines.SingleAsync(e => e.Name == "056")).EngineSupplierId = + (await c.EngineSuppliers.SingleAsync(s => s.Name == "Cosworth")).Name, + async c => (await c.Engines.SingleAsync(e => e.Name == "056")).EngineSupplier = + await c.EngineSuppliers.SingleAsync(s => s.Name == "Renault"), + async (c, ex) => { var entry = ex.Entries.Single(e => e.Metadata.ClrType == typeof(Engine)); Assert.IsAssignableFrom(entry.Entity); - entry.Reload(); + await entry.ReloadAsync(); }, - c => + async c => Assert.Equal( "Cosworth", - c.Engines.Single(e => e.Name == "056").EngineSupplier.Name)); + (await c.Engines.SingleAsync(e => e.Name == "056")).EngineSupplier.Name)); #endregion @@ -233,11 +233,13 @@ public virtual Task Concurrency_issue_where_the_FK_is_the_concurrency_token_can_ [ConditionalFact] public virtual Task Change_in_independent_association_results_in_independent_association_exception() => ConcurrencyTestAsync( - c => c.Teams.Single(t => t.Id == Team.Ferrari).Engine = c.Engines.Single(s => s.Name == "FO 108X"), - (c, ex) => + async c => (await c.Teams.SingleAsync(t => t.Id == Team.Ferrari)).Engine = + await c.Engines.SingleAsync(s => s.Name == "FO 108X"), + (_, ex) => { var entry = ex.Entries.Single(); Assert.IsAssignableFrom(entry.Entity); + return Task.CompletedTask; }, null); @@ -245,29 +247,31 @@ public virtual Task Change_in_independent_association_results_in_independent_ass public virtual Task Change_in_independent_association_after_change_in_different_concurrency_token_results_in_independent_association_exception() => ConcurrencyTestAsync( - c => c.Teams.Single(t => t.Id == Team.Ferrari).FastestLaps = 0, - c => - c.Teams.Single(t => t.Constructor == "Ferrari").Engine = - c.Engines.Single(s => s.Name == "FO 108X"), - (c, ex) => + async c => (await c.Teams.SingleAsync(t => t.Id == Team.Ferrari)).FastestLaps = 0, async c => + (await c.Teams.SingleAsync(t => t.Constructor == "Ferrari")).Engine = + await c.Engines.SingleAsync(s => s.Name == "FO 108X"), + (_, ex) => { var entry = ex.Entries.Single(); Assert.IsAssignableFrom(entry.Entity); + return Task.CompletedTask; }, null); [ConditionalFact] public virtual Task Attempting_to_delete_same_relationship_twice_for_many_to_many_results_in_independent_association_exception() => ConcurrencyTestAsync( - c => + async c => { - c.Teams.Include(e => e.Sponsors).Load(); - c.Teams.Single(t => t.Id == Team.McLaren).Sponsors.Remove(c.Sponsors.Single(s => s.Name.Contains("FIA"))); + await c.Teams.Include(e => e.Sponsors).LoadAsync(); + (await c.Teams.SingleAsync(t => t.Id == Team.McLaren)).Sponsors.Remove( + await c.Sponsors.SingleAsync(s => s.Name.Contains("FIA"))); }, - (c, ex) => + (_, ex) => { var entry = ex.Entries.Single(); Assert.IsAssignableFrom(entry.Entity); + return Task.CompletedTask; }, null); @@ -281,13 +285,15 @@ public virtual Task Attempting_to_add_same_relationship_twice_for_many_to_many_r { var entry = ex.Entries.Single(); Assert.IsAssignableFrom(entry.Entity); + return Task.CompletedTask; }, null); - void Change(F1Context c) + async Task Change(F1Context c) { - c.Teams.Include(e => e.Sponsors).Load(); - c.Teams.Single(t => t.Id == Team.McLaren).Sponsors.Add(c.Sponsors.Single(s => s.Name.Contains("Shell"))); + await c.Teams.Include(e => e.Sponsors).LoadAsync(); + (await c.Teams.SingleAsync(t => t.Id == Team.McLaren)).Sponsors.Add( + await c.Sponsors.SingleAsync(s => s.Name.Contains("Shell"))); } } @@ -299,15 +305,15 @@ void Change(F1Context c) [ConditionalFact(Skip = "Issue#13890")] public virtual Task Concurrency_issue_where_a_complex_type_nested_member_is_the_concurrency_token_can_be_handled() => ConcurrencyTestAsync( - c => c.Engines.Single(s => s.Name == "CA2010").StorageLocation.Latitude = 47.642576, - (c, ex) => + async c => (await c.Engines.SingleAsync(s => s.Name == "CA2010")).StorageLocation.Latitude = 47.642576, + (_, ex) => { var entry = ex.Entries.Single(); Assert.IsAssignableFrom(entry.Entity); entry.Reload(); - }, - c => - Assert.Equal(47.642576, c.Engines.Single(s => s.Name == "CA2010").StorageLocation.Latitude)); + return Task.CompletedTask; + }, async c => + Assert.Equal(47.642576, (await c.Engines.SingleAsync(s => s.Name == "CA2010")).StorageLocation.Latitude)); #endregion @@ -348,75 +354,74 @@ await c.Database.CreateExecutionStrategy().ExecuteAsync( [ConditionalFact] public virtual Task Deleting_the_same_entity_twice_results_in_DbUpdateConcurrencyException() => ConcurrencyTestAsync( - c => c.Drivers.Remove(c.Drivers.Single(d => d.Name == "Fernando Alonso")), - (c, ex) => + async c => c.Drivers.Remove(await c.Drivers.SingleAsync(d => d.Name == "Fernando Alonso")), + async (_, ex) => { var entry = ex.Entries.Single(); Assert.IsAssignableFrom(entry.Entity); - entry.Reload(); - }, - c => Assert.Null(c.Drivers.SingleOrDefault(d => d.Name == "Fernando Alonso"))); + await entry.ReloadAsync(); + }, async c => Assert.Null(await c.Drivers.SingleOrDefaultAsync(d => d.Name == "Fernando Alonso"))); [ConditionalFact] public virtual Task Updating_then_deleting_the_same_entity_results_in_DbUpdateConcurrencyException() => ConcurrencyTestAsync( - c => c.Drivers.Single(d => d.Name == "Fernando Alonso").Wins = 1, - c => c.Drivers.Remove(c.Drivers.Single(d => d.Name == "Fernando Alonso")), - (c, ex) => + async c => (await c.Drivers.SingleAsync(d => d.Name == "Fernando Alonso")).Wins = 1, + async c => c.Drivers.Remove(await c.Drivers.SingleAsync(d => d.Name == "Fernando Alonso")), + async (_, ex) => { var entry = ex.Entries.Single(); Assert.IsAssignableFrom(entry.Entity); - entry.Reload(); + await entry.ReloadAsync(); }, - c => Assert.Equal(1, c.Drivers.Single(d => d.Name == "Fernando Alonso").Wins)); + async c => Assert.Equal(1, (await c.Drivers.SingleAsync(d => d.Name == "Fernando Alonso")).Wins)); [ConditionalFact] public virtual Task Updating_then_deleting_the_same_entity_results_in_DbUpdateConcurrencyException_which_can_be_resolved_with_store_values() => ConcurrencyTestAsync( - c => c.Drivers.Single(d => d.Name == "Fernando Alonso").Wins = 1, - c => c.Drivers.Remove(c.Drivers.Single(d => d.Name == "Fernando Alonso")), - (c, ex) => + async c => (await c.Drivers.SingleAsync(d => d.Name == "Fernando Alonso")).Wins = 1, + async c => c.Drivers.Remove(await c.Drivers.SingleAsync(d => d.Name == "Fernando Alonso")), + async (_, ex) => { var entry = ex.Entries.Single(); Assert.IsAssignableFrom(entry.Entity); entry.State = EntityState.Unchanged; - var storeValues = entry.GetDatabaseValues(); + var storeValues = await entry.GetDatabaseValuesAsync(); entry.OriginalValues.SetValues(storeValues); entry.CurrentValues.SetValues(storeValues); ResolveConcurrencyTokens(entry); }, - c => Assert.Equal(1, c.Drivers.Single(d => d.Name == "Fernando Alonso").Wins)); + async c => Assert.Equal(1, (await c.Drivers.SingleAsync(d => d.Name == "Fernando Alonso")).Wins)); [ConditionalFact] public virtual Task Deleting_then_updating_the_same_entity_results_in_DbUpdateConcurrencyException() => ConcurrencyTestAsync( - c => c.Drivers.Remove(c.Drivers.Single(d => d.Name == "Fernando Alonso")), - c => c.Drivers.Single(d => d.Name == "Fernando Alonso").Wins = 1, - (c, ex) => + async c => c.Drivers.Remove(await c.Drivers.SingleAsync(d => d.Name == "Fernando Alonso")), + async c => (await c.Drivers.SingleAsync(d => d.Name == "Fernando Alonso")).Wins = 1, + async (_, ex) => { var entry = ex.Entries.Single(); Assert.IsAssignableFrom(entry.Entity); - entry.Reload(); + await entry.ReloadAsync(); }, - c => Assert.Null(c.Drivers.SingleOrDefault(d => d.Name == "Fernando Alonso"))); + async c => Assert.Null(await c.Drivers.SingleOrDefaultAsync(d => d.Name == "Fernando Alonso"))); [ConditionalFact] public virtual Task Deleting_then_updating_the_same_entity_results_in_DbUpdateConcurrencyException_which_can_be_resolved_with_store_values() => ConcurrencyTestAsync( - c => c.Drivers.Remove(c.Drivers.Single(d => d.Name == "Fernando Alonso")), - c => c.Drivers.Single(d => d.Name == "Fernando Alonso").Wins = 1, - (c, ex) => + async c => c.Drivers.Remove(await c.Drivers.SingleAsync(d => d.Name == "Fernando Alonso")), + async c => (await c.Drivers.SingleAsync(d => d.Name == "Fernando Alonso")).Wins = 1, + async (_, ex) => { var entry = ex.Entries.Single(); Assert.IsAssignableFrom(entry.Entity); - var storeValues = entry.GetDatabaseValues(); + var storeValues = await entry.GetDatabaseValuesAsync(); Assert.Null(storeValues); entry.State = EntityState.Detached; }, - c => Assert.Null(c.Drivers.SingleOrDefault(d => d.Name == "Fernando Alonso"))); + async c => Assert.Null(await c.Drivers.SingleOrDefaultAsync(d => d.Name == "Fernando Alonso"))); #endregion @@ -544,7 +549,10 @@ await c.Database.CreateExecutionStrategy().ExecuteAsync( { using (BeginTransaction(context.Database)) { - var larry = context.Drivers.Single(d => d.Name == "Jenson Button"); + var larry = async + ? await context.Drivers.SingleAsync(d => d.Name == "Jenson Button") + : context.Drivers.Single(d => d.Name == "Jenson Button"); + larry.Name = "Rory Gilmore"; var entry = context.Entry(larry); entry.Property(e => e.Name).CurrentValue = "Emily Gilmore"; @@ -576,7 +584,9 @@ await c.Database.CreateExecutionStrategy().ExecuteAsync( c, async context => { using var transaction = BeginTransaction(context.Database); - var titleSponsor = context.Set().Single(t => t.Name == "Vodafone"); + var titleSponsor = async + ? await context.Set().SingleAsync(t => t.Name == "Vodafone") + : context.Set().Single(t => t.Name == "Vodafone"); var ownerEntry = context.Entry(titleSponsor); var ownedEntry = ownerEntry.Reference(e => e.Details).TargetEntry; @@ -606,7 +616,9 @@ await c.Database.CreateExecutionStrategy().ExecuteAsync( c, async context => { using var transaction = BeginTransaction(context.Database); - var titleSponsor = context.Set().Single(t => t.Name == "Vodafone"); + var titleSponsor = async + ? await context.Set().SingleAsync(t => t.Name == "Vodafone") + : context.Set().Single(t => t.Name == "Vodafone"); var ownerEntry = context.Entry(titleSponsor); var ownedEntry = ownerEntry.Reference(e => e.Details).TargetEntry; @@ -647,12 +659,12 @@ protected virtual void ResolveConcurrencyTokens(EntityEntry entry) protected F1Context CreateF1Context() => Fixture.CreateContext(); - private Task ConcurrencyTestAsync(int expectedPodiums, Action resolver) + private Task ConcurrencyTestAsync(int expectedPodiums, Func resolver) => ConcurrencyTestAsync( - c => c.Drivers.Single(d => d.CarNumber == 1).Podiums = StorePodiums, - c => c.Drivers.Single(d => d.CarNumber == 1).Podiums = ClientPodiums, + async c => (await c.Drivers.SingleAsync(d => d.CarNumber == 1)).Podiums = StorePodiums, + async c => (await c.Drivers.SingleAsync(d => d.CarNumber == 1)).Podiums = ClientPodiums, resolver, - c => Assert.Equal(expectedPodiums, c.Drivers.Single(d => d.CarNumber == 1).Podiums)); + async c => Assert.Equal(expectedPodiums, (await c.Drivers.SingleAsync(d => d.CarNumber == 1)).Podiums)); /// /// Runs the same action twice inside a transaction scope but with two different contexts and calling @@ -663,9 +675,9 @@ private Task ConcurrencyTestAsync(int expectedPodiums, Action private Task ConcurrencyTestAsync( - Action change, - Action resolver, - Action validator) + Func change, + Func resolver, + Func validator) => ConcurrencyTestAsync(change, change, resolver, validator); /// @@ -677,10 +689,10 @@ private Task ConcurrencyTestAsync( /// the database at the end of the process can be validated. /// protected virtual Task ConcurrencyTestAsync( - Action storeChange, - Action clientChange, - Action resolver, - Action validator) + Func storeChange, + Func clientChange, + Func resolver, + Func validator) => ConcurrencyTestAsync(storeChange, clientChange, resolver, validator); /// @@ -692,10 +704,10 @@ protected virtual Task ConcurrencyTestAsync( /// the database at the end of the process can be validated. /// protected virtual async Task ConcurrencyTestAsync( - Action storeChange, - Action clientChange, - Action resolver, - Action validator) + Func storeChange, + Func clientChange, + Func resolver, + Func validator) where TException : DbUpdateException { using var c = CreateF1Context(); @@ -703,11 +715,11 @@ await c.Database.CreateExecutionStrategy().ExecuteAsync( c, async context => { using var transaction = BeginTransaction(context.Database); - clientChange(context); + await clientChange(context); using var innerContext = CreateF1Context(); UseTransaction(innerContext.Database, transaction); - storeChange(innerContext); + await storeChange(innerContext); await innerContext.SaveChangesAsync(); var updateException = @@ -722,7 +734,7 @@ await c.Database.CreateExecutionStrategy().ExecuteAsync( Fixture.ListLoggerFactory.Clear(); - resolver(context, updateException); + await resolver(context, updateException); using var validationContext = CreateF1Context(); UseTransaction(validationContext.Database, transaction); @@ -730,7 +742,7 @@ await c.Database.CreateExecutionStrategy().ExecuteAsync( { await context.SaveChangesAsync(); - validator(validationContext); + await validator(validationContext); } }); } diff --git a/test/EFCore.Specification.Tests/OverzealousInitializationTestBase.cs b/test/EFCore.Specification.Tests/OverzealousInitializationTestBase.cs index 235462d9135..424b82aca73 100644 --- a/test/EFCore.Specification.Tests/OverzealousInitializationTestBase.cs +++ b/test/EFCore.Specification.Tests/OverzealousInitializationTestBase.cs @@ -97,7 +97,7 @@ public virtual IDisposable BeginTransaction(DbContext context) protected override string StoreName => "OverzealousInitialization"; - protected override void Seed(AlbumViewerContext context) + protected override Task SeedAsync(AlbumViewerContext context) { for (var i = 1; i <= 10; i++) { @@ -110,7 +110,7 @@ protected override void Seed(AlbumViewerContext context) }); } - context.SaveChanges(); + return context.SaveChangesAsync(); } } } diff --git a/test/EFCore.Specification.Tests/PropertyValuesTestBase.cs b/test/EFCore.Specification.Tests/PropertyValuesTestBase.cs index 6bc71e23076..a02f56cde4e 100644 --- a/test/EFCore.Specification.Tests/PropertyValuesTestBase.cs +++ b/test/EFCore.Specification.Tests/PropertyValuesTestBase.cs @@ -2557,7 +2557,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con }); } - protected override void Seed(PoolableDbContext context) + protected override Task SeedAsync(PoolableDbContext context) { var buildings = new List { @@ -2678,7 +2678,7 @@ protected override void Seed(PoolableDbContext context) Assert.True((bool)joinEntry.Entity["InitializedCalled"]); } - context.SaveChanges(); + return context.SaveChangesAsync(); } } diff --git a/test/EFCore.Specification.Tests/Query/AdHocAdvancedMappingsQueryTestBase.cs b/test/EFCore.Specification.Tests/Query/AdHocAdvancedMappingsQueryTestBase.cs index 5086a50dd59..dcba2641818 100644 --- a/test/EFCore.Specification.Tests/Query/AdHocAdvancedMappingsQueryTestBase.cs +++ b/test/EFCore.Specification.Tests/Query/AdHocAdvancedMappingsQueryTestBase.cs @@ -58,7 +58,7 @@ public class TipoServicio [ConditionalFact] public virtual async Task Projecting_correlated_collection_along_with_non_mapped_property() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using (var context = contextFactory.CreateContext()) { var result = context.Blogs.Select( @@ -87,7 +87,7 @@ private class Context11835(DbContextOptions options) : DbContext(options) public DbSet Blogs { get; set; } public DbSet Posts { get; set; } - public void Seed() + public Task SeedAsync() { var b1 = new Blog { Title = "B1" }; var b2 = new Blog { Title = "B2" }; @@ -99,7 +99,7 @@ public void Seed() Blogs.AddRange(b1, b2); Posts.AddRange(p11, p12, p13, p21, p22); - SaveChanges(); + return SaveChangesAsync(); } public class Blog @@ -128,7 +128,7 @@ public class Post [ConditionalFact] public virtual async Task Projection_failing_with_EnumToStringConverter() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var query = from p in context.Products join c in context.Categories on p.CategoryId equals c.Id into grouping @@ -155,14 +155,14 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .Property(e => e.Status) .HasConversion(new EnumToStringConverter()); - public void Seed() + public Task SeedAsync() { Products.Add( new Product { Name = "Apple", Category = new Category { Name = "Fruit", Status = CategoryStatus.Active } }); Products.Add(new Product { Name = "Bike" }); - SaveChanges(); + return SaveChangesAsync(); } public class Product @@ -303,7 +303,7 @@ public class Specification(int id) [ConditionalFact] public virtual async Task Double_convert_interface_created_expression_tree() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var expression = Context17794.HasAction17794(Context17794.Actions.Accepted); var query = context.Offers.Where(expression).Count(); @@ -320,10 +320,10 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) { } - public void Seed() + public Task SeedAsync() { Add(new Offer { OfferActions = new List { new() { Action = Actions.Accepted } } }); - SaveChanges(); + return SaveChangesAsync(); } public static Expression> HasAction17794(Actions action) @@ -373,7 +373,7 @@ public class OfferAction [ConditionalFact] public virtual async Task Casts_are_removed_from_expression_tree_when_redundant() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using (var context = contextFactory.CreateContext()) { @@ -411,14 +411,14 @@ private class Context18087(DbContextOptions options) : DbContext(options) { public DbSet MockEntities { get; set; } - public void Seed() + public Task SeedAsync() { AddRange( new MockEntity { Name = "Entity1", NavigationEntity = null }, new MockEntity { Name = "Entity2", NavigationEntity = null }, new MockEntity { Name = "NewEntity", NavigationEntity = null }); - SaveChanges(); + return SaveChangesAsync(); } public interface IDomainEntity @@ -447,7 +447,7 @@ public class MockEntity : IDomainEntity [ConditionalFact] public virtual async Task Can_query_hierarchy_with_non_nullable_property_on_derived() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var query = context.Businesses.ToList(); Assert.Equal(3, query.Count); @@ -463,13 +463,13 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .HasValue(BusinessType.Shop) .HasValue(BusinessType.Brand); - public void Seed() + public Task SeedAsync() { var shop1 = new Shop { IsOnline = true, Name = "Amzn" }; var shop2 = new Shop { IsOnline = false, Name = "Mom and Pop's Shoppe" }; var brand = new Brand { Name = "Tsla" }; Businesses.AddRange(shop1, shop2, brand); - SaveChanges(); + return SaveChangesAsync(); } public abstract class Business @@ -599,7 +599,7 @@ public virtual Task Hierarchy_query_with_abstract_type_sibling(bool async) public virtual async Task Hierarchy_query_with_abstract_type_sibling_helper(bool async, Action onModelCreating) { - var contextFactory = await InitializeAsync(onModelCreating: onModelCreating, seed: c => c.Seed()); + var contextFactory = await InitializeAsync(onModelCreating: onModelCreating, seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var query = context.Animals.OfType().Where(a => a.Species.StartsWith("F")); var result = async @@ -620,7 +620,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) modelBuilder.Entity(); } - public void Seed() + public Task SeedAsync() { AddRange( new Cat @@ -651,7 +651,7 @@ public void Seed() Species = "Ovis aries" }); - SaveChanges(); + return SaveChangesAsync(); } public abstract class Animal diff --git a/test/EFCore.Specification.Tests/Query/AdHocManyToManyQueryTestBase.cs b/test/EFCore.Specification.Tests/Query/AdHocManyToManyQueryTestBase.cs index c304daf82d8..7221edef55c 100644 --- a/test/EFCore.Specification.Tests/Query/AdHocManyToManyQueryTestBase.cs +++ b/test/EFCore.Specification.Tests/Query/AdHocManyToManyQueryTestBase.cs @@ -18,7 +18,7 @@ protected virtual void ClearLog() [ConditionalFact] public virtual async Task SelectMany_with_collection_selector_having_subquery() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var users = (from user in context.Users from organisation in context.Organisations.Where(o => o.OrganisationUsers.Any()).DefaultIfEmpty() @@ -41,14 +41,14 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .HasForeignKey(ou => ou.UserId); } - public void Seed() + public Task SeedAsync() { AddRange( new OrganisationUser { Organisation = new Organisation(), User = new User() }, new Organisation(), new User()); - SaveChanges(); + return SaveChangesAsync(); } public class User diff --git a/test/EFCore.Specification.Tests/Query/AdHocMiscellaneousQueryTestBase.cs b/test/EFCore.Specification.Tests/Query/AdHocMiscellaneousQueryTestBase.cs index d511c6b298b..22223eb470e 100644 --- a/test/EFCore.Specification.Tests/Query/AdHocMiscellaneousQueryTestBase.cs +++ b/test/EFCore.Specification.Tests/Query/AdHocMiscellaneousQueryTestBase.cs @@ -30,7 +30,7 @@ public virtual async Task First_FirstOrDefault_ix_async() using (var context = contextFactory.CreateContext()) { context.Products.Add(new Context603.Product { Name = "Product 1" }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = contextFactory.CreateContext()) @@ -185,7 +185,7 @@ public class Postcode [ConditionalFact] public virtual async Task Shadow_property_with_inheritance() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using (var context = contextFactory.CreateContext()) { @@ -226,33 +226,31 @@ private class Context6986(DbContextOptions options) : DbContext(options) public DbSet ServiceOperatorContacts { get; set; } public DbSet ServiceOperators { get; set; } - public void Seed() + public async Task SeedAsync() { ServiceOperators.Add(new ServiceOperator()); Employers.AddRange( new Employer { Name = "UWE" }, new Employer { Name = "Hewlett Packard" }); - SaveChanges(); + await SaveChangesAsync(); Contacts.AddRange( new ServiceOperatorContact { - UserName = "service.operator@esoterix.co.uk", - ServiceOperator = ServiceOperators.OrderBy(o => o.Id).First() + UserName = "service.operator@esoterix.co.uk", ServiceOperator = ServiceOperators.OrderBy(o => o.Id).First() }, new EmployerContact { - UserName = "uwe@esoterix.co.uk", - Employer = Employers.OrderBy(e => e.Id).First(e => e.Name == "UWE") + UserName = "uwe@esoterix.co.uk", Employer = Employers.OrderBy(e => e.Id).First(e => e.Name == "UWE") }, new EmployerContact { - UserName = "hp@esoterix.co.uk", - Employer = Employers.OrderBy(e => e.Id).First(e => e.Name == "Hewlett Packard") + UserName = "hp@esoterix.co.uk", Employer = Employers.OrderBy(e => e.Id).First(e => e.Name == "Hewlett Packard") }, new Contact { UserName = "noroles@esoterix.co.uk" }); - SaveChanges(); + + await SaveChangesAsync(); } public class EmployerContact : Contact @@ -330,7 +328,7 @@ public class Blog [ConditionalFact] public virtual async Task Discriminator_type_is_handled_correctly() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using (var ctx = contextFactory.CreateContext()) { @@ -360,11 +358,11 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .HasValue(1); } - public void Seed() + public Task SeedAsync() { Add(new Product { Name = "Product1" }); Add(new SpecialProduct { Name = "SpecialProduct" }); - SaveChanges(); + return SaveChangesAsync(); } public class Product @@ -384,7 +382,7 @@ public class SpecialProduct : Product; [ConditionalFact] public virtual async Task New_instances_in_projection_are_not_shared_across_results() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var list = context.Posts.Select(p => new Context7983.PostDTO().From(p)).ToList(); @@ -397,7 +395,7 @@ private class Context7983(DbContextOptions options) : DbContext(options) public DbSet Blogs { get; set; } public DbSet Posts { get; set; } - public void Seed() + public Task SeedAsync() { Add( new Blog @@ -410,7 +408,7 @@ public void Seed() } }); - SaveChanges(); + return SaveChangesAsync(); } public class Blog @@ -449,7 +447,7 @@ public PostDTO From(Post post) [ConditionalFact] public virtual async Task Enum_has_flag_applies_explicit_cast_for_constant() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using (var context = contextFactory.CreateContext()) { @@ -467,7 +465,7 @@ public virtual async Task Enum_has_flag_applies_explicit_cast_for_constant() [ConditionalFact] public virtual async Task Enum_has_flag_does_not_apply_explicit_cast_for_non_constant() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using (var context = contextFactory.CreateContext()) { @@ -486,7 +484,7 @@ private class Context8538(DbContextOptions options) : DbContext(options) { public DbSet Entities { get; set; } - public void Seed() + public Task SeedAsync() { AddRange( new Entity @@ -509,7 +507,7 @@ public void Seed() } ); - SaveChanges(); + return SaveChangesAsync(); } public class Entity @@ -700,7 +698,7 @@ public class Entity [ConditionalFact] public virtual async Task Conditional_expression_with_conditions_does_not_collapse_if_nullable_bool() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var query = context.Carts.Select( t => new { Processing = t.Configuration != null ? !t.Configuration.Processed : (bool?)null }).ToList(); @@ -714,7 +712,7 @@ private class Context9468(DbContextOptions options) : DbContext(options) { public DbSet Carts { get; set; } - public void Seed() + public Task SeedAsync() { AddRange( new Cart(), @@ -722,7 +720,7 @@ public void Seed() new Cart { Configuration = new Configuration() } ); - SaveChanges(); + return SaveChangesAsync(); } public class Cart @@ -746,7 +744,7 @@ public class Configuration [ConditionalFact] public virtual async Task QueryBuffer_requirement_is_computed_when_querying_base_type_while_derived_type_has_shadow_prop() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var query = context.Bases.ToList(); @@ -764,10 +762,10 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .HasValue(false) .HasValue(true); - public void Seed() + public Task SeedAsync() { AddRange(new Derived1 { IsTwo = false }); - SaveChanges(); + return SaveChangesAsync(); } public abstract class Base @@ -796,7 +794,7 @@ public class Stuff [ConditionalFact] public virtual async Task Average_with_cast() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var prices = context.Prices.ToList(); @@ -826,7 +824,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) b.Property(e => e.NullableDecimalColumn).HasPrecision(18, 2); }); - public void Seed() + public Task SeedAsync() { AddRange( new PriceEntity @@ -868,7 +866,7 @@ public void Seed() } ); - SaveChanges(); + return SaveChangesAsync(); } public class PriceEntity @@ -895,7 +893,7 @@ public class PriceEntity [ConditionalFact] public virtual async Task Parameterless_ctor_on_inner_DTO_gets_called_for_every_row() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var results = context.Entities.Select( x => @@ -915,7 +913,7 @@ private class Context12274(DbContextOptions options) : DbContext(options) { public DbSet Entities { get; set; } - public void Seed() + public Task SeedAsync() { var e1 = new MyEntity { Name = "1" }; var e2 = new MyEntity { Name = "2" }; @@ -923,7 +921,7 @@ public void Seed() var e4 = new MyEntity { Name = "4" }; Entities.AddRange(e1, e2, e3, e4); - SaveChanges(); + return SaveChangesAsync(); } public class MyEntity @@ -971,7 +969,8 @@ public virtual async Task Union_and_insert_works_correctly_together() new Context12549.Table2(), new Context12549.Table1(), new Context12549.Table2()); - context.SaveChanges(); + + await context.SaveChangesAsync(); } } @@ -998,7 +997,7 @@ public class Table2 [ConditionalFact] public virtual async Task Repeated_parameters_in_generated_query_sql() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var k = 1; var a = context.Autos.Where(e => e.Id == k).First(); @@ -1017,20 +1016,20 @@ private class Context15215(DbContextOptions options) : DbContext(options) public DbSet Autos { get; set; } public DbSet EqualAutos { get; set; } - public void Seed() + public async Task SeedAsync() { for (var i = 0; i < 10; i++) { Add(new Auto { Name = "Auto " + i }); } - SaveChanges(); + await SaveChangesAsync(); AddRange( - new EqualAuto { Auto = Autos.Find(1), AnotherAuto = Autos.Find(2) }, - new EqualAuto { Auto = Autos.Find(5), AnotherAuto = Autos.Find(4) }); + new EqualAuto { Auto = await Autos.FindAsync(1), AnotherAuto = await Autos.FindAsync(2) }, + new EqualAuto { Auto = await Autos.FindAsync(5), AnotherAuto = await Autos.FindAsync(4) }); - SaveChanges(); + await SaveChangesAsync(); } public class Auto @@ -1054,7 +1053,7 @@ public class EqualAuto [ConditionalFact] public virtual async Task Operators_combine_nullability_of_entity_shapers() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using (var context = contextFactory.CreateContext()) { @@ -1077,11 +1076,7 @@ public virtual async Task Operators_combine_nullability_of_entity_shapers() (right, leftg) => new { leftg, right }) .SelectMany( l => l.leftg.DefaultIfEmpty(), - (x, y) => new Context19253.JoinResult - { - Left = y, - Right = x.right - }) + (x, y) => new Context19253.JoinResult { Left = y, Right = x.right }) .Where(z => z.Left.Equals(null))) .ToList(); @@ -1109,11 +1104,7 @@ public virtual async Task Operators_combine_nullability_of_entity_shapers() (right, leftg) => new { leftg, right }) .SelectMany( l => l.leftg.DefaultIfEmpty(), - (x, y) => new Context19253.JoinResult - { - Left = y, - Right = x.right - }) + (x, y) => new Context19253.JoinResult { Left = y, Right = x.right }) .Where(z => z.Left.Equals(null))) .ToList(); @@ -1141,11 +1132,7 @@ public virtual async Task Operators_combine_nullability_of_entity_shapers() (right, leftg) => new { leftg, right }) .SelectMany( l => l.leftg.DefaultIfEmpty(), - (x, y) => new Context19253.JoinResult - { - Left = y, - Right = x.right - })) + (x, y) => new Context19253.JoinResult { Left = y, Right = x.right })) .ToList(); Assert.Single(query); @@ -1172,11 +1159,7 @@ public virtual async Task Operators_combine_nullability_of_entity_shapers() (right, leftg) => new { leftg, right }) .SelectMany( l => l.leftg.DefaultIfEmpty(), - (x, y) => new Context19253.JoinResult - { - Left = y, - Right = x.right - })) + (x, y) => new Context19253.JoinResult { Left = y, Right = x.right })) .ToList(); Assert.Single(query); @@ -1188,7 +1171,7 @@ private class Context19253(DbContextOptions options) : DbContext(options) public DbSet As { get; set; } public DbSet Bs { get; set; } - public void Seed() + public Task SeedAsync() { var tmp_a = new[] { @@ -1222,7 +1205,7 @@ public void Seed() }; As.AddRange(tmp_a); Bs.AddRange(tmp_b); - SaveChanges(); + return SaveChangesAsync(); } public class JoinResult @@ -1454,7 +1437,7 @@ public int Id [MemberData(nameof(IsAsyncData))] public virtual async Task Bool_discriminator_column_works(bool async) { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var query = context.Authors.Include(e => e.Blog); @@ -1476,12 +1459,12 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .HasValue(false) .HasValue(true); - public void Seed() + public Task SeedAsync() { Add(new Author { Blog = new DevBlog { Title = "Dev Blog", } }); Add(new Author { Blog = new PhotoBlog { Title = "Photo Blog", } }); - SaveChanges(); + return SaveChangesAsync(); } public class Author @@ -1524,7 +1507,7 @@ public PhotoBlog() [MemberData(nameof(IsAsyncData))] public virtual async Task Unwrap_convert_node_over_projection_when_translating_contains_over_subquery(bool async) { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var currentUserId = 1; @@ -1549,7 +1532,7 @@ public virtual async Task Unwrap_convert_node_over_projection_when_translating_c [MemberData(nameof(IsAsyncData))] public virtual async Task Unwrap_convert_node_over_projection_when_translating_contains_over_subquery_2(bool async) { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var currentUserId = 1; @@ -1574,7 +1557,7 @@ public virtual async Task Unwrap_convert_node_over_projection_when_translating_c [MemberData(nameof(IsAsyncData))] public virtual async Task Unwrap_convert_node_over_projection_when_translating_contains_over_subquery_3(bool async) { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var currentUserId = 1; @@ -1601,14 +1584,14 @@ private class Context26593(DbContextOptions options) : DbContext(options) public DbSet Groups { get; set; } public DbSet Memberships { get; set; } - public void Seed() + public Task SeedAsync() { var user = new User(); var group = new Group(); var membership = new Membership { Group = group, User = user }; AddRange(user, group, membership); - SaveChanges(); + return SaveChangesAsync(); } public class User @@ -1747,7 +1730,7 @@ public enum OrderItemType [MemberData(nameof(IsAsyncData))] public virtual async Task GroupBy_Aggregate_over_navigations_repeated(bool async) { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var query = context @@ -1773,7 +1756,7 @@ public virtual async Task GroupBy_Aggregate_over_navigations_repeated(bool async [MemberData(nameof(IsAsyncData))] public virtual async Task Aggregate_over_subquery_in_group_by_projection(bool async) { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); Expression> someFilterFromOutside = x => x.Number != "A1"; @@ -1786,7 +1769,8 @@ public virtual async Task Aggregate_over_subquery_in_group_by_projection(bool as x => new { x.Key.CustomerId, - CustomerMinHourlyRate = context.Set().Where(n => n.CustomerId == x.Key.CustomerId).Min(h => h.HourlyRate), + CustomerMinHourlyRate = + context.Set().Where(n => n.CustomerId == x.Key.CustomerId).Min(h => h.HourlyRate), HourlyRate = x.Min(f => f.HourlyRate), Count = x.Count() }); @@ -1818,7 +1802,7 @@ private class Context27083(DbContextOptions options) : DbContext(options) public DbSet TimeSheets { get; set; } public DbSet Customers { get; set; } - public void Seed() + public Task SeedAsync() { var customerA = new Customer { Name = "Customer A" }; var customerB = new Customer { Name = "Customer B" }; @@ -1852,7 +1836,7 @@ public void Seed() AddRange(projectA, projectB); AddRange(orderA1, orderA2, orderB1); AddRange(timeSheetA, timeSheetB); - SaveChanges(); + return SaveChangesAsync(); } public class Customer @@ -1965,7 +1949,7 @@ public class Table [MemberData(nameof(IsAsyncData))] public virtual async Task Subquery_first_member_compared_to_null(bool async) { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var query = context.Parents @@ -1991,7 +1975,7 @@ public virtual async Task Subquery_first_member_compared_to_null(bool async) [MemberData(nameof(IsAsyncData))] public virtual async Task SelectMany_where_Select(bool async) { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var query = context.Parents @@ -2014,16 +1998,13 @@ private class Context26744(DbContextOptions options) : DbContext(options) { public DbSet Parents { get; set; } - public void Seed() + public Task SeedAsync() { Add( - new Parent - { - Children = [new() { SomeInteger = 1, SomeOtherNullableDateTime = new DateTime(2000, 11, 18) }] - }); + new Parent { Children = [new() { SomeInteger = 1, SomeOtherNullableDateTime = new DateTime(2000, 11, 18) }] }); Add(new Parent { Children = [new() { SomeInteger = 1, }] }); - SaveChanges(); + return SaveChangesAsync(); } public class Parent @@ -2050,7 +2031,7 @@ public class Child [MemberData(nameof(IsAsyncData))] public virtual async Task Flattened_GroupJoin_on_interface_generic(bool async) { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var entitySet = context.Parents.AsQueryable(); var query = from p in entitySet @@ -2070,8 +2051,8 @@ private class Context27343(DbContextOptions options) : DbContext(options) { public DbSet Parents { get; set; } - public void Seed() - => SaveChanges(); + public Task SeedAsync() + => SaveChangesAsync(); public interface IDocumentType { @@ -2168,24 +2149,26 @@ public virtual async Task Filter_on_nested_DTO_with_interface_gets_simplified_co using var context = contextFactory.CreateContext(); var query = await context.Customers - .Select(m => new Context31961.CustomerDto() - { - Id = m.Id, - CompanyId = m.CompanyId, - Company = m.Company != null ? new Context31961.CompanyDto() + .Select( + m => new Context31961.CustomerDto() { - Id = m.Company.Id, - CompanyName = m.Company.CompanyName, - CountryId = m.Company.CountryId, - Country = new Context31961.CountryDto() - { - Id = m.Company.Country.Id, - CountryName = m.Company.Country.CountryName, - }, - } : null, - }) - .Where(m => m.Company.Country.CountryName == "COUNTRY") - .ToListAsync(); + Id = m.Id, + CompanyId = m.CompanyId, + Company = m.Company != null + ? new Context31961.CompanyDto() + { + Id = m.Company.Id, + CompanyName = m.Company.CompanyName, + CountryId = m.Company.CountryId, + Country = new Context31961.CountryDto() + { + Id = m.Company.Country.Id, CountryName = m.Company.Country.CountryName, + }, + } + : null, + }) + .Where(m => m.Company.Country.CountryName == "COUNTRY") + .ToListAsync(); } private class Context31961(DbContextOptions options) : DbContext(options) diff --git a/test/EFCore.Specification.Tests/Query/AdHocNavigationsQueryTestBase.cs b/test/EFCore.Specification.Tests/Query/AdHocNavigationsQueryTestBase.cs index b6fb0fcfd52..c0d03f86d60 100644 --- a/test/EFCore.Specification.Tests/Query/AdHocNavigationsQueryTestBase.cs +++ b/test/EFCore.Specification.Tests/Query/AdHocNavigationsQueryTestBase.cs @@ -20,7 +20,7 @@ protected override string StoreName [ConditionalFact] public virtual async Task ThenInclude_with_interface_navigations() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using (var context = contextFactory.CreateContext()) { @@ -95,7 +95,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .WithOne(c => (Child)c.SelfReferenceBackNavigation); } - public void Seed() + public Task SeedAsync() { var parent1 = new Parent(); @@ -109,7 +109,7 @@ public void Seed() Parents.AddRange(parent1); Children.AddRange(child1, child2, child3); - SaveChanges(); + return SaveChangesAsync(); } public interface IParent @@ -158,7 +158,7 @@ public class Child : IChild [ConditionalFact] public virtual async Task Customer_collections_materialize_properly() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var ctx = contextFactory.CreateContext(); @@ -212,7 +212,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) }); } - public void Seed() + public Task SeedAsync() { var o111 = new Order { Name = "O111" }; var o112 = new Order { Name = "O112" }; @@ -263,7 +263,7 @@ public void Seed() o212, o221, o222, o231, o232, o241); - SaveChanges(); + return SaveChangesAsync(); } public class Customer @@ -303,7 +303,7 @@ public MyInvalidCollection(int argument) [ConditionalFact] public virtual async Task Reference_include_on_derived_type_with_sibling_works() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using (var context = contextFactory.CreateContext()) { @@ -319,14 +319,14 @@ private class Context7312(DbContextOptions options) : DbContext(options) public DbSet ProposalCustoms { get; set; } public DbSet ProposalLeaves { get; set; } - public void Seed() + public Task SeedAsync() { AddRange( new Proposal(), new ProposalCustom { Name = "CustomProposal" }, new ProposalLeave { LeaveStart = DateTime.Now, LeaveType = new ProposalLeaveType() } ); - SaveChanges(); + return SaveChangesAsync(); } public class Proposal @@ -359,7 +359,7 @@ public class ProposalLeaveType [ConditionalFact] public virtual async Task Include_collection_optional_reference_collection() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using (var context = contextFactory.CreateContext()) { @@ -412,7 +412,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) }); } - public void Seed() + public Task SeedAsync() { var famalies = new List { new() { LastName = "Garrison" }, new() { LastName = "Cartman" } }; var teachers = new List @@ -438,7 +438,7 @@ public void Seed() People.AddRange(teachers); People.AddRange(students); - SaveChanges(); + return SaveChangesAsync(); } public abstract class Person9038 @@ -481,7 +481,7 @@ public class PersonFamily9038 [ConditionalFact] public virtual async Task Include_with_order_by_on_interface_key() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using (var context = contextFactory.CreateContext()) { var query = context.Parents.Include(p => p.Children).OrderBy(p => p.Id).ToList(); @@ -498,7 +498,7 @@ private class Context10635(DbContextOptions options) : DbContext(options) public DbSet Parents { get; set; } public DbSet Children { get; set; } - public void Seed() + public Task SeedAsync() { var c11 = new Child10635 { Name = "Child111" }; var c12 = new Child10635 { Name = "Child112" }; @@ -509,7 +509,7 @@ public void Seed() var p2 = new Parent10635 { Name = "Parent2", Children = new[] { c21 } }; Parents.AddRange(p1, p2); Children.AddRange(c11, c12, c13, c21); - SaveChanges(); + return SaveChangesAsync(); } public interface IEntity10635 @@ -539,7 +539,7 @@ public class Child10635 : IEntity10635 [ConditionalFact] public virtual async Task Collection_without_setter_materialized_correctly() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var query1 = context.Blogs .Select( @@ -589,7 +589,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) modelBuilder.Entity(); } - public void Seed() + public Task SeedAsync() { var p111 = new Post { Name = "P111" }; var p112 = new Post { Name = "P112" }; @@ -618,7 +618,7 @@ public void Seed() Blogs.AddRange(b1, b2); Posts.AddRange(p111, p112, p121, p122, p123, p131, p211, p212, p221, p222, p223, p231); - SaveChanges(); + return SaveChangesAsync(); } public class Blog @@ -668,7 +668,7 @@ public class CustomCollection : List; [ConditionalFact] public virtual async Task Include_collection_works_when_defined_on_intermediate_type() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using (var context = contextFactory.CreateContext()) { @@ -698,7 +698,7 @@ protected class Context11944(DbContextOptions options) : DbContext(options) protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity().HasMany(s => s.Students).WithOne(s => s.School); - public void Seed() + public Task SeedAsync() { var student1 = new Student(); var student2 = new Student(); @@ -709,7 +709,7 @@ public void Seed() Schools.AddRange(school); ElementarySchools.Add(elementarySchool); - SaveChanges(); + return SaveChangesAsync(); } public class Student @@ -823,7 +823,7 @@ public class Activity [ConditionalFact] public virtual async Task Include_collection_with_OfType_base() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using (var context = contextFactory.CreateContext()) { @@ -855,7 +855,7 @@ private class Context12582(DbContextOptions options) : DbContext(options) public DbSet Employees { get; set; } public DbSet Devices { get; set; } - public void Seed() + public Task SeedAsync() { var d1 = new EmployeeDevice { Device = "d1" }; var d2 = new EmployeeDevice { Device = "d2" }; @@ -863,7 +863,7 @@ public void Seed() Devices.AddRange(d1, d2); Employees.Add(e); - SaveChanges(); + return SaveChangesAsync(); } public interface IEmployee @@ -899,7 +899,7 @@ public class EmployeeDevice : IEmployeeDevice [ConditionalFact] public virtual async Task Correlated_collection_correctly_associates_entities_with_byte_array_keys() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var query = from blog in context.Blogs select new @@ -917,11 +917,11 @@ private class Context12748(DbContextOptions options) : DbContext(options) public DbSet Blogs { get; set; } public DbSet Comments { get; set; } - public void Seed() + public Task SeedAsync() { Blogs.Add(new Blog { Name = Encoding.UTF8.GetBytes("Awesome Blog") }); Comments.Add(new Comment { BlogName = Encoding.UTF8.GetBytes("Awesome Blog") }); - SaveChanges(); + return SaveChangesAsync(); } public class Blog @@ -1201,7 +1201,7 @@ public enum IllustrationState [ConditionalFact] public virtual async Task Cycles_in_auto_include() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using (var context = contextFactory.CreateContext()) { var principals = context.Set().ToList(); @@ -1279,7 +1279,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) modelBuilder.Entity().Navigation(e => e.As).AutoInclude(); } - public void Seed() + public Task SeedAsync() { Add(new PrincipalOneToOne { Dependent = new DependentOneToOne() }); Add( @@ -1288,7 +1288,7 @@ public void Seed() Dependents = [new(), new()] }); - SaveChanges(); + return SaveChangesAsync(); } public class PrincipalOneToOne @@ -1620,7 +1620,7 @@ public class MovieEntity [MemberData(nameof(IsAsyncData))] public virtual async Task Count_member_over_IReadOnlyCollection_works(bool async) { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var query = context.Authors @@ -1638,7 +1638,7 @@ protected class Context26433(DbContextOptions options) : DbContext(options) public DbSet Books { get; set; } public DbSet Authors { get; set; } - public void Seed() + public Task SeedAsync() { base.Add( new Author @@ -1653,7 +1653,7 @@ public void Seed() } }); - SaveChanges(); + return SaveChangesAsync(); } public class Author diff --git a/test/EFCore.Specification.Tests/Query/AdHocQueryFiltersQueryTestBase.cs b/test/EFCore.Specification.Tests/Query/AdHocQueryFiltersQueryTestBase.cs index b28ffffdcac..c9cd6ab37f2 100644 --- a/test/EFCore.Specification.Tests/Query/AdHocQueryFiltersQueryTestBase.cs +++ b/test/EFCore.Specification.Tests/Query/AdHocQueryFiltersQueryTestBase.cs @@ -15,7 +15,7 @@ protected override string StoreName [ConditionalFact] public virtual async Task Query_filter_with_contains_evaluates_correctly() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var result = context.Entities.ToList(); Assert.Single(result); @@ -30,12 +30,12 @@ protected class Context10295(DbContextOptions options) : DbContext(options) protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity().HasQueryFilter(x => !_ids.Contains(x.Id)); - public void Seed() + public Task SeedAsync() { var e1 = new MyEntity10295 { Name = "Name1" }; var e2 = new MyEntity10295 { Name = "Name2" }; Entities.AddRange(e1, e2); - SaveChanges(); + return SaveChangesAsync(); } public class MyEntity10295 @@ -52,7 +52,7 @@ public class MyEntity10295 [ConditionalFact] public virtual async Task MultiContext_query_filter_test() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using (var context = contextFactory.CreateContext()) { @@ -75,7 +75,7 @@ protected class FilterContextBase10301(DbContextOptions options) : DbContext(opt protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity().HasQueryFilter(e => e.SomeValue == Tenant); - public void Seed() + public Task SeedAsync() { AddRange( new Blog10301 { SomeValue = 1 }, @@ -83,7 +83,7 @@ public void Seed() new Blog10301 { SomeValue = 2 } ); - SaveChanges(); + return SaveChangesAsync(); } public class Blog10301 @@ -163,7 +163,7 @@ public class Definition12170 [ConditionalFact] public virtual async Task Query_filter_with_pk_fk_optimization() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); context.Entities.Select( s => @@ -185,12 +185,12 @@ protected class Context13517(DbContextOptions options) : DbContext(options) protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity().HasQueryFilter(f => f.Public); - public void Seed() + public Task SeedAsync() { var refEntity = new RefEntity13517 { Public = false }; RefEntities.Add(refEntity); Entities.Add(new Entity13517 { RefEntity = refEntity }); - SaveChanges(); + return SaveChangesAsync(); } public class Entity13517 @@ -227,7 +227,7 @@ public class RefEntityDto13517 [ConditionalFact] public virtual async Task Self_reference_in_query_filter_works() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using (var context = contextFactory.CreateContext()) { @@ -245,7 +245,12 @@ public virtual async Task Self_reference_in_query_filter_works() protected class Context17253(DbContextOptions options) : DbContext(options) { public DbSet EntitiesWithQueryFilterSelfReference { get; set; } - public DbSet EntitiesReferencingEntityWithQueryFilterSelfReference { get; set; } + + public DbSet EntitiesReferencingEntityWithQueryFilterSelfReference + { + get; + set; + } public DbSet EntitiesWithQueryFilterCycle1 { get; set; } public DbSet EntitiesWithQueryFilterCycle2 { get; set; } @@ -262,18 +267,21 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) modelBuilder.Entity().HasQueryFilter(e => EntitiesWithQueryFilterCycle1.Any()); } - public void Seed() + public Task SeedAsync() { EntitiesWithQueryFilterSelfReference.Add( new EntityWithQueryFilterSelfReference17253 { Name = "EntityWithQueryFilterSelfReference" }); EntitiesReferencingEntityWithQueryFilterSelfReference.Add( - new EntityReferencingEntityWithQueryFilterSelfReference17253 { Name = "EntityReferencingEntityWithQueryFilterSelfReference" }); + new EntityReferencingEntityWithQueryFilterSelfReference17253 + { + Name = "EntityReferencingEntityWithQueryFilterSelfReference" + }); EntitiesWithQueryFilterCycle1.Add(new EntityWithQueryFilterCycle17253_1 { Name = "EntityWithQueryFilterCycle1_1" }); EntitiesWithQueryFilterCycle2.Add(new EntityWithQueryFilterCycle17253_2 { Name = "EntityWithQueryFilterCycle2_1" }); EntitiesWithQueryFilterCycle3.Add(new EntityWithQueryFilterCycle17253_3 { Name = "EntityWithQueryFilterCycle3_1" }); - SaveChanges(); + return SaveChangesAsync(); } public class EntityWithQueryFilterSelfReference17253 @@ -314,7 +322,7 @@ public class EntityWithQueryFilterCycle17253_3 [ConditionalFact] public virtual async Task Invoke_inside_query_filter_gets_correctly_evaluated_during_translation() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); context.TenantId = 1; @@ -356,7 +364,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) entityType.SetQueryFilter(updatedQueryFilter); } - public void Seed() + public Task SeedAsync() { var e1 = new MyEntity18510 { Name = "e1", TenantId = 1 }; var e2 = new MyEntity18510 { Name = "e2", TenantId = 2 }; @@ -364,7 +372,7 @@ public void Seed() var e4 = new MyEntity18510 { Name = "Foo", TenantId = 2 }; Entities.AddRange(e1, e2, e3, e4); - SaveChanges(); + return SaveChangesAsync(); } public class MyEntity18510 @@ -414,7 +422,7 @@ public class User18759 [ConditionalFact] public virtual async Task GroupJoin_SelectMany_gets_flattened() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using (var context = contextFactory.CreateContext()) { var query = context.CustomerFilters.ToList(); @@ -470,7 +478,7 @@ from cm in g.DefaultIfEmpty() #pragma warning restore CS0618 // Type or member is obsolete } - public void Seed() + public Task SeedAsync() { var customer1 = new Customer19708 { Name = "First" }; var customer2 = new Customer19708 { Name = "Second" }; @@ -483,7 +491,7 @@ public void Seed() AddRange(customer1, customer2, customer3); AddRange(customerMembership1, customerMembership2, customerMembership3); - SaveChanges(); + return SaveChangesAsync(); } private Expression>> Build_Customers_Sql_View_InMemory() @@ -543,7 +551,7 @@ public class CustomerView19708 [MemberData(nameof(IsAsyncData))] public virtual async Task IsDeleted_query_filter_with_conversion_to_int_works(bool async) { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var query = context.Suppliers.Include(s => s.Location).OrderBy(s => s.Name); @@ -573,7 +581,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) modelBuilder.Entity().HasQueryFilter(l => !l.IsDeleted); } - public void Seed() + public Task SeedAsync() { var activeAddress = new Location { Address = "Active address", IsDeleted = false }; var deletedAddress = new Location { Address = "Deleted address", IsDeleted = true }; @@ -596,7 +604,7 @@ public void Seed() AddRange(activeAddress, deletedAddress); AddRange(activeSupplier1, activeSupplier2, activeSupplier3, deletedSupplier); - SaveChanges(); + return SaveChangesAsync(); } } diff --git a/test/EFCore.Specification.Tests/Query/ComplexNavigationsQueryFixtureBase.cs b/test/EFCore.Specification.Tests/Query/ComplexNavigationsQueryFixtureBase.cs index 91c507cf6e4..d81b7c92023 100644 --- a/test/EFCore.Specification.Tests/Query/ComplexNavigationsQueryFixtureBase.cs +++ b/test/EFCore.Specification.Tests/Query/ComplexNavigationsQueryFixtureBase.cs @@ -470,8 +470,8 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con modelBuilder.Entity().HasOne(g => g.Language); } - protected override void Seed(ComplexNavigationsContext context) - => ComplexNavigationsData.Seed(context); + protected override Task SeedAsync(ComplexNavigationsContext context) + => ComplexNavigationsData.SeedAsync(context); public override DbContextOptionsBuilder AddOptions(DbContextOptionsBuilder builder) => base.AddOptions(builder).ConfigureWarnings( diff --git a/test/EFCore.Specification.Tests/Query/ComplexNavigationsSharedTypeQueryFixtureBase.cs b/test/EFCore.Specification.Tests/Query/ComplexNavigationsSharedTypeQueryFixtureBase.cs index ec06eb090ff..07a1acefe6f 100644 --- a/test/EFCore.Specification.Tests/Query/ComplexNavigationsSharedTypeQueryFixtureBase.cs +++ b/test/EFCore.Specification.Tests/Query/ComplexNavigationsSharedTypeQueryFixtureBase.cs @@ -235,8 +235,8 @@ protected virtual void Configure(OwnedNavigationBuilder l4) .IsRequired(false); } - protected override void Seed(ComplexNavigationsContext context) - => ComplexNavigationsData.Seed(context, tableSplitting: true); + protected override Task SeedAsync(ComplexNavigationsContext context) + => ComplexNavigationsData.SeedAsync(context, tableSplitting: true); private class ComplexNavigationsWeakSetExtractor(DbContext context) : ISetSource { diff --git a/test/EFCore.Specification.Tests/Query/ComplexTypeQueryFixtureBase.cs b/test/EFCore.Specification.Tests/Query/ComplexTypeQueryFixtureBase.cs index e860f418e69..7207c5fa501 100644 --- a/test/EFCore.Specification.Tests/Query/ComplexTypeQueryFixtureBase.cs +++ b/test/EFCore.Specification.Tests/Query/ComplexTypeQueryFixtureBase.cs @@ -22,8 +22,8 @@ public override PoolableDbContext CreateContext() public override DbContextOptionsBuilder AddOptions(DbContextOptionsBuilder builder) => base.AddOptions(builder).ConfigureWarnings(wcb => wcb.Throw()); - protected override void Seed(PoolableDbContext context) - => ComplexTypeData.Seed(context); + protected override Task SeedAsync(PoolableDbContext context) + => ComplexTypeData.SeedAsync(context); protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext context) { @@ -144,7 +144,7 @@ public ISetSource GetExpectedData() { typeof(CountryStruct), (CountryStruct e, CountryStruct a) => { - AssertCountryStruct(e, e); + AssertCountryStruct(e, e); } }, { diff --git a/test/EFCore.Specification.Tests/Query/CompositeKeysQueryFixtureBase.cs b/test/EFCore.Specification.Tests/Query/CompositeKeysQueryFixtureBase.cs index 4e572d6b3e3..f3e1a7e528f 100644 --- a/test/EFCore.Specification.Tests/Query/CompositeKeysQueryFixtureBase.cs +++ b/test/EFCore.Specification.Tests/Query/CompositeKeysQueryFixtureBase.cs @@ -363,8 +363,8 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con .IsRequired(false); } - protected override void Seed(CompositeKeysContext context) - => CompositeKeysData.Seed(context); + protected override Task SeedAsync(CompositeKeysContext context) + => CompositeKeysData.SeedAsync(context); public override DbContextOptionsBuilder AddOptions(DbContextOptionsBuilder builder) => base.AddOptions(builder).ConfigureWarnings( diff --git a/test/EFCore.Specification.Tests/Query/Ef6GroupByTestBase.cs b/test/EFCore.Specification.Tests/Query/Ef6GroupByTestBase.cs index f7eae535e38..1b719b54393 100644 --- a/test/EFCore.Specification.Tests/Query/Ef6GroupByTestBase.cs +++ b/test/EFCore.Specification.Tests/Query/Ef6GroupByTestBase.cs @@ -797,8 +797,20 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con }); } - protected override void Seed(ArubaContext context) - => new ArubaData(context); + protected override Task SeedAsync(ArubaContext context) + { + var data = new ArubaData(); + context.AddRange(data.ArubaOwners); + context.AddRange(data.NumbersForLinq); + context.AddRange(data.ProductsForLinq); + context.AddRange(data.CustomersForLinq); + context.AddRange(data.OrdersForLinq); + context.AddRange(data.People); + context.AddRange(data.Feet); + context.AddRange(data.Shoes); + + return context.SaveChangesAsync(); + } public virtual ISetSource GetExpectedData() { @@ -986,7 +998,7 @@ public class ArubaData : ISetSource public IReadOnlyList Feet { get; } public IReadOnlyList Shoes { get; } - public ArubaData(ArubaContext context = null) + public ArubaData() { ArubaOwners = CreateArubaOwners(); NumbersForLinq = CreateNumbersForLinq(); @@ -996,19 +1008,6 @@ public ArubaData(ArubaContext context = null) People = CreatePeople(); Feet = CreateFeet(People); Shoes = CreateShoes(People); - - if (context != null) - { - context.AddRange(ArubaOwners); - context.AddRange(NumbersForLinq); - context.AddRange(ProductsForLinq); - context.AddRange(CustomersForLinq); - context.AddRange(OrdersForLinq); - context.AddRange(People); - context.AddRange(Feet); - context.AddRange(Shoes); - context.SaveChanges(); - } } public IQueryable Set() diff --git a/test/EFCore.Specification.Tests/Query/FunkyDataQueryTestBase.cs b/test/EFCore.Specification.Tests/Query/FunkyDataQueryTestBase.cs index 30cfe87cf1b..b784d760fe9 100644 --- a/test/EFCore.Specification.Tests/Query/FunkyDataQueryTestBase.cs +++ b/test/EFCore.Specification.Tests/Query/FunkyDataQueryTestBase.cs @@ -608,7 +608,7 @@ public override FunkyDataContext CreateContext() return context; } - protected override void Seed(FunkyDataContext context) - => FunkyDataContext.Seed(context); + protected override Task SeedAsync(FunkyDataContext context) + => FunkyDataContext.SeedAsync(context); } } diff --git a/test/EFCore.Specification.Tests/Query/GearsOfWarQueryFixtureBase.cs b/test/EFCore.Specification.Tests/Query/GearsOfWarQueryFixtureBase.cs index de37c89b6d5..acc1005dfd9 100644 --- a/test/EFCore.Specification.Tests/Query/GearsOfWarQueryFixtureBase.cs +++ b/test/EFCore.Specification.Tests/Query/GearsOfWarQueryFixtureBase.cs @@ -367,8 +367,8 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con modelBuilder.Entity().Property(l => l.Id).ValueGeneratedNever(); } - protected override void Seed(GearsOfWarContext context) - => GearsOfWarContext.Seed(context); + protected override Task SeedAsync(GearsOfWarContext context) + => GearsOfWarContext.SeedAsync(context); public override DbContextOptionsBuilder AddOptions(DbContextOptionsBuilder builder) => base.AddOptions(builder).ConfigureWarnings( diff --git a/test/EFCore.Specification.Tests/Query/IncludeOneToOneTestBase.cs b/test/EFCore.Specification.Tests/Query/IncludeOneToOneTestBase.cs index 2e161b86cba..5e7ffac6e56 100644 --- a/test/EFCore.Specification.Tests/Query/IncludeOneToOneTestBase.cs +++ b/test/EFCore.Specification.Tests/Query/IncludeOneToOneTestBase.cs @@ -222,7 +222,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con .HasForeignKey("PersonId")); } - protected override void Seed(PoolableDbContext context) + protected override Task SeedAsync(PoolableDbContext context) { var address1 = new Address { Street = "3 Dragons Way", City = "Meereen" }; var address2 = new Address { Street = "42 Castle Black", City = "The Wall" }; @@ -262,7 +262,7 @@ protected override void Seed(PoolableDbContext context) context.Set().AddRange(address21, address22, address23); - context.SaveChanges(); + return context.SaveChangesAsync(); } } diff --git a/test/EFCore.Specification.Tests/Query/InheritanceQueryFixtureBase.cs b/test/EFCore.Specification.Tests/Query/InheritanceQueryFixtureBase.cs index 295a12437da..4bcd243ae37 100644 --- a/test/EFCore.Specification.Tests/Query/InheritanceQueryFixtureBase.cs +++ b/test/EFCore.Specification.Tests/Query/InheritanceQueryFixtureBase.cs @@ -439,6 +439,6 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con } } - protected override void Seed(InheritanceContext context) - => InheritanceContext.Seed(context, UseGeneratedKeys); + protected override Task SeedAsync(InheritanceContext context) + => InheritanceContext.SeedAsync(context, UseGeneratedKeys); } diff --git a/test/EFCore.Specification.Tests/Query/InheritanceQueryTestBase.cs b/test/EFCore.Specification.Tests/Query/InheritanceQueryTestBase.cs index 4af3d4f1213..d179e72403f 100644 --- a/test/EFCore.Specification.Tests/Query/InheritanceQueryTestBase.cs +++ b/test/EFCore.Specification.Tests/Query/InheritanceQueryTestBase.cs @@ -288,15 +288,14 @@ public virtual Task Discriminator_used_when_projection_over_of_type(bool async) ss => ss.Set().OfType().Select(k => k.FoundOn)); [ConditionalFact] - public virtual void Can_insert_update_delete() + public virtual Task Can_insert_update_delete() { int? eagleId = null; - TestHelpers.ExecuteWithStrategyInTransaction( + return TestHelpers.ExecuteWithStrategyInTransactionAsync( CreateContext, - UseTransaction, - context => + UseTransaction, async context => { - eagleId = context.Set().AsNoTracking().Single(e => e.Species == "Aquila chrysaetos canadensis").Id; + eagleId = (await context.Set().AsNoTracking().SingleAsync(e => e.Species == "Aquila chrysaetos canadensis")).Id; var kiwi = new Kiwi { @@ -306,31 +305,28 @@ public virtual void Can_insert_update_delete() FoundOn = Island.North }; - var nz = context.Set().Single(c => c.Id == 1); + var nz = await context.Set().SingleAsync(c => c.Id == 1); nz.Animals.Add(kiwi); - context.SaveChanges(); - }, - context => + await context.SaveChangesAsync(); + }, async context => { - var kiwi = context.Set().Single(k => k.Species.EndsWith("owenii")); + var kiwi = await context.Set().SingleAsync(k => k.Species.EndsWith("owenii")); kiwi.EagleId = eagleId; - context.SaveChanges(); - }, - context => + await context.SaveChangesAsync(); + }, async context => { - var kiwi = context.Set().Single(k => k.Species.EndsWith("owenii")); + var kiwi = await context.Set().SingleAsync(k => k.Species.EndsWith("owenii")); context.Set().Remove(kiwi); - context.SaveChanges(); - }, - context => + await context.SaveChangesAsync(); + }, async context => { - var count = context.Set().Count(k => k.Species.EndsWith("owenii")); + var count = await context.Set().CountAsync(k => k.Species.EndsWith("owenii")); Assert.Equal(0, count); }); @@ -388,10 +384,10 @@ public virtual Task Union_entity_equality(bool async) .Where(b => b == null)); [ConditionalFact] - public virtual void Setting_foreign_key_to_a_different_type_throws() + public virtual async Task Setting_foreign_key_to_a_different_type_throws() { using var context = CreateContext(); - var kiwi = context.Set().Single(); + var kiwi = await context.Set().SingleAsync(); var eagle = new Eagle { @@ -401,7 +397,7 @@ public virtual void Setting_foreign_key_to_a_different_type_throws() EagleId = kiwi.Id }; - context.Add(eagle); + await context.AddAsync(eagle); // No fixup, because no principal with this key of the correct type is loaded. Assert.Empty(eagle.Prey); @@ -409,7 +405,7 @@ public virtual void Setting_foreign_key_to_a_different_type_throws() if (EnforcesFkConstraints) { // Relational database throws due to constraint violation - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(async () => await context.SaveChangesAsync()); } } @@ -421,7 +417,7 @@ public virtual Task Byte_enum_value_constant_used_in_projection(bool async) ss => ss.Set().Select(k => k.IsFlightless ? Island.North : Island.South)); [ConditionalFact] - public virtual void Member_access_on_intermediate_type_works() + public virtual async Task Member_access_on_intermediate_type_works() { using var context = CreateContext(); var query = context.Set().Select(k => new Kiwi { Name = k.Name }); @@ -436,7 +432,7 @@ public virtual void Member_access_on_intermediate_type_works() query = query.Provider.CreateQuery(expression); - var result = query.ToList(); + var result = await query.ToListAsync(); var kiwi = Assert.Single(result); Assert.Equal("Great spotted kiwi", kiwi.Name); diff --git a/test/EFCore.Specification.Tests/Query/InheritanceRelationshipsQueryFixtureBase.cs b/test/EFCore.Specification.Tests/Query/InheritanceRelationshipsQueryFixtureBase.cs index f1600dff34f..34b444ddc7f 100644 --- a/test/EFCore.Specification.Tests/Query/InheritanceRelationshipsQueryFixtureBase.cs +++ b/test/EFCore.Specification.Tests/Query/InheritanceRelationshipsQueryFixtureBase.cs @@ -563,8 +563,8 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con .IsRequired(false); } - protected override void Seed(InheritanceRelationshipsContext context) - => InheritanceRelationshipsContext.Seed(context); + protected override Task SeedAsync(InheritanceRelationshipsContext context) + => InheritanceRelationshipsContext.SeedAsync(context); public override InheritanceRelationshipsContext CreateContext() { diff --git a/test/EFCore.Specification.Tests/Query/ManyToManyFieldsQueryFixtureBase.cs b/test/EFCore.Specification.Tests/Query/ManyToManyFieldsQueryFixtureBase.cs index d0e5bd12f3c..b241d1129a3 100644 --- a/test/EFCore.Specification.Tests/Query/ManyToManyFieldsQueryFixtureBase.cs +++ b/test/EFCore.Specification.Tests/Query/ManyToManyFieldsQueryFixtureBase.cs @@ -400,9 +400,9 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con public virtual bool UseGeneratedKeys => false; - protected override void Seed(ManyToManyContext context) + protected override Task SeedAsync(ManyToManyContext context) { new ManyToManyData(context, UseGeneratedKeys); - context.SaveChanges(); + return context.SaveChangesAsync(); } } diff --git a/test/EFCore.Specification.Tests/Query/ManyToManyQueryFixtureBase.cs b/test/EFCore.Specification.Tests/Query/ManyToManyQueryFixtureBase.cs index c50b88667e8..51c07ff117c 100644 --- a/test/EFCore.Specification.Tests/Query/ManyToManyQueryFixtureBase.cs +++ b/test/EFCore.Specification.Tests/Query/ManyToManyQueryFixtureBase.cs @@ -644,9 +644,9 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con public virtual bool UseGeneratedKeys => false; - protected override void Seed(ManyToManyContext context) + protected override Task SeedAsync(ManyToManyContext context) { new ManyToManyData(context, UseGeneratedKeys); - context.SaveChanges(); + return context.SaveChangesAsync(); } } diff --git a/test/EFCore.Specification.Tests/Query/NonSharedPrimitiveCollectionsQueryTestBase.cs b/test/EFCore.Specification.Tests/Query/NonSharedPrimitiveCollectionsQueryTestBase.cs index faea1addfa3..6357dfe2c77 100644 --- a/test/EFCore.Specification.Tests/Query/NonSharedPrimitiveCollectionsQueryTestBase.cs +++ b/test/EFCore.Specification.Tests/Query/NonSharedPrimitiveCollectionsQueryTestBase.cs @@ -128,7 +128,7 @@ public virtual async Task Column_with_custom_converter() context.AddRange( new TestEntity { Id = 1, Ints = [1, 2, 3] }, new TestEntity { Id = 2, Ints = [1, 2, 4] }); - context.SaveChanges(); + return context.SaveChangesAsync(); }); await using var context = contextFactory.CreateContext(); @@ -157,7 +157,7 @@ public virtual async Task Parameter_with_inferred_value_converter() entry1.Property("PropertyWithValueConverter").CurrentValue = new IntWrapper(8); var entry2 = context.Add(new TestEntity { Id = 2 }); entry2.Property("PropertyWithValueConverter").CurrentValue = new IntWrapper(9); - context.SaveChanges(); + return context.SaveChangesAsync(); }); await using var context = contextFactory.CreateContext(); @@ -182,7 +182,7 @@ public virtual async Task Constant_with_inferred_value_converter() entry1.Property("PropertyWithValueConverter").CurrentValue = new IntWrapper(8); var entry2 = context.Add(new TestEntity { Id = 2 }); entry2.Property("PropertyWithValueConverter").CurrentValue = new IntWrapper(9); - context.SaveChanges(); + return context.SaveChangesAsync(); }); await using var context = contextFactory.CreateContext(); @@ -208,7 +208,7 @@ public virtual async Task Inline_collection_in_query_filter() context.AddRange( new TestEntity { Id = 1 }, new TestEntity { Id = 2 }); - context.SaveChanges(); + return context.SaveChangesAsync(); }); await using var context = contextFactory.CreateContext(); @@ -246,7 +246,7 @@ protected async Task TestArray( array2.SetValue(value2, 1); context.Entry(instance2).Property("SomeArray").CurrentValue = array2; - context.SaveChanges(); + return context.SaveChangesAsync(); }); await using var context = contextFactory.CreateContext(); diff --git a/test/EFCore.Specification.Tests/Query/NorthwindFunctionsQueryTestBase.cs b/test/EFCore.Specification.Tests/Query/NorthwindFunctionsQueryTestBase.cs index 61e9dc21901..7d309d55a20 100644 --- a/test/EFCore.Specification.Tests/Query/NorthwindFunctionsQueryTestBase.cs +++ b/test/EFCore.Specification.Tests/Query/NorthwindFunctionsQueryTestBase.cs @@ -331,7 +331,7 @@ public virtual async Task String_compare_with_parameter(bool async) Customer customer = null; using (var context = CreateContext()) { - customer = context.Customers.Single(c => c.CustomerID == "AROUT"); + customer = await context.Customers.SingleAsync(c => c.CustomerID == "AROUT"); } ClearLog(); @@ -493,7 +493,7 @@ public virtual async Task String_compare_to_with_parameter(bool async) Customer customer = null; using (var context = CreateContext()) { - customer = context.Customers.Single(x => x.CustomerID == "AROUT"); + customer = await context.Customers.SingleAsync(x => x.CustomerID == "AROUT"); } ClearLog(); diff --git a/test/EFCore.Specification.Tests/Query/NorthwindMiscellaneousQueryTestBase.cs b/test/EFCore.Specification.Tests/Query/NorthwindMiscellaneousQueryTestBase.cs index 565e4062058..a100eae5b3a 100644 --- a/test/EFCore.Specification.Tests/Query/NorthwindMiscellaneousQueryTestBase.cs +++ b/test/EFCore.Specification.Tests/Query/NorthwindMiscellaneousQueryTestBase.cs @@ -1706,7 +1706,8 @@ public virtual Task Where_query_composition_entity_equality_multiple_elements_Si => AssertQuery( async, ss => from e1 in ss.Set() - where ss.Set().OrderBy(e2 => e2.EmployeeID).SingleOrDefault(e2 => e2.EmployeeID != e1.ReportsTo) == new Employee { EmployeeID = 1 } + where ss.Set().OrderBy(e2 => e2.EmployeeID).SingleOrDefault(e2 => e2.EmployeeID != e1.ReportsTo) + == new Employee { EmployeeID = 1 } select e1, ss => from e1 in ss.Set() where ss.Set().OrderBy(e2 => e2.EmployeeID).FirstOrDefault(e2 => e2.EmployeeID != e1.ReportsTo).EmployeeID == 1 @@ -2948,17 +2949,17 @@ orderby o.OrderID public virtual async Task Throws_on_concurrent_query_list(bool async) { using var context = CreateContext(); - context.Database.EnsureCreatedResiliently(); + await context.Database.EnsureCreatedResilientlyAsync(); using var synchronizationEvent = new ManualResetEventSlim(false); using var blockingSemaphore = new SemaphoreSlim(0); var blockingTask = Task.Run( - () => + async () => { try { - context.Customers.Select( - c => Process(c, synchronizationEvent, blockingSemaphore)).ToList(); + await context.Customers.Select( + c => Process(c, synchronizationEvent, blockingSemaphore)).ToListAsync(); } finally { @@ -2989,17 +2990,17 @@ public virtual async Task Throws_on_concurrent_query_list(bool async) public virtual async Task Throws_on_concurrent_query_first(bool async) { using var context = CreateContext(); - context.Database.EnsureCreatedResiliently(); + await context.Database.EnsureCreatedResilientlyAsync(); using var synchronizationEvent = new ManualResetEventSlim(false); using var blockingSemaphore = new SemaphoreSlim(0); var blockingTask = Task.Run( - () => + async () => { try { - context.Customers.Select( - c => Process(c, synchronizationEvent, blockingSemaphore)).ToList(); + await context.Customers.Select( + c => Process(c, synchronizationEvent, blockingSemaphore)).ToListAsync(); } finally { @@ -5696,7 +5697,7 @@ await AssertQuery( .Select(g => new { g.Key, MaxTimestamp = g.Select(e => e.Order.OrderDate).Max() }) .OrderBy(x => x.MaxTimestamp) .Select(x => x)); - } + } [ConditionalTheory] [MemberData(nameof(IsAsyncData))] @@ -5713,7 +5714,7 @@ public virtual Task Contains_over_concatenated_columns_with_different_sizes(bool [MemberData(nameof(IsAsyncData))] public virtual Task Contains_over_concatenated_column_and_constant(bool async) { - var data = new[] { "ALFKI" + "SomeConstant", "ANATR" + "SomeConstant", "ALFKI" + "X"}; + var data = new[] { "ALFKI" + "SomeConstant", "ANATR" + "SomeConstant", "ALFKI" + "X" }; return AssertQuery( async, @@ -5724,7 +5725,7 @@ public virtual Task Contains_over_concatenated_column_and_constant(bool async) [MemberData(nameof(IsAsyncData))] public virtual Task Contains_over_concatenated_column_and_parameter(bool async) { - var data = new[] { "ALFKI" + "SomeVariable", "ANATR" + "SomeVariable", "ALFKI" + "X" }; + var data = new[] { "ALFKI" + "SomeVariable", "ANATR" + "SomeVariable", "ALFKI" + "X" }; var someVariable = "SomeVariable"; return AssertQuery( @@ -5748,7 +5749,7 @@ public virtual Task Contains_over_concatenated_parameter_and_constant(bool async [MemberData(nameof(IsAsyncData))] public virtual Task Contains_over_concatenated_columns_both_fixed_length(bool async) { - var data = new[] { "ALFKIALFKI", "ALFKI", "ANATR" + "Ana Trujillo Emparedados y helados", "ANATR" + "ANATR"}; + var data = new[] { "ALFKIALFKI", "ALFKI", "ANATR" + "Ana Trujillo Emparedados y helados", "ANATR" + "ANATR" }; return AssertQuery( async, diff --git a/test/EFCore.Specification.Tests/Query/NorthwindQueryFixtureBase.cs b/test/EFCore.Specification.Tests/Query/NorthwindQueryFixtureBase.cs index 469b682a7d5..a254eee36d3 100644 --- a/test/EFCore.Specification.Tests/Query/NorthwindQueryFixtureBase.cs +++ b/test/EFCore.Specification.Tests/Query/NorthwindQueryFixtureBase.cs @@ -276,9 +276,6 @@ protected override void ConfigureConventions(ModelConfigurationBuilder configura protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext context) => new TModelCustomizer().Customize(modelBuilder, context); - protected override void Seed(NorthwindContext context) - => NorthwindData.Seed(context); - protected override Task SeedAsync(NorthwindContext context) => NorthwindData.SeedAsync(context); diff --git a/test/EFCore.Specification.Tests/Query/NorthwindWhereQueryTestBase.cs b/test/EFCore.Specification.Tests/Query/NorthwindWhereQueryTestBase.cs index 2dbfe91870a..5805fb6fa45 100644 --- a/test/EFCore.Specification.Tests/Query/NorthwindWhereQueryTestBase.cs +++ b/test/EFCore.Specification.Tests/Query/NorthwindWhereQueryTestBase.cs @@ -1651,7 +1651,7 @@ public virtual Task Where_subquery_FirstOrDefault_compared_to_entity(bool async) c => c.Orders.OrderBy(o => o.OrderID).FirstOrDefault() == new Order { OrderID = 10276 }), ss => ss.Set().Where( - c => c.Orders.OrderBy(o => o.OrderID).FirstOrDefault().OrderID == 10276 )); + c => c.Orders.OrderBy(o => o.OrderID).FirstOrDefault().OrderID == 10276)); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] diff --git a/test/EFCore.Specification.Tests/Query/NullKeysTestBase.cs b/test/EFCore.Specification.Tests/Query/NullKeysTestBase.cs index d5678bf4454..4e6ba8f5ae6 100644 --- a/test/EFCore.Specification.Tests/Query/NullKeysTestBase.cs +++ b/test/EFCore.Specification.Tests/Query/NullKeysTestBase.cs @@ -259,7 +259,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con .Property(e => e.Id).ValueGeneratedNever(); } - protected override void Seed(PoolableDbContext context) + protected override Task SeedAsync(PoolableDbContext context) { context.Add( new WithStringKey { Id = "Stereo" }); @@ -340,7 +340,7 @@ protected override void Seed(PoolableDbContext context) context.Add( new WithAllNullableIntFk { Id = 6 }); - context.SaveChanges(); + return context.SaveChangesAsync(); } } } diff --git a/test/EFCore.Specification.Tests/Query/OwnedEntityQueryTestBase.cs b/test/EFCore.Specification.Tests/Query/OwnedEntityQueryTestBase.cs index ea55294722d..189928999a3 100644 --- a/test/EFCore.Specification.Tests/Query/OwnedEntityQueryTestBase.cs +++ b/test/EFCore.Specification.Tests/Query/OwnedEntityQueryTestBase.cs @@ -17,7 +17,7 @@ protected override string StoreName [ConditionalFact] public virtual async Task Include_collection_for_entity_with_owned_type_works() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using (var context = contextFactory.CreateContext()) { @@ -54,7 +54,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) modelBuilder.Entity().OwnsOne(m => m.Details); } - public void Seed() + public Task SeedAsync() { var av = new Actor { Name = "Alicia Vikander", Details = new Details { Info = "Best actress ever" } }; var oi = new Actor { Name = "Oscar Isaac", Details = new Details { Info = "Best actor ever made" } }; @@ -73,7 +73,7 @@ public void Seed() Actors.AddRange(av, oi, dg); Movies.Add(em); - SaveChanges(); + return SaveChangesAsync(); } public class Movie @@ -110,7 +110,7 @@ public virtual async Task Multilevel_owned_entities_determine_correct_nullabilit var contextFactory = await InitializeAsync(); using var context = contextFactory.CreateContext(); await context.AddAsync(new Context13079.BaseEntity()); - context.SaveChanges(); + await context.SaveChangesAsync(); } private class Context13079(DbContextOptions options) : DbContext(options) @@ -150,7 +150,7 @@ public class OwnedSubData [ConditionalFact] public virtual async Task Correlated_subquery_with_owned_navigation_being_compared_to_null_works() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using (var context = contextFactory.CreateContext()) { @@ -189,7 +189,7 @@ private class Context13157(DbContextOptions options) : DbContext(options) protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity
().OwnsOne(x => x.Turnovers); - public void Seed() + public Task SeedAsync() { AddRange( new Partner @@ -201,7 +201,7 @@ public void Seed() } ); - SaveChanges(); + return SaveChangesAsync(); } public class Partner @@ -229,11 +229,12 @@ public class AddressTurnovers [ConditionalFact] public virtual async Task Owned_entity_multiple_level_in_aggregate() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var aggregate = context.Set().OrderByDescending(e => e.Id).FirstOrDefault(); Assert.Equal(10, aggregate.FirstValueObject.SecondValueObjects[0].FourthValueObject.FifthValueObjects[0].AnyValue); - Assert.Equal(20, aggregate.FirstValueObject.SecondValueObjects[0].ThirdValueObjects[0].FourthValueObject.FifthValueObjects[0].AnyValue); + Assert.Equal( + 20, aggregate.FirstValueObject.SecondValueObjects[0].ThirdValueObjects[0].FourthValueObject.FifthValueObjects[0].AnyValue); } protected class Context14911(DbContextOptions options) : DbContext(options) @@ -288,7 +289,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) }); }); - public void Seed() + public Task SeedAsync() { var aggregate = new Aggregate { @@ -302,13 +303,7 @@ public void Seed() new FourthValueObject { FifthValueObjects = [new() { AnyValue = 10 }] }, ThirdValueObjects = [ - new() - { - FourthValueObject = new FourthValueObject - { - FifthValueObjects = [new() { AnyValue = 20 }] - } - } + new() { FourthValueObject = new FourthValueObject { FifthValueObjects = [new() { AnyValue = 20 }] } } ] } ] @@ -316,7 +311,7 @@ public void Seed() }; Set().Add(aggregate); - SaveChanges(); + return SaveChangesAsync(); } public class Aggregate @@ -362,14 +357,13 @@ public class FifthValueObject [MemberData(nameof(IsAsyncData))] public virtual async Task Projecting_correlated_collection_property_for_owned_entity(bool async) { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var query = context.Warehouses.Select( x => new Context18582.WarehouseModel { - WarehouseCode = x.WarehouseCode, - DestinationCountryCodes = x.DestinationCountries.Select(c => c.CountryCode).ToArray() + WarehouseCode = x.WarehouseCode, DestinationCountryCodes = x.DestinationCountries.Select(c => c.CountryCode).ToArray() }).AsNoTracking(); var result = async @@ -385,7 +379,7 @@ private class Context18582(DbContextOptions options) : DbContext(options) { public DbSet Warehouses { get; set; } - public void Seed() + public Task SeedAsync() { Add( new Warehouse @@ -398,7 +392,7 @@ public void Seed() } }); - SaveChanges(); + return SaveChangesAsync(); } protected override void OnModelCreating(ModelBuilder modelBuilder) @@ -437,7 +431,7 @@ public class WarehouseModel [ConditionalFact] public virtual async Task Accessing_scalar_property_in_derived_type_projection_does_not_load_owned_navigations() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var result = context.BaseEntities .Select(b => context.OtherEntities.Where(o => o.OtherEntityData == ((Context19138.SubEntity)b).Data).FirstOrDefault()) @@ -458,12 +452,12 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) modelBuilder.Entity(); } - public void Seed() + public Task SeedAsync() { Add(new OtherEntity { OtherEntityData = "A" }); Add(new SubEntity { Data = "A" }); - SaveChanges(); + return SaveChangesAsync(); } public class BaseEntity @@ -575,7 +569,7 @@ public class Owned [ConditionalFact] public virtual async Task Can_auto_include_navigation_from_model() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using (var context = contextFactory.CreateContext()) { @@ -618,7 +612,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) modelBuilder.Entity().Navigation(e => e.SkipOtherSide).AutoInclude(); } - public void Seed() + public Task SeedAsync() { var joinEntity = new JoinEntity { @@ -636,7 +630,7 @@ public void Seed() AddRange(joinEntity); - SaveChanges(); + return SaveChangesAsync(); } public class Parent @@ -689,7 +683,7 @@ public class Collection [ConditionalFact] public virtual async Task Nested_owned_required_dependents_are_materialized() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var query = context.Set().ToList(); var result = Assert.Single(query); @@ -715,11 +709,11 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) builder.Navigation(x => x.Contact).IsRequired(); }); - public void Seed() + public Task SeedAsync() { Add(new Entity { Id = "1", Contact = new Contact { Address = new Address { Zip = 12345 } } }); - SaveChanges(); + return SaveChangesAsync(); } public class Entity @@ -754,7 +748,10 @@ public virtual async Task OwnsMany_correlated_projection(bool async) var contextFactory = await InitializeAsync(); using var context = contextFactory.CreateContext(); var results = await context.Contacts.Select( - contact => new Context22089.ContactDto { Id = contact.Id, Names = contact.Names.Select(name => new Context22089.NameDto()).ToArray() }) + contact => new Context22089.ContactDto + { + Id = contact.Id, Names = contact.Names.Select(name => new Context22089.NameDto()).ToArray() + }) .ToListAsync(); } @@ -907,7 +904,7 @@ protected MyContext26592Base(DbContextOptions options) public DbSet Companies { get; set; } public DbSet Owners { get; set; } - public void Seed() + public Task SeedAsync() { Add( new Company @@ -929,7 +926,7 @@ public void Seed() } }); - SaveChanges(); + return SaveChangesAsync(); } public class Company diff --git a/test/EFCore.Specification.Tests/Query/PrimitiveCollectionsQueryTestBase.cs b/test/EFCore.Specification.Tests/Query/PrimitiveCollectionsQueryTestBase.cs index 111e2d3fb46..f60fe2f02f6 100644 --- a/test/EFCore.Specification.Tests/Query/PrimitiveCollectionsQueryTestBase.cs +++ b/test/EFCore.Specification.Tests/Query/PrimitiveCollectionsQueryTestBase.cs @@ -932,8 +932,18 @@ public virtual Task Project_primitive_collections_element(bool async) [MemberData(nameof(IsAsyncData))] public virtual Task Nested_contains_with_Lists_and_no_inferred_type_mapping(bool async) { - var ints = new List { 1, 2, 3 }; - var strings = new List { "one", "two", "three" }; + var ints = new List + { + 1, + 2, + 3 + }; + var strings = new List + { + "one", + "two", + "three" + }; // Note that in this query, the outer Contains really has no type mapping, neither for its source (collection parameter), nor // for its item (the conditional expression returns constants). The default type mapping must be applied. @@ -969,8 +979,11 @@ public Func GetContextCreator() protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext context) => modelBuilder.Entity().Property(p => p.Id).ValueGeneratedNever(); - protected override void Seed(PrimitiveCollectionsContext context) - => new PrimitiveArrayData(context); + protected override Task SeedAsync(PrimitiveCollectionsContext context) + { + context.AddRange(new PrimitiveArrayData().PrimitiveArrayEntities); + return context.SaveChangesAsync(); + } public virtual ISetSource GetExpectedData() => _expectedData ??= new PrimitiveArrayData(); @@ -1036,12 +1049,6 @@ public class PrimitiveArrayData : ISetSource public PrimitiveArrayData(PrimitiveCollectionsContext? context = null) { PrimitiveArrayEntities = CreatePrimitiveArrayEntities(); - - if (context != null) - { - context.AddRange(PrimitiveArrayEntities); - context.SaveChanges(); - } } public IQueryable Set() @@ -1094,8 +1101,8 @@ private static IReadOnlyList CreatePrimitiveArrayEnt DateTimes = [ new(2020, 1, 1, 12, 30, 0, DateTimeKind.Utc), - new(2020, 1, 11, 12, 30, 0, DateTimeKind.Utc), - new(2020, 1, 31, 12, 30, 0, DateTimeKind.Utc) + new(2020, 1, 11, 12, 30, 0, DateTimeKind.Utc), + new(2020, 1, 31, 12, 30, 0, DateTimeKind.Utc) ], Bools = [false], Enums = [MyEnum.Value2, MyEnum.Value3], @@ -1117,10 +1124,10 @@ private static IReadOnlyList CreatePrimitiveArrayEnt DateTimes = [ new(2020, 1, 1, 12, 30, 0, DateTimeKind.Utc), - new(2020, 1, 10, 12, 30, 0, DateTimeKind.Utc), - new(2020, 1, 1, 12, 30, 0, DateTimeKind.Utc), - new(2020, 1, 1, 12, 30, 0, DateTimeKind.Utc), - new(2020, 1, 10, 12, 30, 0, DateTimeKind.Utc) + new(2020, 1, 10, 12, 30, 0, DateTimeKind.Utc), + new(2020, 1, 1, 12, 30, 0, DateTimeKind.Utc), + new(2020, 1, 1, 12, 30, 0, DateTimeKind.Utc), + new(2020, 1, 10, 12, 30, 0, DateTimeKind.Utc) ], Bools = [true, false], Enums = [MyEnum.Value1, MyEnum.Value2], @@ -1142,13 +1149,13 @@ private static IReadOnlyList CreatePrimitiveArrayEnt DateTimes = [ new(2020, 1, 1, 12, 30, 0, DateTimeKind.Utc), - new(2020, 1, 11, 12, 30, 0, DateTimeKind.Utc), - new(2020, 1, 1, 12, 30, 0, DateTimeKind.Utc), - new(2020, 1, 11, 12, 30, 0, DateTimeKind.Utc), - new(2020, 1, 31, 12, 30, 0, DateTimeKind.Utc), - new(2020, 1, 1, 12, 30, 0, DateTimeKind.Utc), - new(2020, 1, 31, 12, 30, 0, DateTimeKind.Utc), - new(2020, 1, 31, 12, 30, 0, DateTimeKind.Utc) + new(2020, 1, 11, 12, 30, 0, DateTimeKind.Utc), + new(2020, 1, 1, 12, 30, 0, DateTimeKind.Utc), + new(2020, 1, 11, 12, 30, 0, DateTimeKind.Utc), + new(2020, 1, 31, 12, 30, 0, DateTimeKind.Utc), + new(2020, 1, 1, 12, 30, 0, DateTimeKind.Utc), + new(2020, 1, 31, 12, 30, 0, DateTimeKind.Utc), + new(2020, 1, 31, 12, 30, 0, DateTimeKind.Utc) ], Bools = [false], Enums = [MyEnum.Value2, MyEnum.Value3], diff --git a/test/EFCore.Specification.Tests/Query/QueryFilterFuncletizationFixtureBase.cs b/test/EFCore.Specification.Tests/Query/QueryFilterFuncletizationFixtureBase.cs index c88a23a6bf1..59068ee9028 100644 --- a/test/EFCore.Specification.Tests/Query/QueryFilterFuncletizationFixtureBase.cs +++ b/test/EFCore.Specification.Tests/Query/QueryFilterFuncletizationFixtureBase.cs @@ -11,6 +11,6 @@ protected override string StoreName protected override bool UsePooling => false; - protected override void Seed(QueryFilterFuncletizationContext context) - => QueryFilterFuncletizationContext.SeedData(context); + protected override Task SeedAsync(QueryFilterFuncletizationContext context) + => QueryFilterFuncletizationContext.SeedDataAsync(context); } diff --git a/test/EFCore.Specification.Tests/Query/SharedTypeQueryTestBase.cs b/test/EFCore.Specification.Tests/Query/SharedTypeQueryTestBase.cs index 9bdc16bf260..6a73dc0d5be 100644 --- a/test/EFCore.Specification.Tests/Query/SharedTypeQueryTestBase.cs +++ b/test/EFCore.Specification.Tests/Query/SharedTypeQueryTestBase.cs @@ -15,7 +15,7 @@ protected override string StoreName public virtual async Task Can_use_shared_type_entity_type_in_query_filter(bool async) { var contextFactory = await InitializeAsync( - seed: c => c.Seed()); + seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var query = context.Set(); @@ -28,11 +28,11 @@ public virtual async Task Can_use_shared_type_entity_type_in_query_filter(bool a protected class MyContext24601(DbContextOptions options) : DbContext(options) { - public void Seed() + public Task SeedAsync() { Set>("STET").Add(new Dictionary { ["Value"] = "Maumar" }); - SaveChanges(); + return SaveChangesAsync(); } protected override void OnModelCreating(ModelBuilder modelBuilder) diff --git a/test/EFCore.Specification.Tests/Query/SpatialQueryFixtureBase.cs b/test/EFCore.Specification.Tests/Query/SpatialQueryFixtureBase.cs index 8954bf127b5..a1de203544d 100644 --- a/test/EFCore.Specification.Tests/Query/SpatialQueryFixtureBase.cs +++ b/test/EFCore.Specification.Tests/Query/SpatialQueryFixtureBase.cs @@ -152,6 +152,6 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con }); } - protected override void Seed(SpatialContext context) - => SpatialContext.Seed(context, GeometryFactory); + protected override Task SeedAsync(SpatialContext context) + => SpatialContext.SeedAsync(context, GeometryFactory); } diff --git a/test/EFCore.Specification.Tests/QueryExpressionInterceptionTestBase.cs b/test/EFCore.Specification.Tests/QueryExpressionInterceptionTestBase.cs index 63fa09c27a1..742784525ce 100644 --- a/test/EFCore.Specification.Tests/QueryExpressionInterceptionTestBase.cs +++ b/test/EFCore.Specification.Tests/QueryExpressionInterceptionTestBase.cs @@ -19,7 +19,7 @@ protected QueryExpressionInterceptionTestBase(InterceptionFixtureBase fixture) [InlineData(true, true)] public virtual async Task Intercept_query_passively(bool async, bool inject) { - var (context, interceptor) = CreateContext(inject); + var (context, interceptor) = await CreateContextAsync(inject); using var _ = context; @@ -46,7 +46,7 @@ public virtual async Task Intercept_query_with_multiple_interceptors(bool async, var interceptor3 = new TestQueryExpressionInterceptor(); var interceptor4 = new TestQueryExpressionInterceptor(); - using var context = CreateContext( + using var context = await CreateContextAsync( new IInterceptor[] { new TestQueryExpressionInterceptor(), interceptor1, interceptor2 }, new IInterceptor[] { interceptor3, interceptor4, new TestQueryExpressionInterceptor() }); @@ -77,7 +77,7 @@ public virtual async Task Intercept_query_with_multiple_interceptors(bool async, [InlineData(true, true)] public virtual async Task Intercept_to_change_query_expression(bool async, bool inject) { - var (context, interceptor) = CreateContext(inject); + var (context, interceptor) = await CreateContextAsync(inject); using var _ = context; diff --git a/test/EFCore.Specification.Tests/SaveChangesInterceptionTestBase.cs b/test/EFCore.Specification.Tests/SaveChangesInterceptionTestBase.cs index 518d9238f20..956bcc9a177 100644 --- a/test/EFCore.Specification.Tests/SaveChangesInterceptionTestBase.cs +++ b/test/EFCore.Specification.Tests/SaveChangesInterceptionTestBase.cs @@ -23,7 +23,7 @@ protected SaveChangesInterceptionTestBase(InterceptionFixtureBase fixture) [InlineData(true, true, true)] public virtual async Task Intercept_SaveChanges_passively(bool async, bool inject, bool noAcceptChanges) { - var (context, interceptor) = CreateContext(inject); + var (context, interceptor) = await CreateContextAsync(inject); using var _ = context; @@ -91,7 +91,7 @@ protected class PassiveSaveChangesInterceptor : SaveChangesInterceptorBase; [InlineData(true, true, true)] public virtual async Task Intercept_SaveChanges_to_suppress_save(bool async, bool inject, bool noAcceptChanges) { - var (context, interceptor) = CreateContext(inject); + var (context, interceptor) = await CreateContextAsync(inject); using var _ = context; @@ -177,7 +177,7 @@ public override async ValueTask> SavingChangesAsync( [InlineData(true, true, true)] public virtual async Task Intercept_SaveChanges_to_change_result(bool async, bool inject, bool noAcceptChanges) { - var (context, interceptor) = CreateContext(inject); + var (context, interceptor) = await CreateContextAsync(inject); using var _ = context; @@ -277,7 +277,7 @@ public virtual async Task Intercept_SaveChanges_failed(bool async, bool inject, return; } - var (context, interceptor) = CreateContext(inject); + var (context, interceptor) = await CreateContextAsync(inject); using var _ = context; @@ -379,7 +379,7 @@ public virtual async Task Intercept_to_suppress_concurrency_exception(bool async return; } - var (context, interceptor) = CreateContext(inject); + var (context, interceptor) = await CreateContextAsync(inject); using var _ = context; @@ -486,7 +486,7 @@ public virtual async Task Intercept_SaveChanges_with_multiple_interceptors(bool var interceptor3 = new ResultMutatingSaveChangesInterceptor(); var interceptor4 = new PassiveSaveChangesInterceptor(); - using var context = CreateContext( + using var context = await CreateContextAsync( new IInterceptor[] { new PassiveSaveChangesInterceptor(), interceptor1, interceptor2 }, new IInterceptor[] { interceptor3, interceptor4, new PassiveSaveChangesInterceptor() }); diff --git a/test/EFCore.Specification.Tests/Scaffolding/CompiledModelTestBase.cs b/test/EFCore.Specification.Tests/Scaffolding/CompiledModelTestBase.cs index f2f2062e497..85782222257 100644 --- a/test/EFCore.Specification.Tests/Scaffolding/CompiledModelTestBase.cs +++ b/test/EFCore.Specification.Tests/Scaffolding/CompiledModelTestBase.cs @@ -23,12 +23,13 @@ public virtual void SimpleModel() modelBuilder => { modelBuilder.Ignore>(); - modelBuilder.Entity>(b => - { - b.Ignore(e => e.Principal); - b.Property(e => e.Id).ValueGeneratedNever(); - b.Property("Data"); - }); + modelBuilder.Entity>( + b => + { + b.Ignore(e => e.Principal); + b.Property(e => e.Id).ValueGeneratedNever(); + b.Property("Data"); + }); }, model => Assert.Single(model.GetEntityTypes()), // Blocked by dotnet/runtime/issues/89439 @@ -594,6 +595,8 @@ public virtual void ComplexTypes() }); //c.SaveChanges(); + + return Task.CompletedTask; }, options: new CompiledModelCodeGenerationOptions { UseNullableReferenceTypes = true }); @@ -724,6 +727,7 @@ public NullIntToNullStringConverter() { } } + public abstract class AbstractBase { public int Id { get; set; } @@ -1081,6 +1085,7 @@ public class ManyTypes } public readonly record struct ManyTypesId(int Id); + public class Data { public byte[]? Blob { get; set; } @@ -1122,7 +1127,9 @@ public class DependentBase(TKey id) : AbstractBase { private new TKey Id { get; } = id; - public TKey GetId() => Id; + public TKey GetId() + => Id; + public PrincipalDerived>? Principal { get; set; } } @@ -1135,7 +1142,9 @@ public DependentDerived(TKey id, string data) } private string? Data { get; set; } - public string? GetData() => Data; + + public string? GetData() + => Data; } public class OwnedType : INotifyPropertyChanged, INotifyPropertyChanging @@ -1266,11 +1275,14 @@ public IEnumerable? RefTypeEnumerable } protected abstract TestHelpers TestHelpers { get; } - protected override string StoreName => "CompiledModelTest"; + + protected override string StoreName + => "CompiledModelTest"; private string _filePath = ""; - protected virtual BuildSource AddReferences(BuildSource build, + protected virtual BuildSource AddReferences( + BuildSource build, [CallerFilePath] string filePath = "") { _filePath = filePath; @@ -1291,10 +1303,10 @@ protected virtual void AddDesignTimeServices(IServiceCollection services) { } - protected virtual void Test( + protected virtual Task Test( Action onModelCreating, Action? assertModel = null, - Action? useContext = null, + Func? useContext = null, Action? onConfiguring = null, CompiledModelCodeGenerationOptions? options = null, Func? addServices = null, @@ -1316,10 +1328,10 @@ protected virtual void Test( expectedExceptionMessage, testName); - protected virtual (TContext?, IModel?) Test( + protected virtual async Task<(TContext?, IModel?)> Test( Action? onModelCreating = null, Action? assertModel = null, - Action? useContext = null, + Func? useContext = null, Action? onConfiguring = null, CompiledModelCodeGenerationOptions? options = null, Func? addServices = null, @@ -1330,7 +1342,7 @@ protected virtual (TContext?, IModel?) Test( [CallerMemberName] string testName = "") where TContext : DbContext { - using var context = CreateContextFactory( + using var context = (await CreateContextFactory( modelBuilder => { var model = modelBuilder.Model; @@ -1339,7 +1351,7 @@ protected virtual (TContext?, IModel?) Test( onModelCreating?.Invoke(modelBuilder); }, onConfiguring, - addServices).CreateContext(); + addServices)).CreateContext(); var model = context.GetService().Model; options ??= new CompiledModelCodeGenerationOptions(); @@ -1388,7 +1400,7 @@ protected virtual (TContext?, IModel?) Test( if (useContext != null) { - var contextFactory = CreateContextFactory( + var contextFactory = await CreateContextFactory( onConfiguring: options => { onConfiguring?.Invoke(options); @@ -1396,7 +1408,7 @@ protected virtual (TContext?, IModel?) Test( }, addServices: addServices); ListLoggerFactory.Clear(); - TestStore.Initialize(ServiceProvider, contextFactory.CreateContext, c => useContext((TContext)c)); + await TestStore.InitializeAsync(ServiceProvider, contextFactory.CreateContext, c => useContext((TContext)c)); } AssertBaseline(scaffoldedFiles, testName); @@ -1412,8 +1424,7 @@ private IModel CompileModel( { var build = new BuildSource { - Sources = scaffoldedFiles.ToDictionary(f => f.Path, f => f.Code), - NullableReferenceTypes = options.UseNullableReferenceTypes + Sources = scaffoldedFiles.ToDictionary(f => f.Path, f => f.Code), NullableReferenceTypes = options.UseNullableReferenceTypes }; AddReferences(build); diff --git a/test/EFCore.Specification.Tests/SeedingTestBase.cs b/test/EFCore.Specification.Tests/SeedingTestBase.cs index 51085c642ab..42bad8a3207 100644 --- a/test/EFCore.Specification.Tests/SeedingTestBase.cs +++ b/test/EFCore.Specification.Tests/SeedingTestBase.cs @@ -15,7 +15,7 @@ public abstract class SeedingTestBase public virtual async Task Seeding_does_not_leave_context_contaminated(bool async) { using var context = CreateContextWithEmptyDatabase(async ? "1A" : "1S"); - TestStore.Clean(context); + await TestStore.CleanAsync(context); var _ = async ? await context.Database.EnsureCreatedResilientlyAsync() : context.Database.EnsureCreatedResiliently(); @@ -39,7 +39,7 @@ public virtual async Task Seeding_keyless_entity_throws_exception(bool async) async () => { using var context = CreateKeylessContextWithEmptyDatabase(); - TestStore.Clean(context); + await TestStore.CleanAsync(context); var _ = async ? await context.Database.EnsureCreatedResilientlyAsync() : context.Database.EnsureCreatedResiliently(); diff --git a/test/EFCore.Specification.Tests/SharedStoreFixtureBase.cs b/test/EFCore.Specification.Tests/SharedStoreFixtureBase.cs index 7b35a6632a5..1ffad9e7362 100644 --- a/test/EFCore.Specification.Tests/SharedStoreFixtureBase.cs +++ b/test/EFCore.Specification.Tests/SharedStoreFixtureBase.cs @@ -4,7 +4,7 @@ // ReSharper disable VirtualMemberCallInConstructor namespace Microsoft.EntityFrameworkCore; -public abstract class SharedStoreFixtureBase : FixtureBase, IDisposable, IAsyncLifetime +public abstract class SharedStoreFixtureBase : FixtureBase, IAsyncLifetime where TContext : DbContext { protected virtual Type ContextType { get; } = typeof(TContext); @@ -42,7 +42,7 @@ public ListLoggerFactory ListLoggerFactory private MethodInfo? _createDbContext; - public virtual Task InitializeAsync() + public virtual async Task InitializeAsync() { _testStore = TestStoreFactory.GetOrCreate(StoreName); @@ -67,9 +67,7 @@ public virtual Task InitializeAsync() _serviceProvider = services.BuildServiceProvider(validateScopes: true); - TestStore.Initialize(ServiceProvider, CreateContext, c => Seed((TContext)c), Clean); - - return Task.CompletedTask; + await TestStore.InitializeAsync(ServiceProvider, CreateContext, c => SeedAsync((TContext)c), CleanAsync); } public virtual TContext CreateContext() @@ -91,14 +89,6 @@ protected override IServiceCollection AddServices(IServiceCollection serviceColl protected virtual bool ShouldLogCategory(string logCategory) => false; - public virtual void Reseed() - { - using var context = CreateContext(); - TestStore.Clean(context); - Clean(context); - Seed(context); - } - public virtual async Task ReseedAsync() { using var context = CreateContext(); @@ -107,15 +97,8 @@ public virtual async Task ReseedAsync() await SeedAsync(context); } - protected virtual void Seed(TContext context) - { - } - protected virtual Task SeedAsync(TContext context) - { - Seed(context); - return Task.CompletedTask; - } + => Task.CompletedTask; protected virtual void Clean(DbContext context) { @@ -127,11 +110,6 @@ protected virtual Task CleanAsync(DbContext context) return Task.CompletedTask; } - // Called after DisposeAsync - public virtual void Dispose() - { - } - public virtual Task DisposeAsync() => TestStore.DisposeAsync(); } diff --git a/test/EFCore.Specification.Tests/SingletonInterceptorsTestBase.cs b/test/EFCore.Specification.Tests/SingletonInterceptorsTestBase.cs index b0dc37408f0..d8bdc9450ef 100644 --- a/test/EFCore.Specification.Tests/SingletonInterceptorsTestBase.cs +++ b/test/EFCore.Specification.Tests/SingletonInterceptorsTestBase.cs @@ -70,9 +70,9 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) } } - public TContext CreateContext(IEnumerable interceptors, bool inject, bool usePooling) + public async Task CreateContext(IEnumerable interceptors, bool inject, bool usePooling) { - var contextFactory = base.Initialize( + var contextFactory = await base.InitializeAsync( onConfiguring: inject ? null : o => o.AddInterceptors(interceptors), addServices: inject ? s => InjectInterceptors(s, interceptors) : null, usePooling: usePooling, diff --git a/test/EFCore.Specification.Tests/SpatialFixtureBase.cs b/test/EFCore.Specification.Tests/SpatialFixtureBase.cs index 47ce05a99d5..3373505a621 100644 --- a/test/EFCore.Specification.Tests/SpatialFixtureBase.cs +++ b/test/EFCore.Specification.Tests/SpatialFixtureBase.cs @@ -30,6 +30,6 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con }); } - protected override void Seed(SpatialContext context) - => SpatialContext.Seed(context, _geometryFactory); + protected override Task SeedAsync(SpatialContext context) + => SpatialContext.SeedAsync(context, _geometryFactory); } diff --git a/test/EFCore.Specification.Tests/SpatialTestBase.cs b/test/EFCore.Specification.Tests/SpatialTestBase.cs index e2be8f69101..840519678b5 100644 --- a/test/EFCore.Specification.Tests/SpatialTestBase.cs +++ b/test/EFCore.Specification.Tests/SpatialTestBase.cs @@ -43,7 +43,7 @@ public virtual void Values_arent_compared_by_reference() } [ConditionalFact] - public virtual void Mutation_of_tracked_values_does_not_mutate_values_in_store() + public virtual async void Mutation_of_tracked_values_does_not_mutate_values_in_store() { Point CreatePoint(double y = 2.2) => new(1.1, y, 3.3); @@ -57,22 +57,21 @@ Polygon CreatePolygon(double y = 2.2) var point = CreatePoint(); var polygon = CreatePolygon(); - ExecuteWithStrategyInTransaction( + await ExecuteWithStrategyInTransactionAsync( context => { context.AddRange( new PointEntity { Id = id1, Point = point }, new PolygonEntity { Id = id2, Polygon = polygon }); - context.SaveChanges(); - }, - context => + return context.SaveChangesAsync(); + }, async context => { point.X = 11.1; polygon.Coordinates[1].X = 11.1; - var fromStore1 = context.Set().First(p => p.Id == id1); - var fromStore2 = context.Set().First(p => p.Id == id2); + var fromStore1 = await context.Set().FirstAsync(p => p.Id == id1); + var fromStore2 = await context.Set().FirstAsync(p => p.Id == id2); Assert.Equal(CreatePoint(), fromStore1.Point); Assert.Equal(CreatePolygon(), fromStore2.Polygon); @@ -82,12 +81,11 @@ Polygon CreatePolygon(double y = 2.2) context.Entry(fromStore2).State = EntityState.Unchanged; - context.SaveChanges(); - }, - context => + await context.SaveChangesAsync(); + }, async context => { - var fromStore1 = context.Set().First(p => p.Id == id1); - var fromStore2 = context.Set().First(p => p.Id == id2); + var fromStore1 = await context.Set().FirstAsync(p => p.Id == id1); + var fromStore2 = await context.Set().FirstAsync(p => p.Id == id2); Assert.Equal(CreatePoint(22.2), fromStore1.Point); Assert.Equal(CreatePolygon(), fromStore2.Polygon); @@ -129,11 +127,11 @@ public virtual void Can_roundtrip_Z_and_M() Assert.Equal(0, entity.PointZM.M); } - protected virtual void ExecuteWithStrategyInTransaction( - Action testOperation, - Action nestedTestOperation1 = null, - Action nestedTestOperation2 = null) - => TestHelpers.ExecuteWithStrategyInTransaction( + protected virtual Task ExecuteWithStrategyInTransactionAsync( + Func testOperation, + Func nestedTestOperation1 = null, + Func nestedTestOperation2 = null) + => TestHelpers.ExecuteWithStrategyInTransactionAsync( CreateContext, UseTransaction, testOperation, nestedTestOperation1, nestedTestOperation2); diff --git a/test/EFCore.Specification.Tests/StoreGeneratedFixupTestBase.cs b/test/EFCore.Specification.Tests/StoreGeneratedFixupTestBase.cs index 7844f1ed010..d0e7e1db7e2 100644 --- a/test/EFCore.Specification.Tests/StoreGeneratedFixupTestBase.cs +++ b/test/EFCore.Specification.Tests/StoreGeneratedFixupTestBase.cs @@ -23,8 +23,8 @@ protected StoreGeneratedFixupTestBase(TFixture fixture) protected TFixture Fixture { get; } [ConditionalFact] - public virtual void Add_dependent_then_principal_one_to_many_FK_set_both_navs_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_dependent_then_principal_one_to_many_FK_set_both_navs_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new Category { Id1 = -77, Id2 = Guid77 }; @@ -43,12 +43,12 @@ public virtual void Add_dependent_then_principal_one_to_many_FK_set_both_navs_se context.Add(dependent); context.Add(principal); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_dependent_then_principal_one_to_many_FK_not_set_both_navs_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_dependent_then_principal_one_to_many_FK_not_set_both_navs_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new Category(); @@ -59,12 +59,12 @@ public virtual void Add_dependent_then_principal_one_to_many_FK_not_set_both_nav context.Add(dependent); context.Add(principal); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_dependent_then_principal_one_to_many_FK_set_no_navs_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_dependent_then_principal_one_to_many_FK_set_no_navs_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new Category { Id1 = -77, Id2 = Guid77 }; @@ -81,12 +81,12 @@ public virtual void Add_dependent_then_principal_one_to_many_FK_set_no_navs_set( context.Add(dependent); context.Add(principal); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_dependent_then_principal_one_to_many_FK_set_principal_nav_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_dependent_then_principal_one_to_many_FK_set_principal_nav_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new Category { Id1 = -77, Id2 = Guid77 }; @@ -104,12 +104,12 @@ public virtual void Add_dependent_then_principal_one_to_many_FK_set_principal_na context.Add(dependent); context.Add(principal); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_dependent_then_principal_one_to_many_FK_set_dependent_nav_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_dependent_then_principal_one_to_many_FK_set_dependent_nav_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new Category { Id1 = -77, Id2 = Guid77 }; @@ -127,12 +127,12 @@ public virtual void Add_dependent_then_principal_one_to_many_FK_set_dependent_na context.Add(dependent); context.Add(principal); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_dependent_then_principal_one_to_many_FK_not_set_principal_nav_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_dependent_then_principal_one_to_many_FK_not_set_principal_nav_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new Category(); @@ -142,12 +142,12 @@ public virtual void Add_dependent_then_principal_one_to_many_FK_not_set_principa context.Add(dependent); context.Add(principal); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_dependent_then_principal_one_to_many_FK_not_set_dependent_nav_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_dependent_then_principal_one_to_many_FK_not_set_dependent_nav_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new Category(); @@ -156,12 +156,12 @@ public virtual void Add_dependent_then_principal_one_to_many_FK_not_set_dependen context.Add(dependent); context.Add(principal); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_principal_then_dependent_one_to_many_FK_set_both_navs_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_principal_then_dependent_one_to_many_FK_set_both_navs_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new Category { Id1 = -77, Id2 = Guid77 }; @@ -180,12 +180,12 @@ public virtual void Add_principal_then_dependent_one_to_many_FK_set_both_navs_se context.Add(principal); context.Add(dependent); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_principal_then_dependent_one_to_many_FK_not_set_both_navs_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_principal_then_dependent_one_to_many_FK_not_set_both_navs_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new Category(); @@ -195,12 +195,12 @@ public virtual void Add_principal_then_dependent_one_to_many_FK_not_set_both_nav context.Add(principal); context.Add(dependent); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_principal_then_dependent_one_to_many_FK_set_no_navs_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_principal_then_dependent_one_to_many_FK_set_no_navs_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new Category { Id1 = -77, Id2 = Guid77 }; @@ -217,12 +217,12 @@ public virtual void Add_principal_then_dependent_one_to_many_FK_set_no_navs_set( context.Add(principal); context.Add(dependent); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_principal_then_dependent_one_to_many_FK_set_principal_nav_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_principal_then_dependent_one_to_many_FK_set_principal_nav_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new Category { Id1 = -77, Id2 = Guid77 }; @@ -240,12 +240,12 @@ public virtual void Add_principal_then_dependent_one_to_many_FK_set_principal_na context.Add(principal); context.Add(dependent); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_principal_then_dependent_one_to_many_FK_set_dependent_nav_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_principal_then_dependent_one_to_many_FK_set_dependent_nav_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new Category { Id1 = -77, Id2 = Guid77 }; @@ -263,12 +263,12 @@ public virtual void Add_principal_then_dependent_one_to_many_FK_set_dependent_na context.Add(principal); context.Add(dependent); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_principal_then_dependent_one_to_many_FK_not_set_principal_nav_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_principal_then_dependent_one_to_many_FK_not_set_principal_nav_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new Category(); @@ -278,12 +278,12 @@ public virtual void Add_principal_then_dependent_one_to_many_FK_not_set_principa context.Add(principal); context.Add(dependent); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_principal_then_dependent_one_to_many_FK_not_set_dependent_nav_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_principal_then_dependent_one_to_many_FK_not_set_dependent_nav_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new Category(); @@ -292,10 +292,10 @@ public virtual void Add_principal_then_dependent_one_to_many_FK_not_set_dependen context.Add(principal); context.Add(dependent); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); - private void AssertFixupAndSave(DbContext context, Category principal, Product dependent) + private async Task AssertFixupAndSaveAsync(DbContext context, Category principal, Product dependent) { AssertFixup( context, @@ -315,7 +315,7 @@ private void AssertFixupAndSave(DbContext context, Category principal, Product d Assert.Equal(EntityState.Added, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -331,8 +331,8 @@ private void AssertFixupAndSave(DbContext context, Category principal, Product d } [ConditionalFact] - public virtual void Add_dependent_then_principal_one_to_many_prin_uni_FK_set_no_navs_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_dependent_then_principal_one_to_many_prin_uni_FK_set_no_navs_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new CategoryPN { Id1 = -77, Id2 = Guid77 }; @@ -349,12 +349,12 @@ public virtual void Add_dependent_then_principal_one_to_many_prin_uni_FK_set_no_ context.Add(dependent); context.Add(principal); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_principal_then_dependent_one_to_many_prin_uni_FK_set_no_navs_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_principal_then_dependent_one_to_many_prin_uni_FK_set_no_navs_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new CategoryPN { Id1 = -77, Id2 = Guid77 }; @@ -371,12 +371,12 @@ public virtual void Add_principal_then_dependent_one_to_many_prin_uni_FK_set_no_ context.Add(principal); context.Add(dependent); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_dependent_then_principal_one_to_many_prin_uni_FK_set_principal_nav_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_dependent_then_principal_one_to_many_prin_uni_FK_set_principal_nav_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new CategoryPN { Id1 = -77, Id2 = Guid77 }; @@ -394,12 +394,12 @@ public virtual void Add_dependent_then_principal_one_to_many_prin_uni_FK_set_pri context.Add(dependent); context.Add(principal); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_dependent_then_principal_one_to_many_prin_uni_FK_not_set_principal_nav_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_dependent_then_principal_one_to_many_prin_uni_FK_not_set_principal_nav_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new CategoryPN(); @@ -409,12 +409,12 @@ public virtual void Add_dependent_then_principal_one_to_many_prin_uni_FK_not_set context.Add(dependent); context.Add(principal); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_principal_then_dependent_one_to_many_prin_uni_FK_set_principal_nav_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_principal_then_dependent_one_to_many_prin_uni_FK_set_principal_nav_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new CategoryPN { Id1 = -77, Id2 = Guid77 }; @@ -432,12 +432,12 @@ public virtual void Add_principal_then_dependent_one_to_many_prin_uni_FK_set_pri context.Add(principal); context.Add(dependent); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_principal_then_dependent_one_to_many_prin_uni_FK_not_set_principal_nav_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_principal_then_dependent_one_to_many_prin_uni_FK_not_set_principal_nav_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new CategoryPN(); @@ -447,10 +447,10 @@ public virtual void Add_principal_then_dependent_one_to_many_prin_uni_FK_not_set context.Add(principal); context.Add(dependent); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); - private void AssertFixupAndSave(DbContext context, CategoryPN principal, ProductPN dependent) + private async Task AssertFixupAndSaveAsync(DbContext context, CategoryPN principal, ProductPN dependent) { AssertFixup( context, @@ -469,7 +469,7 @@ private void AssertFixupAndSave(DbContext context, CategoryPN principal, Product Assert.Equal(EntityState.Added, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -484,8 +484,8 @@ private void AssertFixupAndSave(DbContext context, CategoryPN principal, Product } [ConditionalFact] - public virtual void Add_dependent_then_principal_one_to_many_dep_uni_FK_set_no_navs_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_dependent_then_principal_one_to_many_dep_uni_FK_set_no_navs_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new CategoryDN { Id1 = -77, Id2 = Guid77 }; @@ -502,12 +502,12 @@ public virtual void Add_dependent_then_principal_one_to_many_dep_uni_FK_set_no_n context.Add(dependent); context.Add(principal); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_dependent_then_principal_one_to_many_dep_uni_FK_set_dependent_nav_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_dependent_then_principal_one_to_many_dep_uni_FK_set_dependent_nav_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new CategoryDN { Id1 = -77, Id2 = Guid77 }; @@ -525,12 +525,12 @@ public virtual void Add_dependent_then_principal_one_to_many_dep_uni_FK_set_depe context.Add(dependent); context.Add(principal); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_dependent_then_principal_one_to_many_dep_uni_FK_not_set_dependent_nav_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_dependent_then_principal_one_to_many_dep_uni_FK_not_set_dependent_nav_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new CategoryDN(); @@ -539,12 +539,12 @@ public virtual void Add_dependent_then_principal_one_to_many_dep_uni_FK_not_set_ context.Add(dependent); context.Add(principal); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_principal_then_dependent_one_to_many_dep_uni_FK_set_no_navs_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_principal_then_dependent_one_to_many_dep_uni_FK_set_no_navs_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new CategoryDN { Id1 = -77, Id2 = Guid77 }; @@ -561,12 +561,12 @@ public virtual void Add_principal_then_dependent_one_to_many_dep_uni_FK_set_no_n context.Add(principal); context.Add(dependent); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_principal_then_dependent_one_to_many_dep_uni_FK_set_dependent_nav_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_principal_then_dependent_one_to_many_dep_uni_FK_set_dependent_nav_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new CategoryDN { Id1 = -77, Id2 = Guid77 }; @@ -584,12 +584,12 @@ public virtual void Add_principal_then_dependent_one_to_many_dep_uni_FK_set_depe context.Add(principal); context.Add(dependent); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_principal_then_dependent_one_to_many_dep_uni_FK_not_set_dependent_nav_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_principal_then_dependent_one_to_many_dep_uni_FK_not_set_dependent_nav_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new CategoryDN(); @@ -598,10 +598,10 @@ public virtual void Add_principal_then_dependent_one_to_many_dep_uni_FK_not_set_ context.Add(principal); context.Add(dependent); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); - private void AssertFixupAndSave(DbContext context, CategoryDN principal, ProductDN dependent) + private async Task AssertFixupAndSaveAsync(DbContext context, CategoryDN principal, ProductDN dependent) { AssertFixup( context, @@ -620,7 +620,7 @@ private void AssertFixupAndSave(DbContext context, CategoryDN principal, Product Assert.Equal(EntityState.Added, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -635,8 +635,8 @@ private void AssertFixupAndSave(DbContext context, CategoryDN principal, Product } [ConditionalFact] - public virtual void Add_dependent_then_principal_one_to_many_no_navs_FK_set_no_navs_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_dependent_then_principal_one_to_many_no_navs_FK_set_no_navs_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new CategoryNN { Id1 = -77, Id2 = Guid77 }; @@ -653,12 +653,12 @@ public virtual void Add_dependent_then_principal_one_to_many_no_navs_FK_set_no_n context.Add(dependent); context.Add(principal); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_principal_then_dependent_one_to_many_no_navs_FK_set_no_navs_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_principal_then_dependent_one_to_many_no_navs_FK_set_no_navs_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new CategoryNN { Id1 = -77, Id2 = Guid77 }; @@ -675,10 +675,10 @@ public virtual void Add_principal_then_dependent_one_to_many_no_navs_FK_set_no_n context.Add(principal); context.Add(dependent); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); - private void AssertFixupAndSave(DbContext context, CategoryNN principal, ProductNN dependent) + private async Task AssertFixupAndSaveAsync(DbContext context, CategoryNN principal, ProductNN dependent) { AssertFixup( context, @@ -690,7 +690,7 @@ private void AssertFixupAndSave(DbContext context, CategoryNN principal, Product Assert.Equal(EntityState.Added, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -704,8 +704,8 @@ private void AssertFixupAndSave(DbContext context, CategoryNN principal, Product } [ConditionalFact] - public virtual void Add_dependent_then_principal_one_to_one_FK_set_both_navs_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_dependent_then_principal_one_to_one_FK_set_both_navs_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new Parent { Id1 = -77, Id2 = Guid77 }; @@ -724,12 +724,12 @@ public virtual void Add_dependent_then_principal_one_to_one_FK_set_both_navs_set context.Add(dependent); context.Add(principal); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_dependent_then_principal_one_to_one_FK_not_set_both_navs_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_dependent_then_principal_one_to_one_FK_not_set_both_navs_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new Parent(); @@ -739,12 +739,12 @@ public virtual void Add_dependent_then_principal_one_to_one_FK_not_set_both_navs context.Add(dependent); context.Add(principal); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_dependent_then_principal_one_to_one_FK_set_no_navs_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_dependent_then_principal_one_to_one_FK_set_no_navs_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new Parent { Id1 = -77, Id2 = Guid77 }; @@ -761,12 +761,12 @@ public virtual void Add_dependent_then_principal_one_to_one_FK_set_no_navs_set() context.Add(dependent); context.Add(principal); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_dependent_then_principal_one_to_one_FK_set_principal_nav_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_dependent_then_principal_one_to_one_FK_set_principal_nav_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new Parent { Id1 = -77, Id2 = Guid77 }; @@ -784,12 +784,12 @@ public virtual void Add_dependent_then_principal_one_to_one_FK_set_principal_nav context.Add(dependent); context.Add(principal); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_dependent_then_principal_one_to_one_FK_set_dependent_nav_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_dependent_then_principal_one_to_one_FK_set_dependent_nav_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new Parent { Id1 = -77, Id2 = Guid77 }; @@ -807,12 +807,12 @@ public virtual void Add_dependent_then_principal_one_to_one_FK_set_dependent_nav context.Add(dependent); context.Add(principal); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_dependent_then_principal_one_to_one_FK_not_set_principal_nav_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_dependent_then_principal_one_to_one_FK_not_set_principal_nav_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new Parent(); @@ -822,12 +822,12 @@ public virtual void Add_dependent_then_principal_one_to_one_FK_not_set_principal context.Add(dependent); context.Add(principal); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_dependent_then_principal_one_to_one_FK_not_set_dependent_nav_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_dependent_then_principal_one_to_one_FK_not_set_dependent_nav_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new Parent(); @@ -836,12 +836,12 @@ public virtual void Add_dependent_then_principal_one_to_one_FK_not_set_dependent context.Add(dependent); context.Add(principal); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_principal_then_dependent_one_to_one_FK_set_both_navs_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_principal_then_dependent_one_to_one_FK_set_both_navs_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new Parent { Id1 = -77, Id2 = Guid77 }; @@ -860,12 +860,12 @@ public virtual void Add_principal_then_dependent_one_to_one_FK_set_both_navs_set context.Add(principal); context.Add(dependent); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_principal_then_dependent_one_to_one_FK_not_set_both_navs_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_principal_then_dependent_one_to_one_FK_not_set_both_navs_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new Parent(); @@ -875,12 +875,12 @@ public virtual void Add_principal_then_dependent_one_to_one_FK_not_set_both_navs context.Add(principal); context.Add(dependent); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_principal_then_dependent_one_to_one_FK_set_no_navs_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_principal_then_dependent_one_to_one_FK_set_no_navs_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new Parent { Id1 = -77, Id2 = Guid77 }; @@ -897,12 +897,12 @@ public virtual void Add_principal_then_dependent_one_to_one_FK_set_no_navs_set() context.Add(principal); context.Add(dependent); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_principal_then_dependent_one_to_one_FK_set_principal_nav_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_principal_then_dependent_one_to_one_FK_set_principal_nav_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new Parent { Id1 = -77, Id2 = Guid77 }; @@ -920,12 +920,12 @@ public virtual void Add_principal_then_dependent_one_to_one_FK_set_principal_nav context.Add(principal); context.Add(dependent); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_principal_then_dependent_one_to_one_FK_set_dependent_nav_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_principal_then_dependent_one_to_one_FK_set_dependent_nav_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new Parent { Id1 = -77, Id2 = Guid77 }; @@ -943,12 +943,12 @@ public virtual void Add_principal_then_dependent_one_to_one_FK_set_dependent_nav context.Add(principal); context.Add(dependent); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_principal_then_dependent_one_to_one_FK_not_set_principal_nav_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_principal_then_dependent_one_to_one_FK_not_set_principal_nav_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new Parent(); @@ -958,12 +958,12 @@ public virtual void Add_principal_then_dependent_one_to_one_FK_not_set_principal context.Add(principal); context.Add(dependent); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_principal_then_dependent_one_to_one_FK_not_set_dependent_nav_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_principal_then_dependent_one_to_one_FK_not_set_dependent_nav_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new Parent(); @@ -972,10 +972,10 @@ public virtual void Add_principal_then_dependent_one_to_one_FK_not_set_dependent context.Add(principal); context.Add(dependent); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); - private void AssertFixupAndSave(DbContext context, Parent principal, Child dependent) + private async Task AssertFixupAndSaveAsync(DbContext context, Parent principal, Child dependent) { AssertFixup( context, @@ -995,7 +995,7 @@ private void AssertFixupAndSave(DbContext context, Parent principal, Child depen Assert.Equal(EntityState.Added, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -1011,8 +1011,8 @@ private void AssertFixupAndSave(DbContext context, Parent principal, Child depen } [ConditionalFact] - public virtual void Add_dependent_then_principal_one_to_one_prin_uni_FK_set_no_navs_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_dependent_then_principal_one_to_one_prin_uni_FK_set_no_navs_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new ParentPN { Id1 = -77, Id2 = Guid77 }; @@ -1029,12 +1029,12 @@ public virtual void Add_dependent_then_principal_one_to_one_prin_uni_FK_set_no_n context.Add(dependent); context.Add(principal); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_principal_then_dependent_one_to_one_prin_uni_FK_set_no_navs_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_principal_then_dependent_one_to_one_prin_uni_FK_set_no_navs_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new ParentPN { Id1 = -77, Id2 = Guid77 }; @@ -1051,12 +1051,12 @@ public virtual void Add_principal_then_dependent_one_to_one_prin_uni_FK_set_no_n context.Add(principal); context.Add(dependent); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_dependent_then_principal_one_to_one_prin_uni_FK_set_principal_nav_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_dependent_then_principal_one_to_one_prin_uni_FK_set_principal_nav_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new ParentPN { Id1 = -77, Id2 = Guid77 }; @@ -1074,12 +1074,12 @@ public virtual void Add_dependent_then_principal_one_to_one_prin_uni_FK_set_prin context.Add(dependent); context.Add(principal); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_dependent_then_principal_one_to_one_prin_uni_FK_not_set_principal_nav_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_dependent_then_principal_one_to_one_prin_uni_FK_not_set_principal_nav_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new ParentPN(); @@ -1089,12 +1089,12 @@ public virtual void Add_dependent_then_principal_one_to_one_prin_uni_FK_not_set_ context.Add(dependent); context.Add(principal); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_principal_then_dependent_one_to_one_prin_uni_FK_set_principal_nav_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_principal_then_dependent_one_to_one_prin_uni_FK_set_principal_nav_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new ParentPN { Id1 = -77, Id2 = Guid77 }; @@ -1112,12 +1112,12 @@ public virtual void Add_principal_then_dependent_one_to_one_prin_uni_FK_set_prin context.Add(principal); context.Add(dependent); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_principal_then_dependent_one_to_one_prin_uni_FK_not_set_principal_nav_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_principal_then_dependent_one_to_one_prin_uni_FK_not_set_principal_nav_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new ParentPN(); @@ -1127,10 +1127,10 @@ public virtual void Add_principal_then_dependent_one_to_one_prin_uni_FK_not_set_ context.Add(principal); context.Add(dependent); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); - private void AssertFixupAndSave(DbContext context, ParentPN principal, ChildPN dependent) + private async Task AssertFixupAndSaveAsync(DbContext context, ParentPN principal, ChildPN dependent) { AssertFixup( context, @@ -1149,7 +1149,7 @@ private void AssertFixupAndSave(DbContext context, ParentPN principal, ChildPN d Assert.Equal(EntityState.Added, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -1164,8 +1164,8 @@ private void AssertFixupAndSave(DbContext context, ParentPN principal, ChildPN d } [ConditionalFact] - public virtual void Add_dependent_then_principal_one_to_one_dep_uni_FK_set_no_navs_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_dependent_then_principal_one_to_one_dep_uni_FK_set_no_navs_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new ParentDN { Id1 = -77, Id2 = Guid77 }; @@ -1182,12 +1182,12 @@ public virtual void Add_dependent_then_principal_one_to_one_dep_uni_FK_set_no_na context.Add(dependent); context.Add(principal); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_dependent_then_principal_one_to_one_dep_uni_FK_set_dependent_nav_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_dependent_then_principal_one_to_one_dep_uni_FK_set_dependent_nav_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new ParentDN { Id1 = -77, Id2 = Guid77 }; @@ -1205,12 +1205,12 @@ public virtual void Add_dependent_then_principal_one_to_one_dep_uni_FK_set_depen context.Add(dependent); context.Add(principal); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_dependent_then_principal_one_to_one_dep_uni_FK_not_set_dependent_nav_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_dependent_then_principal_one_to_one_dep_uni_FK_not_set_dependent_nav_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new ParentDN(); @@ -1219,12 +1219,12 @@ public virtual void Add_dependent_then_principal_one_to_one_dep_uni_FK_not_set_d context.Add(dependent); context.Add(principal); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_principal_then_dependent_one_to_one_dep_uni_FK_set_no_navs_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_principal_then_dependent_one_to_one_dep_uni_FK_set_no_navs_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new ParentDN { Id1 = -77, Id2 = Guid77 }; @@ -1241,12 +1241,12 @@ public virtual void Add_principal_then_dependent_one_to_one_dep_uni_FK_set_no_na context.Add(principal); context.Add(dependent); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_principal_then_dependent_one_to_one_dep_uni_FK_set_dependent_nav_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_principal_then_dependent_one_to_one_dep_uni_FK_set_dependent_nav_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new ParentDN { Id1 = -77, Id2 = Guid77 }; @@ -1264,12 +1264,12 @@ public virtual void Add_principal_then_dependent_one_to_one_dep_uni_FK_set_depen context.Add(principal); context.Add(dependent); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_principal_then_dependent_one_to_one_dep_uni_FK_not_set_dependent_nav_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_principal_then_dependent_one_to_one_dep_uni_FK_not_set_dependent_nav_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new ParentDN(); @@ -1280,10 +1280,10 @@ public virtual void Add_principal_then_dependent_one_to_one_dep_uni_FK_not_set_d MarkIdsTemporary(context, dependent, principal); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); - private void AssertFixupAndSave(DbContext context, ParentDN principal, ChildDN dependent) + private async Task AssertFixupAndSaveAsync(DbContext context, ParentDN principal, ChildDN dependent) { AssertFixup( context, @@ -1302,7 +1302,7 @@ private void AssertFixupAndSave(DbContext context, ParentDN principal, ChildDN d Assert.Equal(EntityState.Added, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -1317,8 +1317,8 @@ private void AssertFixupAndSave(DbContext context, ParentDN principal, ChildDN d } [ConditionalFact] - public virtual void Add_dependent_then_principal_one_to_one_no_navs_FK_set_no_navs_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_dependent_then_principal_one_to_one_no_navs_FK_set_no_navs_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new ParentNN { Id1 = -77, Id2 = Guid77 }; @@ -1335,12 +1335,12 @@ public virtual void Add_dependent_then_principal_one_to_one_no_navs_FK_set_no_na context.Add(dependent); context.Add(principal); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); [ConditionalFact] - public virtual void Add_principal_then_dependent_one_to_one_no_navs_FK_set_no_navs_set() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_principal_then_dependent_one_to_one_no_navs_FK_set_no_navs_set() + => ExecuteWithStrategyInTransactionAsync( context => { var principal = new ParentNN { Id1 = -77, Id2 = Guid77 }; @@ -1357,10 +1357,10 @@ public virtual void Add_principal_then_dependent_one_to_one_no_navs_FK_set_no_na context.Add(principal); context.Add(dependent); - AssertFixupAndSave(context, principal, dependent); + return AssertFixupAndSaveAsync(context, principal, dependent); }); - private void AssertFixupAndSave(DbContext context, ParentNN principal, ChildNN dependent) + private async Task AssertFixupAndSaveAsync(DbContext context, ParentNN principal, ChildNN dependent) { AssertFixup( context, @@ -1372,7 +1372,7 @@ private void AssertFixupAndSave(DbContext context, ParentNN principal, ChildNN d Assert.Equal(EntityState.Added, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -1386,9 +1386,9 @@ private void AssertFixupAndSave(DbContext context, ParentNN principal, ChildNN d } [ConditionalFact] - public virtual void Add_dependent_but_not_principal_one_to_many_FK_set_both_navs_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_dependent_but_not_principal_one_to_many_FK_set_both_navs_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new Category { Id1 = -77, Id2 = Guid77 }; var dependent = new Product { Id1 = -78, Id2 = Guid78 }; @@ -1416,7 +1416,7 @@ public virtual void Add_dependent_but_not_principal_one_to_many_FK_set_both_navs Assert.Equal(EntityState.Added, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -1432,9 +1432,9 @@ public virtual void Add_dependent_but_not_principal_one_to_many_FK_set_both_navs }); [ConditionalFact] - public virtual void Add_dependent_but_not_principal_one_to_many_FK_not_set_both_navs_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_dependent_but_not_principal_one_to_many_FK_not_set_both_navs_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new Category(); var dependent = new Product(); @@ -1464,7 +1464,7 @@ public virtual void Add_dependent_but_not_principal_one_to_many_FK_not_set_both_ Assert.Equal(EntityState.Added, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -1480,9 +1480,9 @@ public virtual void Add_dependent_but_not_principal_one_to_many_FK_not_set_both_ }); [ConditionalFact] - public virtual void Add_dependent_but_not_principal_one_to_many_FK_set_no_navs_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_dependent_but_not_principal_one_to_many_FK_set_no_navs_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new Category { Id1 = -77, Id2 = Guid77 }; var dependent = new Product { Id1 = -78, Id2 = Guid78 }; @@ -1510,11 +1510,11 @@ public virtual void Add_dependent_but_not_principal_one_to_many_FK_set_no_navs_s if (EnforcesFKs) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); } AssertFixup( @@ -1531,9 +1531,9 @@ public virtual void Add_dependent_but_not_principal_one_to_many_FK_set_no_navs_s }); [ConditionalFact] - public virtual void Add_dependent_but_not_principal_one_to_many_FK_set_principal_nav_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_dependent_but_not_principal_one_to_many_FK_set_principal_nav_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new Category { Id1 = -77, Id2 = Guid77 }; var dependent = new Product { Id1 = -78, Id2 = Guid78 }; @@ -1562,11 +1562,11 @@ public virtual void Add_dependent_but_not_principal_one_to_many_FK_set_principal if (EnforcesFKs) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); } AssertFixup( @@ -1583,9 +1583,9 @@ public virtual void Add_dependent_but_not_principal_one_to_many_FK_set_principal }); [ConditionalFact] - public virtual void Add_dependent_but_not_principal_one_to_many_FK_set_dependent_nav_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_dependent_but_not_principal_one_to_many_FK_set_dependent_nav_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new Category { Id1 = -77, Id2 = Guid77 }; var dependent = new Product { Id1 = -78, Id2 = Guid78 }; @@ -1612,7 +1612,7 @@ public virtual void Add_dependent_but_not_principal_one_to_many_FK_set_dependent Assert.Equal(EntityState.Added, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -1628,9 +1628,9 @@ public virtual void Add_dependent_but_not_principal_one_to_many_FK_set_dependent }); [ConditionalFact] - public virtual void Add_dependent_but_not_principal_one_to_many_FK_not_set_principal_nav_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_dependent_but_not_principal_one_to_many_FK_not_set_principal_nav_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new Category(); var dependent = new Product(); @@ -1654,11 +1654,11 @@ public virtual void Add_dependent_but_not_principal_one_to_many_FK_not_set_princ if (EnforcesFKs) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); } AssertFixup( @@ -1674,9 +1674,9 @@ public virtual void Add_dependent_but_not_principal_one_to_many_FK_not_set_princ }); [ConditionalFact] - public virtual void Add_dependent_but_not_principal_one_to_many_FK_not_set_dependent_nav_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_dependent_but_not_principal_one_to_many_FK_not_set_dependent_nav_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new Category(); var dependent = new Product(); @@ -1705,7 +1705,7 @@ public virtual void Add_dependent_but_not_principal_one_to_many_FK_not_set_depen Assert.Equal(EntityState.Added, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -1721,9 +1721,9 @@ public virtual void Add_dependent_but_not_principal_one_to_many_FK_not_set_depen }); [ConditionalFact] - public virtual void Add_principal_but_not_dependent_one_to_many_FK_set_both_navs_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_principal_but_not_dependent_one_to_many_FK_set_both_navs_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new Category { Id1 = -77, Id2 = Guid77 }; var dependent = new Product { Id1 = -78, Id2 = Guid78 }; @@ -1751,7 +1751,7 @@ public virtual void Add_principal_but_not_dependent_one_to_many_FK_set_both_navs Assert.Equal(EntityState.Added, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -1767,9 +1767,9 @@ public virtual void Add_principal_but_not_dependent_one_to_many_FK_set_both_navs }); [ConditionalFact] - public virtual void Add_principal_but_not_dependent_one_to_many_FK_not_set_both_navs_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_principal_but_not_dependent_one_to_many_FK_not_set_both_navs_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new Category(); var dependent = new Product(); @@ -1799,7 +1799,7 @@ public virtual void Add_principal_but_not_dependent_one_to_many_FK_not_set_both_ Assert.Equal(EntityState.Added, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -1815,9 +1815,9 @@ public virtual void Add_principal_but_not_dependent_one_to_many_FK_not_set_both_ }); [ConditionalFact] - public virtual void Add_principal_but_not_dependent_one_to_many_FK_set_no_navs_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_principal_but_not_dependent_one_to_many_FK_set_no_navs_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new Category { Id1 = -77, Id2 = Guid77 }; var dependent = new Product { Id1 = -78, Id2 = Guid78 }; @@ -1843,7 +1843,7 @@ public virtual void Add_principal_but_not_dependent_one_to_many_FK_set_no_navs_s Assert.Equal(EntityState.Detached, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -1857,9 +1857,9 @@ public virtual void Add_principal_but_not_dependent_one_to_many_FK_set_no_navs_s }); [ConditionalFact] - public virtual void Add_principal_but_not_dependent_one_to_many_FK_set_principal_nav_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_principal_but_not_dependent_one_to_many_FK_set_principal_nav_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new Category { Id1 = -77, Id2 = Guid77 }; var dependent = new Product { Id1 = -78, Id2 = Guid78 }; @@ -1886,7 +1886,7 @@ public virtual void Add_principal_but_not_dependent_one_to_many_FK_set_principal Assert.Equal(EntityState.Added, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -1902,9 +1902,9 @@ public virtual void Add_principal_but_not_dependent_one_to_many_FK_set_principal }); [ConditionalFact] - public virtual void Add_principal_but_not_dependent_one_to_many_FK_set_dependent_nav_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_principal_but_not_dependent_one_to_many_FK_set_dependent_nav_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new Category { Id1 = -77, Id2 = Guid77 }; var dependent = new Product { Id1 = -78, Id2 = Guid78 }; @@ -1931,7 +1931,7 @@ public virtual void Add_principal_but_not_dependent_one_to_many_FK_set_dependent Assert.Equal(EntityState.Detached, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -1945,9 +1945,9 @@ public virtual void Add_principal_but_not_dependent_one_to_many_FK_set_dependent }); [ConditionalFact] - public virtual void Add_principal_but_not_dependent_one_to_many_FK_not_set_principal_nav_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_principal_but_not_dependent_one_to_many_FK_not_set_principal_nav_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new Category(); var dependent = new Product(); @@ -1972,7 +1972,7 @@ public virtual void Add_principal_but_not_dependent_one_to_many_FK_not_set_princ Assert.Equal(EntityState.Added, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -1988,9 +1988,9 @@ public virtual void Add_principal_but_not_dependent_one_to_many_FK_not_set_princ }); [ConditionalFact] - public virtual void Add_principal_but_not_dependent_one_to_many_FK_not_set_dependent_nav_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_principal_but_not_dependent_one_to_many_FK_not_set_dependent_nav_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new Category(); var dependent = new Product(); @@ -2012,7 +2012,7 @@ public virtual void Add_principal_but_not_dependent_one_to_many_FK_not_set_depen Assert.Equal(EntityState.Detached, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -2027,9 +2027,9 @@ public virtual void Add_principal_but_not_dependent_one_to_many_FK_not_set_depen }); [ConditionalFact] - public virtual void Add_dependent_but_not_principal_one_to_many_prin_uni_FK_set_no_navs_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_dependent_but_not_principal_one_to_many_prin_uni_FK_set_no_navs_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new CategoryPN { Id1 = -77, Id2 = Guid77 }; var dependent = new ProductPN { Id1 = -78, Id2 = Guid78 }; @@ -2056,11 +2056,11 @@ public virtual void Add_dependent_but_not_principal_one_to_many_prin_uni_FK_set_ if (EnforcesFKs) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); } AssertFixup( @@ -2076,9 +2076,9 @@ public virtual void Add_dependent_but_not_principal_one_to_many_prin_uni_FK_set_ }); [ConditionalFact] - public virtual void Add_principal_but_not_dependent_one_to_many_prin_uni_FK_set_no_navs_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_principal_but_not_dependent_one_to_many_prin_uni_FK_set_no_navs_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new CategoryPN { Id1 = -77, Id2 = Guid77 }; var dependent = new ProductPN { Id1 = -78, Id2 = Guid78 }; @@ -2103,7 +2103,7 @@ public virtual void Add_principal_but_not_dependent_one_to_many_prin_uni_FK_set_ Assert.Equal(EntityState.Detached, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -2116,9 +2116,9 @@ public virtual void Add_principal_but_not_dependent_one_to_many_prin_uni_FK_set_ }); [ConditionalFact] - public virtual void Add_dependent_but_not_principal_one_to_many_prin_uni_FK_set_principal_nav_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_dependent_but_not_principal_one_to_many_prin_uni_FK_set_principal_nav_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new CategoryPN { Id1 = -77, Id2 = Guid77 }; var dependent = new ProductPN { Id1 = -78, Id2 = Guid78 }; @@ -2146,11 +2146,11 @@ public virtual void Add_dependent_but_not_principal_one_to_many_prin_uni_FK_set_ if (EnforcesFKs) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); } AssertFixup( @@ -2166,9 +2166,9 @@ public virtual void Add_dependent_but_not_principal_one_to_many_prin_uni_FK_set_ }); [ConditionalFact] - public virtual void Add_dependent_but_not_principal_one_to_many_prin_uni_FK_not_set_principal_nav_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_dependent_but_not_principal_one_to_many_prin_uni_FK_not_set_principal_nav_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new CategoryPN(); var dependent = new ProductPN(); @@ -2191,11 +2191,11 @@ public virtual void Add_dependent_but_not_principal_one_to_many_prin_uni_FK_not_ if (EnforcesFKs) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); } AssertFixup( @@ -2210,9 +2210,9 @@ public virtual void Add_dependent_but_not_principal_one_to_many_prin_uni_FK_not_ }); [ConditionalFact] - public virtual void Add_principal_but_not_dependent_one_to_many_prin_uni_FK_set_principal_nav_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_principal_but_not_dependent_one_to_many_prin_uni_FK_set_principal_nav_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new CategoryPN { Id1 = -77, Id2 = Guid77 }; var dependent = new ProductPN { Id1 = -78, Id2 = Guid78 }; @@ -2238,7 +2238,7 @@ public virtual void Add_principal_but_not_dependent_one_to_many_prin_uni_FK_set_ Assert.Equal(EntityState.Added, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -2253,9 +2253,9 @@ public virtual void Add_principal_but_not_dependent_one_to_many_prin_uni_FK_set_ }); [ConditionalFact] - public virtual void Add_principal_but_not_dependent_one_to_many_prin_uni_FK_not_set_principal_nav_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_principal_but_not_dependent_one_to_many_prin_uni_FK_not_set_principal_nav_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new CategoryPN(); var dependent = new ProductPN(); @@ -2283,7 +2283,7 @@ public virtual void Add_principal_but_not_dependent_one_to_many_prin_uni_FK_not_ Assert.Equal(EntityState.Added, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -2298,9 +2298,9 @@ public virtual void Add_principal_but_not_dependent_one_to_many_prin_uni_FK_not_ }); [ConditionalFact] - public virtual void Add_dependent_but_not_principal_one_to_many_dep_uni_FK_set_no_navs_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_dependent_but_not_principal_one_to_many_dep_uni_FK_set_no_navs_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new CategoryDN { Id1 = -77, Id2 = Guid77 }; var dependent = new ProductDN { Id1 = -78, Id2 = Guid78 }; @@ -2327,11 +2327,11 @@ public virtual void Add_dependent_but_not_principal_one_to_many_dep_uni_FK_set_n if (EnforcesFKs) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); } AssertFixup( @@ -2347,9 +2347,9 @@ public virtual void Add_dependent_but_not_principal_one_to_many_dep_uni_FK_set_n }); [ConditionalFact] - public virtual void Add_dependent_but_not_principal_one_to_many_dep_uni_FK_set_dependent_nav_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_dependent_but_not_principal_one_to_many_dep_uni_FK_set_dependent_nav_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new CategoryDN { Id1 = -77, Id2 = Guid77 }; var dependent = new ProductDN { Id1 = -78, Id2 = Guid78 }; @@ -2375,7 +2375,7 @@ public virtual void Add_dependent_but_not_principal_one_to_many_dep_uni_FK_set_d Assert.Equal(EntityState.Added, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -2390,9 +2390,9 @@ public virtual void Add_dependent_but_not_principal_one_to_many_dep_uni_FK_set_d }); [ConditionalFact] - public virtual void Add_dependent_but_not_principal_one_to_many_dep_uni_FK_not_set_dependent_nav_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_dependent_but_not_principal_one_to_many_dep_uni_FK_not_set_dependent_nav_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new CategoryDN(); var dependent = new ProductDN(); @@ -2420,7 +2420,7 @@ public virtual void Add_dependent_but_not_principal_one_to_many_dep_uni_FK_not_s Assert.Equal(EntityState.Added, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -2435,9 +2435,9 @@ public virtual void Add_dependent_but_not_principal_one_to_many_dep_uni_FK_not_s }); [ConditionalFact] - public virtual void Add_principal_but_not_dependent_one_to_many_dep_uni_FK_set_no_navs_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_principal_but_not_dependent_one_to_many_dep_uni_FK_set_no_navs_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new CategoryDN { Id1 = -77, Id2 = Guid77 }; var dependent = new ProductDN { Id1 = -78, Id2 = Guid78 }; @@ -2462,7 +2462,7 @@ public virtual void Add_principal_but_not_dependent_one_to_many_dep_uni_FK_set_n Assert.Equal(EntityState.Detached, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -2475,9 +2475,9 @@ public virtual void Add_principal_but_not_dependent_one_to_many_dep_uni_FK_set_n }); [ConditionalFact] - public virtual void Add_principal_but_not_dependent_one_to_many_dep_uni_FK_set_dependent_nav_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_principal_but_not_dependent_one_to_many_dep_uni_FK_set_dependent_nav_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new CategoryDN { Id1 = -77, Id2 = Guid77 }; var dependent = new ProductDN { Id1 = -78, Id2 = Guid78 }; @@ -2503,7 +2503,7 @@ public virtual void Add_principal_but_not_dependent_one_to_many_dep_uni_FK_set_d Assert.Equal(EntityState.Detached, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -2516,9 +2516,9 @@ public virtual void Add_principal_but_not_dependent_one_to_many_dep_uni_FK_set_d }); [ConditionalFact] - public virtual void Add_principal_but_not_dependent_one_to_many_dep_uni_FK_not_set_dependent_nav_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_principal_but_not_dependent_one_to_many_dep_uni_FK_not_set_dependent_nav_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new CategoryDN(); var dependent = new ProductDN(); @@ -2539,7 +2539,7 @@ public virtual void Add_principal_but_not_dependent_one_to_many_dep_uni_FK_not_s Assert.Equal(EntityState.Detached, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -2553,9 +2553,9 @@ public virtual void Add_principal_but_not_dependent_one_to_many_dep_uni_FK_not_s }); [ConditionalFact] - public virtual void Add_dependent_but_not_principal_one_to_many_no_navs_FK_set_no_navs_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_dependent_but_not_principal_one_to_many_no_navs_FK_set_no_navs_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new CategoryNN { Id1 = -77, Id2 = Guid77 }; var dependent = new ProductNN { Id1 = -78, Id2 = Guid78 }; @@ -2581,11 +2581,11 @@ public virtual void Add_dependent_but_not_principal_one_to_many_no_navs_FK_set_n if (EnforcesFKs) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); } AssertFixup( @@ -2600,9 +2600,9 @@ public virtual void Add_dependent_but_not_principal_one_to_many_no_navs_FK_set_n }); [ConditionalFact] - public virtual void Add_principal_but_not_dependent_one_to_many_no_navs_FK_set_no_navs_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_principal_but_not_dependent_one_to_many_no_navs_FK_set_no_navs_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new CategoryNN { Id1 = -77, Id2 = Guid77 }; var dependent = new ProductNN { Id1 = -78, Id2 = Guid78 }; @@ -2626,7 +2626,7 @@ public virtual void Add_principal_but_not_dependent_one_to_many_no_navs_FK_set_n Assert.Equal(EntityState.Detached, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -2638,9 +2638,9 @@ public virtual void Add_principal_but_not_dependent_one_to_many_no_navs_FK_set_n }); [ConditionalFact] - public virtual void Add_dependent_but_not_principal_one_to_one_FK_set_both_navs_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_dependent_but_not_principal_one_to_one_FK_set_both_navs_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new Parent { Id1 = -77, Id2 = Guid77 }; var dependent = new Child { Id1 = -78, Id2 = Guid78 }; @@ -2668,7 +2668,7 @@ public virtual void Add_dependent_but_not_principal_one_to_one_FK_set_both_navs_ Assert.Equal(EntityState.Added, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -2684,9 +2684,9 @@ public virtual void Add_dependent_but_not_principal_one_to_one_FK_set_both_navs_ }); [ConditionalFact] - public virtual void Add_dependent_but_not_principal_one_to_one_FK_not_set_both_navs_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_dependent_but_not_principal_one_to_one_FK_not_set_both_navs_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new Parent(); var dependent = new Child(); @@ -2716,7 +2716,7 @@ public virtual void Add_dependent_but_not_principal_one_to_one_FK_not_set_both_n Assert.Equal(EntityState.Added, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -2732,9 +2732,9 @@ public virtual void Add_dependent_but_not_principal_one_to_one_FK_not_set_both_n }); [ConditionalFact] - public virtual void Add_dependent_but_not_principal_one_to_one_FK_set_no_navs_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_dependent_but_not_principal_one_to_one_FK_set_no_navs_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new Parent { Id1 = -77, Id2 = Guid77 }; var dependent = new Child { Id1 = -78, Id2 = Guid78 }; @@ -2762,11 +2762,11 @@ public virtual void Add_dependent_but_not_principal_one_to_one_FK_set_no_navs_se if (EnforcesFKs) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); } AssertFixup( @@ -2783,9 +2783,9 @@ public virtual void Add_dependent_but_not_principal_one_to_one_FK_set_no_navs_se }); [ConditionalFact] - public virtual void Add_dependent_but_not_principal_one_to_one_FK_set_principal_nav_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_dependent_but_not_principal_one_to_one_FK_set_principal_nav_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new Parent { Id1 = -77, Id2 = Guid77 }; var dependent = new Child { Id1 = -78, Id2 = Guid78 }; @@ -2814,11 +2814,11 @@ public virtual void Add_dependent_but_not_principal_one_to_one_FK_set_principal_ if (EnforcesFKs) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); } AssertFixup( @@ -2835,9 +2835,9 @@ public virtual void Add_dependent_but_not_principal_one_to_one_FK_set_principal_ }); [ConditionalFact] - public virtual void Add_dependent_but_not_principal_one_to_one_FK_set_dependent_nav_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_dependent_but_not_principal_one_to_one_FK_set_dependent_nav_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new Parent { Id1 = -77, Id2 = Guid77 }; var dependent = new Child { Id1 = -78, Id2 = Guid78 }; @@ -2864,7 +2864,7 @@ public virtual void Add_dependent_but_not_principal_one_to_one_FK_set_dependent_ Assert.Equal(EntityState.Added, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -2880,9 +2880,9 @@ public virtual void Add_dependent_but_not_principal_one_to_one_FK_set_dependent_ }); [ConditionalFact] - public virtual void Add_dependent_but_not_principal_one_to_one_FK_not_set_principal_nav_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_dependent_but_not_principal_one_to_one_FK_not_set_principal_nav_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new Parent(); var dependent = new Child(); @@ -2906,11 +2906,11 @@ public virtual void Add_dependent_but_not_principal_one_to_one_FK_not_set_princi if (EnforcesFKs) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); } AssertFixup( @@ -2926,9 +2926,9 @@ public virtual void Add_dependent_but_not_principal_one_to_one_FK_not_set_princi }); [ConditionalFact] - public virtual void Add_dependent_but_not_principal_one_to_one_FK_not_set_dependent_nav_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_dependent_but_not_principal_one_to_one_FK_not_set_dependent_nav_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new Parent(); var dependent = new Child(); @@ -2957,7 +2957,7 @@ public virtual void Add_dependent_but_not_principal_one_to_one_FK_not_set_depend Assert.Equal(EntityState.Added, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -2973,9 +2973,9 @@ public virtual void Add_dependent_but_not_principal_one_to_one_FK_not_set_depend }); [ConditionalFact] - public virtual void Add_principal_but_not_dependent_one_to_one_FK_set_both_navs_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_principal_but_not_dependent_one_to_one_FK_set_both_navs_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new Parent { Id1 = -77, Id2 = Guid77 }; var dependent = new Child { Id1 = -78, Id2 = Guid78 }; @@ -3003,7 +3003,7 @@ public virtual void Add_principal_but_not_dependent_one_to_one_FK_set_both_navs_ Assert.Equal(EntityState.Added, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -3019,9 +3019,9 @@ public virtual void Add_principal_but_not_dependent_one_to_one_FK_set_both_navs_ }); [ConditionalFact] - public virtual void Add_principal_but_not_dependent_one_to_one_FK_not_set_both_navs_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_principal_but_not_dependent_one_to_one_FK_not_set_both_navs_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new Parent(); var dependent = new Child(); @@ -3051,7 +3051,7 @@ public virtual void Add_principal_but_not_dependent_one_to_one_FK_not_set_both_n Assert.Equal(EntityState.Added, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -3067,9 +3067,9 @@ public virtual void Add_principal_but_not_dependent_one_to_one_FK_not_set_both_n }); [ConditionalFact] - public virtual void Add_principal_but_not_dependent_one_to_one_FK_set_no_navs_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_principal_but_not_dependent_one_to_one_FK_set_no_navs_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new Parent { Id1 = -77, Id2 = Guid77 }; var dependent = new Child { Id1 = -78, Id2 = Guid78 }; @@ -3095,7 +3095,7 @@ public virtual void Add_principal_but_not_dependent_one_to_one_FK_set_no_navs_se Assert.Equal(EntityState.Detached, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -3109,9 +3109,9 @@ public virtual void Add_principal_but_not_dependent_one_to_one_FK_set_no_navs_se }); [ConditionalFact] - public virtual void Add_principal_but_not_dependent_one_to_one_FK_set_principal_nav_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_principal_but_not_dependent_one_to_one_FK_set_principal_nav_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new Parent { Id1 = -77, Id2 = Guid77 }; var dependent = new Child { Id1 = -78, Id2 = Guid78 }; @@ -3138,7 +3138,7 @@ public virtual void Add_principal_but_not_dependent_one_to_one_FK_set_principal_ Assert.Equal(EntityState.Added, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -3154,9 +3154,9 @@ public virtual void Add_principal_but_not_dependent_one_to_one_FK_set_principal_ }); [ConditionalFact] - public virtual void Add_principal_but_not_dependent_one_to_one_FK_set_dependent_nav_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_principal_but_not_dependent_one_to_one_FK_set_dependent_nav_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new Parent { Id1 = -77, Id2 = Guid77 }; var dependent = new Child { Id1 = -78, Id2 = Guid78 }; @@ -3183,7 +3183,7 @@ public virtual void Add_principal_but_not_dependent_one_to_one_FK_set_dependent_ Assert.Equal(EntityState.Detached, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -3197,9 +3197,9 @@ public virtual void Add_principal_but_not_dependent_one_to_one_FK_set_dependent_ }); [ConditionalFact] - public virtual void Add_principal_but_not_dependent_one_to_one_FK_not_set_principal_nav_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_principal_but_not_dependent_one_to_one_FK_not_set_principal_nav_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new Parent(); var dependent = new Child(); @@ -3228,7 +3228,7 @@ public virtual void Add_principal_but_not_dependent_one_to_one_FK_not_set_princi Assert.Equal(EntityState.Added, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -3244,9 +3244,9 @@ public virtual void Add_principal_but_not_dependent_one_to_one_FK_not_set_princi }); [ConditionalFact] - public virtual void Add_principal_but_not_dependent_one_to_one_FK_not_set_dependent_nav_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_principal_but_not_dependent_one_to_one_FK_not_set_dependent_nav_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new Parent(); var dependent = new Child(); @@ -3268,7 +3268,7 @@ public virtual void Add_principal_but_not_dependent_one_to_one_FK_not_set_depend Assert.Equal(EntityState.Detached, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -3283,9 +3283,9 @@ public virtual void Add_principal_but_not_dependent_one_to_one_FK_not_set_depend }); [ConditionalFact] - public virtual void Add_dependent_but_not_principal_one_to_one_prin_uni_FK_set_no_navs_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_dependent_but_not_principal_one_to_one_prin_uni_FK_set_no_navs_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new ParentPN { Id1 = -77, Id2 = Guid77 }; var dependent = new ChildPN { Id1 = -78, Id2 = Guid78 }; @@ -3312,11 +3312,11 @@ public virtual void Add_dependent_but_not_principal_one_to_one_prin_uni_FK_set_n if (EnforcesFKs) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); } AssertFixup( @@ -3332,9 +3332,9 @@ public virtual void Add_dependent_but_not_principal_one_to_one_prin_uni_FK_set_n }); [ConditionalFact] - public virtual void Add_principal_but_not_dependent_one_to_one_prin_uni_FK_set_no_navs_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_principal_but_not_dependent_one_to_one_prin_uni_FK_set_no_navs_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new ParentPN { Id1 = -77, Id2 = Guid77 }; var dependent = new ChildPN { Id1 = -78, Id2 = Guid78 }; @@ -3359,7 +3359,7 @@ public virtual void Add_principal_but_not_dependent_one_to_one_prin_uni_FK_set_n Assert.Equal(EntityState.Detached, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -3372,9 +3372,9 @@ public virtual void Add_principal_but_not_dependent_one_to_one_prin_uni_FK_set_n }); [ConditionalFact] - public virtual void Add_dependent_but_not_principal_one_to_one_prin_uni_FK_set_principal_nav_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_dependent_but_not_principal_one_to_one_prin_uni_FK_set_principal_nav_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new ParentPN { Id1 = -77, Id2 = Guid77 }; var dependent = new ChildPN { Id1 = -78, Id2 = Guid78 }; @@ -3402,11 +3402,11 @@ public virtual void Add_dependent_but_not_principal_one_to_one_prin_uni_FK_set_p if (EnforcesFKs) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); } AssertFixup( @@ -3422,9 +3422,9 @@ public virtual void Add_dependent_but_not_principal_one_to_one_prin_uni_FK_set_p }); [ConditionalFact] - public virtual void Add_dependent_but_not_principal_one_to_one_prin_uni_FK_not_set_principal_nav_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_dependent_but_not_principal_one_to_one_prin_uni_FK_not_set_principal_nav_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new ParentPN(); var dependent = new ChildPN(); @@ -3447,11 +3447,11 @@ public virtual void Add_dependent_but_not_principal_one_to_one_prin_uni_FK_not_s if (EnforcesFKs) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); } AssertFixup( @@ -3466,9 +3466,9 @@ public virtual void Add_dependent_but_not_principal_one_to_one_prin_uni_FK_not_s }); [ConditionalFact] - public virtual void Add_principal_but_not_dependent_one_to_one_prin_uni_FK_set_principal_nav_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_principal_but_not_dependent_one_to_one_prin_uni_FK_set_principal_nav_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new ParentPN { Id1 = -77, Id2 = Guid77 }; var dependent = new ChildPN { Id1 = -78, Id2 = Guid78 }; @@ -3494,7 +3494,7 @@ public virtual void Add_principal_but_not_dependent_one_to_one_prin_uni_FK_set_p Assert.Equal(EntityState.Added, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -3509,9 +3509,9 @@ public virtual void Add_principal_but_not_dependent_one_to_one_prin_uni_FK_set_p }); [ConditionalFact] - public virtual void Add_principal_but_not_dependent_one_to_one_prin_uni_FK_not_set_principal_nav_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_principal_but_not_dependent_one_to_one_prin_uni_FK_not_set_principal_nav_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new ParentPN(); var dependent = new ChildPN(); @@ -3539,7 +3539,7 @@ public virtual void Add_principal_but_not_dependent_one_to_one_prin_uni_FK_not_s Assert.Equal(EntityState.Added, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -3554,9 +3554,9 @@ public virtual void Add_principal_but_not_dependent_one_to_one_prin_uni_FK_not_s }); [ConditionalFact] - public virtual void Add_dependent_but_not_principal_one_to_one_dep_uni_FK_set_no_navs_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_dependent_but_not_principal_one_to_one_dep_uni_FK_set_no_navs_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new ParentDN { Id1 = -77, Id2 = Guid77 }; var dependent = new ChildDN { Id1 = -78, Id2 = Guid78 }; @@ -3583,11 +3583,11 @@ public virtual void Add_dependent_but_not_principal_one_to_one_dep_uni_FK_set_no if (EnforcesFKs) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); } AssertFixup( @@ -3603,9 +3603,9 @@ public virtual void Add_dependent_but_not_principal_one_to_one_dep_uni_FK_set_no }); [ConditionalFact] - public virtual void Add_dependent_but_not_principal_one_to_one_dep_uni_FK_set_dependent_nav_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_dependent_but_not_principal_one_to_one_dep_uni_FK_set_dependent_nav_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new ParentDN { Id1 = -77, Id2 = Guid77 }; var dependent = new ChildDN { Id1 = -78, Id2 = Guid78 }; @@ -3631,7 +3631,7 @@ public virtual void Add_dependent_but_not_principal_one_to_one_dep_uni_FK_set_de Assert.Equal(EntityState.Added, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -3646,9 +3646,9 @@ public virtual void Add_dependent_but_not_principal_one_to_one_dep_uni_FK_set_de }); [ConditionalFact] - public virtual void Add_dependent_but_not_principal_one_to_one_dep_uni_FK_not_set_dependent_nav_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_dependent_but_not_principal_one_to_one_dep_uni_FK_not_set_dependent_nav_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new ParentDN(); var dependent = new ChildDN(); @@ -3676,7 +3676,7 @@ public virtual void Add_dependent_but_not_principal_one_to_one_dep_uni_FK_not_se Assert.Equal(EntityState.Added, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -3691,9 +3691,9 @@ public virtual void Add_dependent_but_not_principal_one_to_one_dep_uni_FK_not_se }); [ConditionalFact] - public virtual void Add_principal_but_not_dependent_one_to_one_dep_uni_FK_set_no_navs_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_principal_but_not_dependent_one_to_one_dep_uni_FK_set_no_navs_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new ParentDN { Id1 = -77, Id2 = Guid77 }; var dependent = new ChildDN { Id1 = -78, Id2 = Guid78 }; @@ -3718,7 +3718,7 @@ public virtual void Add_principal_but_not_dependent_one_to_one_dep_uni_FK_set_no Assert.Equal(EntityState.Detached, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -3731,9 +3731,9 @@ public virtual void Add_principal_but_not_dependent_one_to_one_dep_uni_FK_set_no }); [ConditionalFact] - public virtual void Add_principal_but_not_dependent_one_to_one_dep_uni_FK_set_dependent_nav_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_principal_but_not_dependent_one_to_one_dep_uni_FK_set_dependent_nav_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new ParentDN { Id1 = -77, Id2 = Guid77 }; var dependent = new ChildDN { Id1 = -78, Id2 = Guid78 }; @@ -3759,7 +3759,7 @@ public virtual void Add_principal_but_not_dependent_one_to_one_dep_uni_FK_set_de Assert.Equal(EntityState.Detached, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -3772,9 +3772,9 @@ public virtual void Add_principal_but_not_dependent_one_to_one_dep_uni_FK_set_de }); [ConditionalFact] - public virtual void Add_principal_but_not_dependent_one_to_one_dep_uni_FK_not_set_dependent_nav_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_principal_but_not_dependent_one_to_one_dep_uni_FK_not_set_dependent_nav_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new ParentDN(); var dependent = new ChildDN(); @@ -3795,7 +3795,7 @@ public virtual void Add_principal_but_not_dependent_one_to_one_dep_uni_FK_not_se Assert.Equal(EntityState.Detached, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -3809,9 +3809,9 @@ public virtual void Add_principal_but_not_dependent_one_to_one_dep_uni_FK_not_se }); [ConditionalFact] - public virtual void Add_dependent_but_not_principal_one_to_one_no_navs_FK_set_no_navs_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_dependent_but_not_principal_one_to_one_no_navs_FK_set_no_navs_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new ParentNN { Id1 = -77, Id2 = Guid77 }; var dependent = new ChildNN { Id1 = -78, Id2 = Guid78 }; @@ -3837,11 +3837,11 @@ public virtual void Add_dependent_but_not_principal_one_to_one_no_navs_FK_set_no if (EnforcesFKs) { - Assert.Throws(() => context.SaveChanges()); + await Assert.ThrowsAsync(() => context.SaveChangesAsync()); } else { - context.SaveChanges(); + await context.SaveChangesAsync(); } AssertFixup( @@ -3856,9 +3856,9 @@ public virtual void Add_dependent_but_not_principal_one_to_one_no_navs_FK_set_no }); [ConditionalFact] - public virtual void Add_principal_but_not_dependent_one_to_one_no_navs_FK_set_no_navs_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Add_principal_but_not_dependent_one_to_one_no_navs_FK_set_no_navs_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var principal = new ParentNN { Id1 = -77, Id2 = Guid77 }; var dependent = new ChildNN { Id1 = -78, Id2 = Guid78 }; @@ -3882,7 +3882,7 @@ public virtual void Add_principal_but_not_dependent_one_to_one_no_navs_FK_set_no Assert.Equal(EntityState.Detached, context.Entry(dependent).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -3894,8 +3894,8 @@ public virtual void Add_principal_but_not_dependent_one_to_one_no_navs_FK_set_no }); [ConditionalFact] - public virtual void Add_overlapping_graph_from_level() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_overlapping_graph_from_level() + => ExecuteWithStrategyInTransactionAsync( context => { var game = new Game { Id = Guid77 }; @@ -3907,12 +3907,12 @@ public virtual void Add_overlapping_graph_from_level() context.Add(level); - AssertFixupAndSave(context, game, level, item); + return AssertFixupAndSaveAsync(context, game, level, item); }); [ConditionalFact] - public virtual void Add_overlapping_graph_from_game() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_overlapping_graph_from_game() + => ExecuteWithStrategyInTransactionAsync( context => { var level = new Level { Id = -77 }; @@ -3925,12 +3925,12 @@ public virtual void Add_overlapping_graph_from_game() context.Add(game); - AssertFixupAndSave(context, game, level, item); + return AssertFixupAndSaveAsync(context, game, level, item); }); [ConditionalFact] - public virtual void Add_overlapping_graph_from_item() - => ExecuteWithStrategyInTransaction( + public virtual Task Add_overlapping_graph_from_item() + => ExecuteWithStrategyInTransactionAsync( context => { var game = new Game { Id = Guid77 }; @@ -3941,7 +3941,7 @@ public virtual void Add_overlapping_graph_from_item() context.Add(item); - AssertFixupAndSave(context, game, level, item); + return AssertFixupAndSaveAsync(context, game, level, item); }); [ConditionalFact] @@ -3958,7 +3958,7 @@ public virtual void Temporary_value_equals_database_generated_value() Assert.Equal(EntityState.Unchanged, internalEntry.EntityState); } - private void AssertFixupAndSave(DbContext context, Game game, Level level, Item item) + private async Task AssertFixupAndSaveAsync(DbContext context, Game game, Level level, Item item) { AssertFixup( context, @@ -3981,7 +3981,7 @@ private void AssertFixupAndSave(DbContext context, Game game, Level level, Item Assert.Equal(EntityState.Added, context.Entry(item).State); }); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertFixup( context, @@ -4027,11 +4027,11 @@ public virtual void Remove_overlapping_principal() } [ConditionalFact] - public virtual void Multi_level_add_replace_and_save() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Multi_level_add_replace_and_save() + => ExecuteWithStrategyInTransactionAsync( + async context => { - var firstLevel = context.Set().Single(); + var firstLevel = await context.Set().SingleAsync(); AddData(firstLevel); @@ -4064,7 +4064,7 @@ public virtual void Multi_level_add_replace_and_save() originalThirdLevels.Select(l => context.Entry(l).State), s => Assert.Equal(EntityState.Detached, s)); - context.SaveChanges(); + await context.SaveChangesAsync(); AssertValidFks(context, firstLevel, tempKeys: false); }); @@ -4358,8 +4358,8 @@ protected virtual void UseTransaction(DatabaseFacade facade, IDbContextTransacti { } - protected virtual void ExecuteWithStrategyInTransaction(Action testOperation) - => TestHelpers.ExecuteWithStrategyInTransaction(CreateContext, UseTransaction, testOperation); + protected virtual Task ExecuteWithStrategyInTransactionAsync(Func testOperation) + => TestHelpers.ExecuteWithStrategyInTransactionAsync(CreateContext, UseTransaction, testOperation); protected DbContext CreateContext() => Fixture.CreateContext(); diff --git a/test/EFCore.Specification.Tests/StoreGeneratedTestBase.cs b/test/EFCore.Specification.Tests/StoreGeneratedTestBase.cs index 3827310f7e1..3cb1399aec1 100644 --- a/test/EFCore.Specification.Tests/StoreGeneratedTestBase.cs +++ b/test/EFCore.Specification.Tests/StoreGeneratedTestBase.cs @@ -18,30 +18,29 @@ protected StoreGeneratedTestBase(TFixture fixture) protected TFixture Fixture { get; } [ConditionalFact] - public virtual void Value_generation_works_for_common_GUID_conversions() + public virtual async Task Value_generation_works_for_common_GUID_conversions() { - ValueGenerationPositive(Fixture.GuidSentinel); - ValueGenerationPositive(Fixture.GuidSentinel); + await ValueGenerationPositive(Fixture.GuidSentinel); + await ValueGenerationPositive(Fixture.GuidSentinel); } - private void ValueGenerationPositive(TKey? sentinel) + private Task ValueGenerationPositive(TKey? sentinel) where TEntity : WithConverter, new() { - TKey? id; + TKey? id = default; - using (var context = CreateContext()) - { - var entity = context.Add(new TEntity { Id = sentinel }).Entity; - - context.SaveChanges(); + return ExecuteWithStrategyInTransactionAsync( + async context => + { + var entity = context.Add(new TEntity { Id = sentinel }).Entity; - id = entity.Id; - } + await context.SaveChangesAsync(); - using (var context = CreateContext()) - { - Assert.Equal(id, context.Set().Single(e => e.Id!.Equals(id)).Id); - } + id = entity.Id; + }, async context => + { + Assert.Equal(id, (await context.Set().SingleAsync(e => e.Id!.Equals(id))).Id); + }); } [ConditionalTheory] @@ -57,15 +56,15 @@ private void ValueGenerationPositive(TKey? sentinel) [InlineData(nameof(Anais.OnUpdateThrowBeforeUseAfter))] [InlineData(nameof(Anais.OnUpdateThrowBeforeIgnoreAfter))] [InlineData(nameof(Anais.OnUpdateThrowBeforeThrowAfter))] - public virtual void Before_save_throw_always_throws_if_value_set(string propertyName) - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Before_save_throw_always_throws_if_value_set(string propertyName) + => ExecuteWithStrategyInTransactionAsync( + async context => { context.Add(WithValue(propertyName, Fixture.IntSentinel, Fixture.StringSentinel)); Assert.Equal( CoreStrings.PropertyReadOnlyBeforeSave(propertyName, "Anais"), - Assert.Throws(() => context.SaveChanges()).Message); + (await Assert.ThrowsAsync(() => context.SaveChangesAsync())).Message); }); [ConditionalTheory] @@ -81,19 +80,18 @@ public virtual void Before_save_throw_always_throws_if_value_set(string property [InlineData(nameof(Anais.OnUpdateThrowBeforeUseAfter), "Rabbit")] [InlineData(nameof(Anais.OnUpdateThrowBeforeIgnoreAfter), "Rabbit")] [InlineData(nameof(Anais.OnUpdateThrowBeforeThrowAfter), "Rabbit")] - public virtual void Before_save_throw_ignores_value_if_not_set(string propertyName, string? expectedValue) + public virtual Task Before_save_throw_ignores_value_if_not_set(string propertyName, string? expectedValue) { var id = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var entity = context.Add(Anais.Create(Fixture.IntSentinel, Fixture.StringSentinel)).Entity; - context.SaveChanges(); + await context.SaveChangesAsync(); id = entity.Id; - }, - context => Assert.Equal(expectedValue, GetValue(context.Set().Find(id)!, propertyName))); + }, async context => Assert.Equal(expectedValue, GetValue((await context.Set().FindAsync(id))!, propertyName))); } [ConditionalTheory] @@ -112,19 +110,18 @@ public virtual void Before_save_throw_ignores_value_if_not_set(string propertyNa [InlineData(nameof(Anais.OnUpdateUseBeforeUseAfter))] [InlineData(nameof(Anais.OnUpdateUseBeforeIgnoreAfter))] [InlineData(nameof(Anais.OnUpdateUseBeforeThrowAfter))] - public virtual void Before_save_use_always_uses_value_if_set(string propertyName) + public virtual Task Before_save_use_always_uses_value_if_set(string propertyName) { var id = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var entity = context.Add(WithValue(propertyName, Fixture.IntSentinel, Fixture.StringSentinel)).Entity; - context.SaveChanges(); + await context.SaveChangesAsync(); id = entity.Id; - }, - context => Assert.Equal("Pink", GetValue(context.Set().Find(id)!, propertyName))); + }, async context => Assert.Equal("Pink", GetValue((await context.Set().FindAsync(id))!, propertyName))); } [ConditionalTheory] @@ -143,7 +140,7 @@ public virtual void Before_save_use_always_uses_value_if_set(string propertyName [InlineData(nameof(Anais.OnUpdateUseBeforeUseAfter), "S")] [InlineData(nameof(Anais.OnUpdateUseBeforeIgnoreAfter), "S")] [InlineData(nameof(Anais.OnUpdateUseBeforeThrowAfter), "S")] - public virtual void Before_save_use_ignores_value_if_not_set(string propertyName, string? expectedValue) + public virtual Task Before_save_use_ignores_value_if_not_set(string propertyName, string? expectedValue) { if (expectedValue == "S") { @@ -151,16 +148,15 @@ public virtual void Before_save_use_ignores_value_if_not_set(string propertyName } var id = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var entity = context.Add(Anais.Create(Fixture.IntSentinel, Fixture.StringSentinel)).Entity; - context.SaveChanges(); + await context.SaveChangesAsync(); id = entity.Id; - }, - context => Assert.Equal(expectedValue, GetValue(context.Set().Find(id)!, propertyName))); + }, async context => Assert.Equal(expectedValue, GetValue((await context.Set().FindAsync(id))!, propertyName))); } [ConditionalTheory] @@ -177,19 +173,18 @@ public virtual void Before_save_use_ignores_value_if_not_set(string propertyName [InlineData(nameof(Anais.OnUpdateIgnoreBeforeUseAfter), "Rabbit")] [InlineData(nameof(Anais.OnUpdateIgnoreBeforeIgnoreAfter), "Rabbit")] [InlineData(nameof(Anais.OnUpdateIgnoreBeforeThrowAfter), "Rabbit")] - public virtual void Before_save_ignore_ignores_value_if_not_set(string propertyName, string? expectedValue) + public virtual Task Before_save_ignore_ignores_value_if_not_set(string propertyName, string? expectedValue) { var id = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var entity = context.Add(Anais.Create(Fixture.IntSentinel, Fixture.StringSentinel)).Entity; - context.SaveChanges(); + await context.SaveChangesAsync(); id = entity.Id; - }, - context => Assert.Equal(expectedValue, GetValue(context.Set().Find(id)!, propertyName))); + }, async context => Assert.Equal(expectedValue, GetValue((await context.Set().FindAsync(id))!, propertyName))); } [ConditionalTheory] @@ -206,19 +201,18 @@ public virtual void Before_save_ignore_ignores_value_if_not_set(string propertyN [InlineData(nameof(Anais.OnUpdateIgnoreBeforeUseAfter), "Rabbit")] [InlineData(nameof(Anais.OnUpdateIgnoreBeforeIgnoreAfter), "Rabbit")] [InlineData(nameof(Anais.OnUpdateIgnoreBeforeThrowAfter), "Rabbit")] - public virtual void Before_save_ignore_ignores_value_even_if_set(string propertyName, string? expectedValue) + public virtual Task Before_save_ignore_ignores_value_even_if_set(string propertyName, string? expectedValue) { var id = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var entity = context.Add(WithValue(propertyName, Fixture.IntSentinel, Fixture.StringSentinel)).Entity; - context.SaveChanges(); + await context.SaveChangesAsync(); id = entity.Id; - }, - context => Assert.Equal(expectedValue, GetValue(context.Set().Find(id)!, propertyName))); + }, async context => Assert.Equal(expectedValue, GetValue((await context.Set().FindAsync(id))!, propertyName))); } [ConditionalTheory] @@ -234,15 +228,15 @@ public virtual void Before_save_ignore_ignores_value_even_if_set(string property [InlineData(nameof(Anais.OnUpdateUseBeforeThrowAfter))] [InlineData(nameof(Anais.OnUpdateIgnoreBeforeThrowAfter))] [InlineData(nameof(Anais.OnUpdateThrowBeforeThrowAfter))] - public virtual void After_save_throw_always_throws_if_value_modified(string propertyName) - => ExecuteWithStrategyInTransaction( - context => + public virtual Task After_save_throw_always_throws_if_value_modified(string propertyName) + => ExecuteWithStrategyInTransactionAsync( + async context => { context.Attach(WithValue(propertyName, 1, Fixture.StringSentinel)).Property(propertyName).IsModified = true; Assert.Equal( CoreStrings.PropertyReadOnlyAfterSave(propertyName, "Anais"), - Assert.Throws(() => context.SaveChanges()).Message); + (await Assert.ThrowsAsync(() => context.SaveChangesAsync())).Message); }); [ConditionalTheory] @@ -258,7 +252,7 @@ public virtual void After_save_throw_always_throws_if_value_modified(string prop [InlineData(nameof(Anais.OnUpdateUseBeforeThrowAfter), "S")] [InlineData(nameof(Anais.OnUpdateIgnoreBeforeThrowAfter), "Rabbit")] [InlineData(nameof(Anais.OnUpdateThrowBeforeThrowAfter), "Rabbit")] - public virtual void After_save_throw_ignores_value_if_not_modified(string propertyName, string? expectedValue) + public virtual Task After_save_throw_ignores_value_if_not_modified(string propertyName, string? expectedValue) { if (expectedValue == "S") { @@ -266,25 +260,25 @@ public virtual void After_save_throw_ignores_value_if_not_modified(string proper } var id = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var entity = context.Add(Anais.Create(Fixture.IntSentinel, Fixture.StringSentinel)).Entity; - context.SaveChanges(); + await context.SaveChangesAsync(); id = entity.Id; }, - context => + async context => { - var entry = context.Entry(context.Set().Find(id)!); + var entry = context.Entry((await context.Set().FindAsync(id))!); entry.State = EntityState.Modified; entry.Property(propertyName).CurrentValue = "Daisy"; entry.Property(propertyName).IsModified = false; - context.SaveChanges(); + await context.SaveChangesAsync(); }, - context => Assert.Equal(expectedValue, GetValue(context.Set().Find(id)!, propertyName))); + async context => Assert.Equal(expectedValue, GetValue((await context.Set().FindAsync(id))!, propertyName))); } [ConditionalTheory] @@ -302,7 +296,7 @@ public virtual void After_save_throw_ignores_value_if_not_modified(string proper [InlineData(nameof(Anais.OnUpdateUseBeforeIgnoreAfter), "S")] [InlineData(nameof(Anais.OnUpdateIgnoreBeforeIgnoreAfter), "Rabbit")] [InlineData(nameof(Anais.OnUpdateThrowBeforeIgnoreAfter), "Rabbit")] - public virtual void After_save_ignore_ignores_value_if_not_modified(string propertyName, string? expectedValue) + public virtual Task After_save_ignore_ignores_value_if_not_modified(string propertyName, string? expectedValue) { if (expectedValue == "S") { @@ -310,25 +304,25 @@ public virtual void After_save_ignore_ignores_value_if_not_modified(string prope } var id = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var entity = context.Add(Anais.Create(Fixture.IntSentinel, Fixture.StringSentinel)).Entity; - context.SaveChanges(); + await context.SaveChangesAsync(); id = entity.Id; }, - context => + async context => { - var entry = context.Entry(context.Set().Find(id)!); + var entry = context.Entry((await context.Set().FindAsync(id))!); entry.State = EntityState.Modified; entry.Property(propertyName).CurrentValue = "Daisy"; entry.Property(propertyName).IsModified = false; - context.SaveChanges(); + await context.SaveChangesAsync(); }, - context => Assert.Equal(expectedValue, GetValue(context.Set().Find(id)!, propertyName))); + async context => Assert.Equal(expectedValue, GetValue((await context.Set().FindAsync(id))!, propertyName))); } [ConditionalTheory] @@ -346,7 +340,7 @@ public virtual void After_save_ignore_ignores_value_if_not_modified(string prope [InlineData(nameof(Anais.OnUpdateUseBeforeIgnoreAfter), "S")] [InlineData(nameof(Anais.OnUpdateIgnoreBeforeIgnoreAfter), "Rabbit")] [InlineData(nameof(Anais.OnUpdateThrowBeforeIgnoreAfter), "Rabbit")] - public virtual void After_save_ignore_ignores_value_even_if_modified(string propertyName, string? expectedValue) + public virtual Task After_save_ignore_ignores_value_even_if_modified(string propertyName, string? expectedValue) { if (expectedValue == "S") { @@ -354,25 +348,25 @@ public virtual void After_save_ignore_ignores_value_even_if_modified(string prop } var id = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var entity = context.Add(Anais.Create(Fixture.IntSentinel, Fixture.StringSentinel)).Entity; - context.SaveChanges(); + await context.SaveChangesAsync(); id = entity.Id; }, - context => + async context => { - var entry = context.Entry(context.Set().Find(id)!); + var entry = context.Entry((await context.Set().FindAsync(id))!); entry.State = EntityState.Modified; entry.Property(propertyName).CurrentValue = "Daisy"; entry.Property(propertyName).IsModified = true; - context.SaveChanges(); + await context.SaveChangesAsync(); }, - context => Assert.Equal(expectedValue, GetValue(context.Set().Find(id)!, propertyName))); + async context => Assert.Equal(expectedValue, GetValue((await context.Set().FindAsync(id))!, propertyName))); } [ConditionalTheory] @@ -392,7 +386,7 @@ public virtual void After_save_ignore_ignores_value_even_if_modified(string prop [InlineData(nameof(Anais.OnUpdateUseBeforeUseAfter), "S")] [InlineData(nameof(Anais.OnUpdateIgnoreBeforeUseAfter), "Rabbit")] [InlineData(nameof(Anais.OnUpdateThrowBeforeUseAfter), "Rabbit")] - public virtual void After_save_use_ignores_value_if_not_modified(string propertyName, string? expectedValue) + public virtual Task After_save_use_ignores_value_if_not_modified(string propertyName, string? expectedValue) { if (expectedValue == "S") { @@ -400,25 +394,25 @@ public virtual void After_save_use_ignores_value_if_not_modified(string property } var id = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var entity = context.Add(Anais.Create(Fixture.IntSentinel, Fixture.StringSentinel)).Entity; - context.SaveChanges(); + await context.SaveChangesAsync(); id = entity.Id; }, - context => + async context => { - var entry = context.Entry(context.Set().Find(id)!); + var entry = context.Entry((await context.Set().FindAsync(id))!); entry.State = EntityState.Modified; entry.Property(propertyName).CurrentValue = "Daisy"; entry.Property(propertyName).IsModified = false; - context.SaveChanges(); + await context.SaveChangesAsync(); }, - context => Assert.Equal(expectedValue, GetValue(context.Set().Find(id)!, propertyName))); + async context => Assert.Equal(expectedValue, GetValue((await context.Set().FindAsync(id))!, propertyName))); } [ConditionalTheory] @@ -436,27 +430,27 @@ public virtual void After_save_use_ignores_value_if_not_modified(string property [InlineData(nameof(Anais.OnUpdateUseBeforeUseAfter), "Daisy")] [InlineData(nameof(Anais.OnUpdateIgnoreBeforeUseAfter), "Daisy")] [InlineData(nameof(Anais.OnUpdateThrowBeforeUseAfter), "Daisy")] - public virtual void After_save_use_uses_value_if_modified(string propertyName, string expectedValue) + public virtual Task After_save_use_uses_value_if_modified(string propertyName, string expectedValue) { var id = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var entity = context.Add(Anais.Create(Fixture.IntSentinel, Fixture.StringSentinel)).Entity; - context.SaveChanges(); + await context.SaveChangesAsync(); id = entity.Id; }, - context => + async context => { - var entry = context.Entry(context.Set().Find(id)!); + var entry = context.Entry((await context.Set().FindAsync(id))!); entry.State = EntityState.Modified; entry.Property(propertyName).CurrentValue = "Daisy"; - context.SaveChanges(); + await context.SaveChangesAsync(); }, - context => Assert.Equal(expectedValue, GetValue(context.Set().Find(id)!, propertyName))); + async context => Assert.Equal(expectedValue, GetValue((await context.Set().FindAsync(id))!, propertyName))); } private static Anais WithValue(string propertyName, int id, string? sentinel) @@ -472,37 +466,37 @@ private static Anais SetValue(Anais entity, string propertyName) => (string?)entity.GetType().GetTypeInfo().GetDeclaredProperty(propertyName)!.GetValue(entity); [ConditionalFact] - public virtual void Identity_key_with_read_only_before_save_throws_if_explicit_values_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Identity_key_with_read_only_before_save_throws_if_explicit_values_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { context.Add(Gumball.Create(Fixture.IntSentinel + 1, Fixture.StringSentinel)); Assert.Equal( CoreStrings.PropertyReadOnlyBeforeSave("Id", "Gumball"), - Assert.Throws(() => context.SaveChanges()).Message); + (await Assert.ThrowsAsync(() => context.SaveChangesAsync())).Message); }); [ConditionalFact] - public virtual void Identity_property_on_Added_entity_with_temporary_value_gets_value_from_store() + public virtual Task Identity_property_on_Added_entity_with_temporary_value_gets_value_from_store() { var id = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var gumball = Gumball.Create(Fixture.IntSentinel, Fixture.StringSentinel); gumball.Identity = "Masami"; var entry = context.Add(gumball); entry.Property(e => e.Identity).IsTemporary = true; - context.SaveChanges(); + await context.SaveChangesAsync(); id = entry.Entity.Id; Assert.Equal("Banana Joe", entry.Entity.Identity); Assert.False(entry.Property(e => e.Identity).IsTemporary); }, - context => Assert.Equal("Banana Joe", context.Set().Single(e => e.Id == id).Identity)); + async context => Assert.Equal("Banana Joe", (await context.Set().SingleAsync(e => e.Id == id)).Identity)); } protected class CompositePrincipal @@ -521,12 +515,12 @@ protected class CompositeDependent } [ConditionalFact] - public virtual void Store_generated_values_are_propagated_with_composite_key_cycles() + public virtual Task Store_generated_values_are_propagated_with_composite_key_cycles() { var id = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var period = new CompositeDependent { @@ -536,11 +530,11 @@ public virtual void Store_generated_values_are_propagated_with_composite_key_cyc }; context.Add(period); - context.SaveChanges(); + await context.SaveChangesAsync(); id = period.PrincipalId; }, - context => Assert.Equal(1, context.Set().Single(e => e.PrincipalId == id).Number)); + async context => Assert.Equal(1, (await context.Set().SingleAsync(e => e.PrincipalId == id)).Number)); } protected class NonStoreGenDependent @@ -561,9 +555,9 @@ protected class StoreGenPrincipal [ConditionalTheory] // Issue #22027 #14192 [InlineData(EntityState.Modified)] [InlineData(EntityState.Deleted)] - public void Change_state_of_entity_with_temp_non_key_does_not_throw(EntityState targetState) - => ExecuteWithStrategyInTransaction( - context => + public Task Change_state_of_entity_with_temp_non_key_does_not_throw(EntityState targetState) + => ExecuteWithStrategyInTransactionAsync( + async context => { var dependent = new NonStoreGenDependent { Id = 89 }; @@ -571,12 +565,12 @@ public void Change_state_of_entity_with_temp_non_key_does_not_throw(EntityState Assert.True(context.Entry(dependent).Property(e => e.HasTemp).IsTemporary); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.Entry(dependent).Property(e => e.HasTemp).IsTemporary); Assert.Equal(777, dependent.HasTemp); }, - context => + async context => { var principal = new StoreGenPrincipal { Id = Fixture.IntSentinel }; var dependent = new NonStoreGenDependent { Id = 89, StoreGenPrincipal = principal }; @@ -590,7 +584,7 @@ public void Change_state_of_entity_with_temp_non_key_does_not_throw(EntityState Assert.True(context.Entry(dependent).Property(e => e.HasTemp).IsTemporary); Assert.True(context.Entry(dependent).Property(e => e.StoreGenPrincipalId).IsTemporary); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.Equal(EntityState.Unchanged, context.Entry(principal).State); @@ -604,9 +598,9 @@ public void Change_state_of_entity_with_temp_non_key_does_not_throw(EntityState }); [ConditionalFact] // Issue #19137 - public void Clearing_optional_FK_does_not_leave_temporary_value() - => ExecuteWithStrategyInTransaction( - context => + public Task Clearing_optional_FK_does_not_leave_temporary_value() + => ExecuteWithStrategyInTransactionAsync( + async context => { var product = new OptionalProduct { Id = Fixture.IntSentinel }; context.Add(product); @@ -624,7 +618,7 @@ public void Clearing_optional_FK_does_not_leave_temporary_value() Assert.Null(productEntry.Property(e => e.CategoryId).CurrentValue); Assert.False(productEntry.Property(e => e.CategoryId).IsTemporary); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -661,7 +655,7 @@ public void Clearing_optional_FK_does_not_leave_temporary_value() Assert.True(categoryEntry.Property(e => e.Id).CurrentValue < 0); Assert.True(categoryEntry.Property(e => e.Id).IsTemporary); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -702,7 +696,7 @@ public void Clearing_optional_FK_does_not_leave_temporary_value() Assert.True(context.ChangeTracker.HasChanges()); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(context.ChangeTracker.HasChanges()); @@ -737,49 +731,49 @@ protected class OptionalCategory } [ConditionalFact] - public virtual void Identity_property_on_Added_entity_with_temporary_value_gets_value_from_store_even_if_same() + public virtual Task Identity_property_on_Added_entity_with_temporary_value_gets_value_from_store_even_if_same() { var id = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var gumball = Gumball.Create(Fixture.IntSentinel, Fixture.StringSentinel); gumball.Identity = "Banana Joe"; var entry = context.Add(gumball); entry.Property(e => e.Identity).IsTemporary = true; - context.SaveChanges(); + await context.SaveChangesAsync(); id = entry.Entity.Id; Assert.Equal("Banana Joe", entry.Entity.Identity); Assert.False(entry.Property(e => e.Identity).IsTemporary); }, - context => Assert.Equal("Banana Joe", context.Set().Single(e => e.Id == id).Identity)); + async context => Assert.Equal("Banana Joe", (await context.Set().SingleAsync(e => e.Id == id)).Identity)); } [ConditionalFact] - public virtual void Identity_property_on_Added_entity_with_default_value_gets_value_from_store() + public virtual Task Identity_property_on_Added_entity_with_default_value_gets_value_from_store() { var id = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var entity = context.Add(Gumball.Create(Fixture.IntSentinel, Fixture.StringSentinel)).Entity; - context.SaveChanges(); + await context.SaveChangesAsync(); id = entity.Id; Assert.Equal("Banana Joe", entity.Identity); }, - context => Assert.Equal("Banana Joe", context.Set().Single(e => e.Id == id).Identity)); + async context => Assert.Equal("Banana Joe", (await context.Set().SingleAsync(e => e.Id == id)).Identity)); } [ConditionalFact] - public virtual void Identity_property_on_Added_entity_with_read_only_before_save_throws_if_explicit_values_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Identity_property_on_Added_entity_with_read_only_before_save_throws_if_explicit_values_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var gumball = Gumball.Create(Fixture.IntSentinel, Fixture.StringSentinel); gumball.IdentityReadOnlyBeforeSave = "Masami"; @@ -787,45 +781,45 @@ public virtual void Identity_property_on_Added_entity_with_read_only_before_save Assert.Equal( CoreStrings.PropertyReadOnlyBeforeSave("IdentityReadOnlyBeforeSave", "Gumball"), - Assert.Throws(() => context.SaveChanges()).Message); + (await Assert.ThrowsAsync(() => context.SaveChangesAsync())).Message); }); [ConditionalFact] - public virtual void Identity_property_on_Added_entity_can_have_value_set_explicitly() + public virtual Task Identity_property_on_Added_entity_can_have_value_set_explicitly() { var id = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var gumball = Gumball.Create(Fixture.IntSentinel, Fixture.StringSentinel); gumball.Identity = "Masami"; var entity = context.Add(gumball).Entity; - context.SaveChanges(); + await context.SaveChangesAsync(); id = entity.Id; Assert.Equal("Masami", entity.Identity); }, - context => Assert.Equal("Masami", context.Set().Single(e => e.Id == id).Identity)); + async context => Assert.Equal("Masami", (await context.Set().SingleAsync(e => e.Id == id)).Identity)); } [ConditionalFact] - public virtual void Identity_property_on_Modified_entity_with_read_only_after_save_throws_if_value_is_in_modified_state() + public virtual Task Identity_property_on_Modified_entity_with_read_only_after_save_throws_if_value_is_in_modified_state() { var id = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var entity = context.Add(Gumball.Create(Fixture.IntSentinel, Fixture.StringSentinel)).Entity; - context.SaveChanges(); + await context.SaveChangesAsync(); id = entity.Id; }, - context => + async context => { - var gumball = context.Set().Single(e => e.Id == id); + var gumball = await context.Set().SingleAsync(e => e.Id == id); Assert.Equal("Anton", gumball.IdentityReadOnlyAfterSave); @@ -834,55 +828,55 @@ public virtual void Identity_property_on_Modified_entity_with_read_only_after_sa Assert.Equal( CoreStrings.PropertyReadOnlyAfterSave("IdentityReadOnlyAfterSave", "Gumball"), - Assert.Throws(() => context.SaveChanges()).Message); + (await Assert.ThrowsAsync(() => context.SaveChangesAsync())).Message); }); } [ConditionalFact] - public virtual void Identity_property_on_Modified_entity_is_included_in_update_when_modified() + public virtual Task Identity_property_on_Modified_entity_is_included_in_update_when_modified() { var id = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var entity = context.Add(Gumball.Create(Fixture.IntSentinel, Fixture.StringSentinel)).Entity; - context.SaveChanges(); + await context.SaveChangesAsync(); id = entity.Id; }, - context => + async context => { - var gumball = context.Set().Single(e => e.Id == id); + var gumball = await context.Set().SingleAsync(e => e.Id == id); Assert.Equal("Banana Joe", gumball.Identity); gumball.Identity = "Masami"; gumball.NotStoreGenerated = "Larry Needlemeye"; - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.Equal("Masami", gumball.Identity); }, - context => Assert.Equal("Masami", context.Set().Single(e => e.Id == id).Identity)); + async context => Assert.Equal("Masami", (await context.Set().SingleAsync(e => e.Id == id)).Identity)); } [ConditionalFact] - public virtual void Identity_property_on_Modified_entity_is_not_included_in_update_when_not_modified() + public virtual Task Identity_property_on_Modified_entity_is_not_included_in_update_when_not_modified() { var id = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var entity = context.Add(Gumball.Create(Fixture.IntSentinel, Fixture.StringSentinel)).Entity; - context.SaveChanges(); + await context.SaveChangesAsync(); id = entity.Id; }, - context => + async context => { - var gumball = context.Set().Single(e => e.Id == id); + var gumball = await context.Set().SingleAsync(e => e.Id == id); Assert.Equal("Banana Joe", gumball.Identity); @@ -892,56 +886,56 @@ public virtual void Identity_property_on_Modified_entity_is_not_included_in_upda context.Entry(gumball).Property(e => e.Identity).OriginalValue = "Masami"; context.Entry(gumball).Property(e => e.Identity).IsModified = false; - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.Equal("Masami", gumball.Identity); }, - context => Assert.Equal("Banana Joe", context.Set().Single(e => e.Id == id).Identity)); + async context => Assert.Equal("Banana Joe", (await context.Set().SingleAsync(e => e.Id == id)).Identity)); } [ConditionalFact] - public virtual void Always_identity_property_on_Added_entity_with_temporary_value_gets_value_from_store() + public virtual Task Always_identity_property_on_Added_entity_with_temporary_value_gets_value_from_store() { var id = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var gumball = Gumball.Create(Fixture.IntSentinel, Fixture.StringSentinel); gumball.AlwaysIdentity = "Masami"; var entry = context.Add(gumball); entry.Property(e => e.AlwaysIdentity).IsTemporary = true; - context.SaveChanges(); + await context.SaveChangesAsync(); id = entry.Entity.Id; Assert.Equal("Banana Joe", entry.Entity.AlwaysIdentity); }, - context => Assert.Equal("Banana Joe", context.Set().Single(e => e.Id == id).AlwaysIdentity)); + async context => Assert.Equal("Banana Joe", (await context.Set().SingleAsync(e => e.Id == id)).AlwaysIdentity)); } [ConditionalFact] - public virtual void Always_identity_property_on_Added_entity_with_default_value_gets_value_from_store() + public virtual Task Always_identity_property_on_Added_entity_with_default_value_gets_value_from_store() { var id = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var entity = context.Add(Gumball.Create(Fixture.IntSentinel, Fixture.StringSentinel)).Entity; - context.SaveChanges(); + await context.SaveChangesAsync(); id = entity.Id; Assert.Equal("Banana Joe", entity.AlwaysIdentity); }, - context => Assert.Equal("Banana Joe", context.Set().Single(e => e.Id == id).AlwaysIdentity)); + async context => Assert.Equal("Banana Joe", (await context.Set().SingleAsync(e => e.Id == id)).AlwaysIdentity)); } [ConditionalFact] - public virtual void Always_identity_property_on_Added_entity_with_read_only_before_save_throws_if_explicit_values_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Always_identity_property_on_Added_entity_with_read_only_before_save_throws_if_explicit_values_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var gumball = Gumball.Create(Fixture.IntSentinel, Fixture.StringSentinel); gumball.AlwaysIdentityReadOnlyBeforeSave = "Masami"; @@ -949,25 +943,25 @@ public virtual void Always_identity_property_on_Added_entity_with_read_only_befo Assert.Equal( CoreStrings.PropertyReadOnlyBeforeSave("AlwaysIdentityReadOnlyBeforeSave", "Gumball"), - Assert.Throws(() => context.SaveChanges()).Message); + (await Assert.ThrowsAsync(() => context.SaveChangesAsync())).Message); }); [ConditionalFact] - public virtual void Always_identity_property_on_Modified_entity_with_read_only_after_save_throws_if_value_is_in_modified_state() + public virtual Task Always_identity_property_on_Modified_entity_with_read_only_after_save_throws_if_value_is_in_modified_state() { var id = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var entity = context.Add(Gumball.Create(Fixture.IntSentinel, Fixture.StringSentinel)).Entity; - context.SaveChanges(); + await context.SaveChangesAsync(); id = entity.Id; }, - context => + async context => { - var gumball = context.Set().Single(e => e.Id == id); + var gumball = await context.Set().SingleAsync(e => e.Id == id); Assert.Equal("Anton", gumball.AlwaysIdentityReadOnlyAfterSave); @@ -976,26 +970,26 @@ public virtual void Always_identity_property_on_Modified_entity_with_read_only_a Assert.Equal( CoreStrings.PropertyReadOnlyAfterSave("AlwaysIdentityReadOnlyAfterSave", "Gumball"), - Assert.Throws(() => context.SaveChanges()).Message); + (await Assert.ThrowsAsync(() => context.SaveChangesAsync())).Message); }); } [ConditionalFact] - public virtual void Always_identity_property_on_Modified_entity_is_not_included_in_the_update_when_not_modified() + public virtual Task Always_identity_property_on_Modified_entity_is_not_included_in_the_update_when_not_modified() { var id = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var entity = context.Add(Gumball.Create(Fixture.IntSentinel, Fixture.StringSentinel)).Entity; - context.SaveChanges(); + await context.SaveChangesAsync(); id = entity.Id; }, - context => + async context => { - var gumball = context.Set().Single(e => e.Id == id); + var gumball = await context.Set().SingleAsync(e => e.Id == id); Assert.Equal("Banana Joe", gumball.AlwaysIdentity); @@ -1005,55 +999,55 @@ public virtual void Always_identity_property_on_Modified_entity_is_not_included_ context.Entry(gumball).Property(e => e.AlwaysIdentity).OriginalValue = "Masami"; context.Entry(gumball).Property(e => e.AlwaysIdentity).IsModified = false; - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.Equal("Masami", gumball.AlwaysIdentity); - }, context => Assert.Equal("Banana Joe", context.Set().Single(e => e.Id == id).AlwaysIdentity)); + }, async context => Assert.Equal("Banana Joe", (await context.Set().SingleAsync(e => e.Id == id)).AlwaysIdentity)); } [ConditionalFact] - public virtual void Computed_property_on_Added_entity_with_temporary_value_gets_value_from_store() + public virtual Task Computed_property_on_Added_entity_with_temporary_value_gets_value_from_store() { var id = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var gumball = Gumball.Create(Fixture.IntSentinel, Fixture.StringSentinel); gumball.Computed = "Masami"; var entry = context.Add(gumball); entry.Property(e => e.Computed).IsTemporary = true; - context.SaveChanges(); + await context.SaveChangesAsync(); id = entry.Entity.Id; Assert.Equal("Alan", entry.Entity.Computed); }, - context => Assert.Equal("Alan", context.Set().Single(e => e.Id == id).Computed)); + async context => Assert.Equal("Alan", (await context.Set().SingleAsync(e => e.Id == id)).Computed)); } [ConditionalFact] - public virtual void Computed_property_on_Added_entity_with_default_value_gets_value_from_store() + public virtual Task Computed_property_on_Added_entity_with_default_value_gets_value_from_store() { var id = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var entity = context.Add(Gumball.Create(Fixture.IntSentinel, Fixture.StringSentinel)).Entity; - context.SaveChanges(); + await context.SaveChangesAsync(); id = entity.Id; Assert.Equal("Alan", entity.Computed); }, - context => Assert.Equal("Alan", context.Set().Single(e => e.Id == id).Computed)); + async context => Assert.Equal("Alan", (await context.Set().SingleAsync(e => e.Id == id)).Computed)); } [ConditionalFact] - public virtual void Computed_property_on_Added_entity_with_read_only_before_save_throws_if_explicit_values_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Computed_property_on_Added_entity_with_read_only_before_save_throws_if_explicit_values_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var gumball = Gumball.Create(Fixture.IntSentinel, Fixture.StringSentinel); gumball.ComputedReadOnlyBeforeSave = "Masami"; @@ -1061,45 +1055,45 @@ public virtual void Computed_property_on_Added_entity_with_read_only_before_save Assert.Equal( CoreStrings.PropertyReadOnlyBeforeSave("ComputedReadOnlyBeforeSave", "Gumball"), - Assert.Throws(() => context.SaveChanges()).Message); + (await Assert.ThrowsAsync(() => context.SaveChangesAsync())).Message); }); [ConditionalFact] - public virtual void Computed_property_on_Added_entity_can_have_value_set_explicitly() + public virtual Task Computed_property_on_Added_entity_can_have_value_set_explicitly() { var id = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var gumball = Gumball.Create(Fixture.IntSentinel, Fixture.StringSentinel); gumball.Computed = "Masami"; var entity = context.Add(gumball).Entity; - context.SaveChanges(); + await context.SaveChangesAsync(); id = entity.Id; Assert.Equal("Masami", entity.Computed); }, - context => Assert.Equal("Masami", context.Set().Single(e => e.Id == id).Computed)); + async context => Assert.Equal("Masami", (await context.Set().SingleAsync(e => e.Id == id)).Computed)); } [ConditionalFact] - public virtual void Computed_property_on_Modified_entity_with_read_only_after_save_throws_if_value_is_in_modified_state() + public virtual Task Computed_property_on_Modified_entity_with_read_only_after_save_throws_if_value_is_in_modified_state() { var id = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var entity = context.Add(Gumball.Create(Fixture.IntSentinel, Fixture.StringSentinel)).Entity; - context.SaveChanges(); + await context.SaveChangesAsync(); id = entity.Id; }, - context => + async context => { - var gumball = context.Set().Single(e => e.Id == id); + var gumball = await context.Set().SingleAsync(e => e.Id == id); Assert.Equal("Tina Rex", gumball.ComputedReadOnlyAfterSave); @@ -1108,55 +1102,55 @@ public virtual void Computed_property_on_Modified_entity_with_read_only_after_sa Assert.Equal( CoreStrings.PropertyReadOnlyAfterSave("ComputedReadOnlyAfterSave", "Gumball"), - Assert.Throws(() => context.SaveChanges()).Message); + (await Assert.ThrowsAsync(() => context.SaveChangesAsync())).Message); }); } [ConditionalFact] - public virtual void Computed_property_on_Modified_entity_is_included_in_update_when_modified() + public virtual Task Computed_property_on_Modified_entity_is_included_in_update_when_modified() { var id = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var entity = context.Add(Gumball.Create(Fixture.IntSentinel, Fixture.StringSentinel)).Entity; - context.SaveChanges(); + await context.SaveChangesAsync(); id = entity.Id; }, - context => + async context => { - var gumball = context.Set().Single(e => e.Id == id); + var gumball = await context.Set().SingleAsync(e => e.Id == id); Assert.Equal("Alan", gumball.Computed); gumball.Computed = "Masami"; gumball.NotStoreGenerated = "Larry Needlemeye"; - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.Equal("Masami", gumball.Computed); }, - context => Assert.Equal("Masami", context.Set().Single(e => e.Id == id).Computed)); + async context => Assert.Equal("Masami", (await context.Set().SingleAsync(e => e.Id == id)).Computed)); } [ConditionalFact] - public virtual void Computed_property_on_Modified_entity_is_read_from_store_when_not_modified() + public virtual Task Computed_property_on_Modified_entity_is_read_from_store_when_not_modified() { var id = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var entity = context.Add(Gumball.Create(Fixture.IntSentinel, Fixture.StringSentinel)).Entity; - context.SaveChanges(); + await context.SaveChangesAsync(); id = entity.Id; }, - context => + async context => { - var gumball = context.Set().Single(e => e.Id == id); + var gumball = await context.Set().SingleAsync(e => e.Id == id); Assert.Equal("Alan", gumball.Computed); @@ -1166,56 +1160,56 @@ public virtual void Computed_property_on_Modified_entity_is_read_from_store_when context.Entry(gumball).Property(e => e.Computed).OriginalValue = "Masami"; context.Entry(gumball).Property(e => e.Computed).IsModified = false; - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.Equal("Alan", gumball.Computed); }, - context => Assert.Equal("Alan", context.Set().Single(e => e.Id == id).Computed)); + async context => Assert.Equal("Alan", (await context.Set().SingleAsync(e => e.Id == id)).Computed)); } [ConditionalFact] - public virtual void Always_computed_property_on_Added_entity_with_temporary_value_gets_value_from_store() + public virtual Task Always_computed_property_on_Added_entity_with_temporary_value_gets_value_from_store() { var id = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var gumball = Gumball.Create(Fixture.IntSentinel, Fixture.StringSentinel); gumball.AlwaysComputed = "Masami"; var entry = context.Add(gumball); entry.Property(e => e.AlwaysComputed).IsTemporary = true; - context.SaveChanges(); + await context.SaveChangesAsync(); id = entry.Entity.Id; Assert.Equal("Alan", entry.Entity.AlwaysComputed); }, - context => Assert.Equal("Alan", context.Set().Single(e => e.Id == id).AlwaysComputed)); + async context => Assert.Equal("Alan", (await context.Set().SingleAsync(e => e.Id == id)).AlwaysComputed)); } [ConditionalFact] - public virtual void Always_computed_property_on_Added_entity_with_default_value_gets_value_from_store() + public virtual Task Always_computed_property_on_Added_entity_with_default_value_gets_value_from_store() { var id = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var entity = context.Add(Gumball.Create(Fixture.IntSentinel, Fixture.StringSentinel)).Entity; - context.SaveChanges(); + await context.SaveChangesAsync(); id = entity.Id; Assert.Equal("Alan", entity.AlwaysComputed); }, - context => Assert.Equal("Alan", context.Set().Single(e => e.Id == id).AlwaysComputed)); + async context => Assert.Equal("Alan", (await context.Set().SingleAsync(e => e.Id == id)).AlwaysComputed)); } [ConditionalFact] - public virtual void Always_computed_property_on_Added_entity_with_read_only_before_save_throws_if_explicit_values_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Always_computed_property_on_Added_entity_with_read_only_before_save_throws_if_explicit_values_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var gumball = Gumball.Create(Fixture.IntSentinel, Fixture.StringSentinel); gumball.AlwaysComputedReadOnlyBeforeSave = "Masami"; @@ -1223,25 +1217,25 @@ public virtual void Always_computed_property_on_Added_entity_with_read_only_befo Assert.Equal( CoreStrings.PropertyReadOnlyBeforeSave("AlwaysComputedReadOnlyBeforeSave", "Gumball"), - Assert.Throws(() => context.SaveChanges()).Message); + (await Assert.ThrowsAsync(() => context.SaveChangesAsync())).Message); }); [ConditionalFact] - public virtual void Always_computed_property_on_Modified_entity_with_read_only_after_save_throws_if_value_is_in_modified_state() + public virtual Task Always_computed_property_on_Modified_entity_with_read_only_after_save_throws_if_value_is_in_modified_state() { var id = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var entity = context.Add(Gumball.Create(Fixture.IntSentinel, Fixture.StringSentinel)).Entity; - context.SaveChanges(); + await context.SaveChangesAsync(); id = entity.Id; }, - context => + async context => { - var gumball = context.Set().Single(e => e.Id == id); + var gumball = await context.Set().SingleAsync(e => e.Id == id); Assert.Equal("Tina Rex", gumball.AlwaysComputedReadOnlyAfterSave); @@ -1250,26 +1244,26 @@ public virtual void Always_computed_property_on_Modified_entity_with_read_only_a Assert.Equal( CoreStrings.PropertyReadOnlyAfterSave("AlwaysComputedReadOnlyAfterSave", "Gumball"), - Assert.Throws(() => context.SaveChanges()).Message); + (await Assert.ThrowsAsync(() => context.SaveChangesAsync())).Message); }); } [ConditionalFact] - public virtual void Always_computed_property_on_Modified_entity_is_read_from_store_when_not_modified() + public virtual Task Always_computed_property_on_Modified_entity_is_read_from_store_when_not_modified() { var id = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var entity = context.Add(Gumball.Create(Fixture.IntSentinel, Fixture.StringSentinel)).Entity; - context.SaveChanges(); + await context.SaveChangesAsync(); id = entity.Id; }, - context => + async context => { - var gumball = context.Set().Single(e => e.Id == id); + var gumball = await context.Set().SingleAsync(e => e.Id == id); Assert.Equal("Alan", gumball.AlwaysComputed); @@ -1279,42 +1273,42 @@ public virtual void Always_computed_property_on_Modified_entity_is_read_from_sto context.Entry(gumball).Property(e => e.AlwaysComputed).OriginalValue = "Masami"; context.Entry(gumball).Property(e => e.AlwaysComputed).IsModified = false; - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.Equal("Alan", gumball.AlwaysComputed); }, - context => Assert.Equal("Alan", context.Set().Single(e => e.Id == id).AlwaysComputed)); + async context => Assert.Equal("Alan", (await context.Set().SingleAsync(e => e.Id == id)).AlwaysComputed)); } [ConditionalFact] - public virtual void Fields_used_correctly_for_store_generated_values() + public virtual Task Fields_used_correctly_for_store_generated_values() { var id = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var entity = context.Add(WithBackingFields.Create(Fixture.IntSentinel, Fixture.NullableIntSentinel)).Entity; - context.SaveChanges(); + await context.SaveChangesAsync(); id = entity.Id; }, - context => + async context => { - var entity = context.Set().Single(e => e.Id.Equals(id)); + var entity = await context.Set().SingleAsync(e => e.Id.Equals(id)); Assert.Equal(1, entity.NullableAsNonNullable); Assert.Equal(1, entity.NonNullableAsNullable); }); } [ConditionalFact] - public virtual void Nullable_fields_get_defaults_when_not_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Nullable_fields_get_defaults_when_not_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var entity = context.Add(WithNullableBackingFields.Create(Fixture.NullableIntSentinel, Fixture.NullableBoolSentinel)) .Entity; - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.NotEqual(0, entity.Id); Assert.True(entity.NullableBackedBoolTrueDefault); @@ -1322,9 +1316,9 @@ public virtual void Nullable_fields_get_defaults_when_not_set() Assert.False(entity.NullableBackedBoolFalseDefault); Assert.Equal(0, entity.NullableBackedIntZeroDefault); }, - context => + async context => { - var entity = context.Set().Single(); + var entity = await context.Set().SingleAsync(); Assert.True(entity.NullableBackedBoolTrueDefault); Assert.Equal(-1, entity.NullableBackedIntNonZeroDefault); Assert.False(entity.NullableBackedBoolFalseDefault); @@ -1332,9 +1326,9 @@ public virtual void Nullable_fields_get_defaults_when_not_set() }); [ConditionalFact] - public virtual void Properties_get_database_defaults_when_set_to_sentinel_values() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Properties_get_database_defaults_when_set_to_sentinel_values() + => ExecuteWithStrategyInTransactionAsync( + async context => { var entity = new WithNoBackingFields { @@ -1347,7 +1341,7 @@ public virtual void Properties_get_database_defaults_when_set_to_sentinel_values context.Add(entity); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.NotEqual(0, entity.Id); Assert.True(entity.TrueDefault); @@ -1355,9 +1349,9 @@ public virtual void Properties_get_database_defaults_when_set_to_sentinel_values Assert.False(entity.FalseDefault); Assert.Equal(0, entity.ZeroDefault); }, - context => + async context => { - var entity = context.Set().Single(); + var entity = await context.Set().SingleAsync(); Assert.True(entity.TrueDefault); Assert.Equal(-1, entity.NonZeroDefault); Assert.False(entity.FalseDefault); @@ -1365,9 +1359,9 @@ public virtual void Properties_get_database_defaults_when_set_to_sentinel_values }); [ConditionalFact] - public virtual void Properties_get_set_values_when_not_set_to_sentinel_values() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Properties_get_set_values_when_not_set_to_sentinel_values() + => ExecuteWithStrategyInTransactionAsync( + async context => { var entity = new WithNoBackingFields { @@ -1380,7 +1374,7 @@ public virtual void Properties_get_set_values_when_not_set_to_sentinel_values() context.Add(entity); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.NotEqual(0, entity.Id); Assert.False(entity.TrueDefault); @@ -1388,9 +1382,9 @@ public virtual void Properties_get_set_values_when_not_set_to_sentinel_values() Assert.Equal(!Fixture.BoolSentinel, entity.FalseDefault); Assert.Equal(5, entity.ZeroDefault); }, - context => + async context => { - var entity = context.Set().Single(); + var entity = await context.Set().SingleAsync(); Assert.False(entity.TrueDefault); Assert.Equal(3, entity.NonZeroDefault); Assert.Equal(!Fixture.BoolSentinel, entity.FalseDefault); @@ -1398,9 +1392,9 @@ public virtual void Properties_get_set_values_when_not_set_to_sentinel_values() }); [ConditionalFact] - public virtual void Nullable_fields_store_non_defaults_when_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Nullable_fields_store_non_defaults_when_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var entity = WithNullableBackingFields.Create(Fixture.NullableIntSentinel, Fixture.NullableBoolSentinel); entity.NullableBackedBoolTrueDefault = Fixture.BoolSentinel; @@ -1410,7 +1404,7 @@ public virtual void Nullable_fields_store_non_defaults_when_set() context.Add(entity); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.NotEqual(0, entity.Id); Assert.Equal(Fixture.BoolSentinel, entity.NullableBackedBoolTrueDefault); @@ -1418,9 +1412,9 @@ public virtual void Nullable_fields_store_non_defaults_when_set() Assert.Equal(!Fixture.BoolSentinel, entity.NullableBackedBoolFalseDefault); Assert.Equal(Fixture.IntSentinel + 1, entity.NullableBackedIntZeroDefault); }, - context => + async context => { - var entity = context.Set().Single(); + var entity = await context.Set().SingleAsync(); Assert.Equal(Fixture.BoolSentinel, entity.NullableBackedBoolTrueDefault); Assert.Equal(Fixture.IntSentinel, entity.NullableBackedIntNonZeroDefault); Assert.Equal(!Fixture.BoolSentinel, entity.NullableBackedBoolFalseDefault); @@ -1428,9 +1422,9 @@ public virtual void Nullable_fields_store_non_defaults_when_set() }); [ConditionalFact] - public virtual void Nullable_fields_store_any_value_when_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Nullable_fields_store_any_value_when_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var entity = WithNullableBackingFields.Create(Fixture.NullableIntSentinel, Fixture.NullableBoolSentinel); entity.NullableBackedBoolTrueDefault = !Fixture.BoolSentinel; @@ -1440,7 +1434,7 @@ public virtual void Nullable_fields_store_any_value_when_set() context.Add(entity); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.NotEqual(0, entity.Id); Assert.Equal(!Fixture.BoolSentinel, entity.NullableBackedBoolTrueDefault); @@ -1448,9 +1442,9 @@ public virtual void Nullable_fields_store_any_value_when_set() Assert.Equal(!Fixture.BoolSentinel, entity.NullableBackedBoolFalseDefault); Assert.Equal(5, entity.NullableBackedIntZeroDefault); }, - context => + async context => { - var entity = context.Set().Single(); + var entity = await context.Set().SingleAsync(); Assert.Equal(!Fixture.BoolSentinel, entity.NullableBackedBoolTrueDefault); Assert.Equal(3, entity.NullableBackedIntNonZeroDefault); Assert.Equal(!Fixture.BoolSentinel, entity.NullableBackedBoolFalseDefault); @@ -1458,14 +1452,14 @@ public virtual void Nullable_fields_store_any_value_when_set() }); [ConditionalFact] - public virtual void Object_fields_get_defaults_when_not_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Object_fields_get_defaults_when_not_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var entity = WithObjectBackingFields.Create(Fixture.NullableIntSentinel, Fixture.NullableBoolSentinel); context.Add(entity); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.NotEqual(0, entity.Id); Assert.True(entity.NullableBackedBoolTrueDefault); @@ -1473,9 +1467,9 @@ public virtual void Object_fields_get_defaults_when_not_set() Assert.False(entity.NullableBackedBoolFalseDefault); Assert.Equal(0, entity.NullableBackedIntZeroDefault); }, - context => + async context => { - var entity = context.Set().Single(); + var entity = await context.Set().SingleAsync(); Assert.True(entity.NullableBackedBoolTrueDefault); Assert.Equal(-1, entity.NullableBackedIntNonZeroDefault); Assert.False(entity.NullableBackedBoolFalseDefault); @@ -1483,9 +1477,9 @@ public virtual void Object_fields_get_defaults_when_not_set() }); [ConditionalFact] - public virtual void Object_fields_store_non_defaults_when_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Object_fields_store_non_defaults_when_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var entity = WithObjectBackingFields.Create(Fixture.NullableIntSentinel, Fixture.NullableBoolSentinel); entity.NullableBackedBoolTrueDefault = Fixture.BoolSentinel; @@ -1495,7 +1489,7 @@ public virtual void Object_fields_store_non_defaults_when_set() context.Add(entity); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.NotEqual(0, entity.Id); Assert.Equal(Fixture.BoolSentinel, entity.NullableBackedBoolTrueDefault); @@ -1503,9 +1497,9 @@ public virtual void Object_fields_store_non_defaults_when_set() Assert.Equal(!Fixture.BoolSentinel, entity.NullableBackedBoolFalseDefault); Assert.Equal(Fixture.IntSentinel + 1, entity.NullableBackedIntZeroDefault); }, - context => + async context => { - var entity = context.Set().Single(); + var entity = await context.Set().SingleAsync(); Assert.Equal(Fixture.BoolSentinel, entity.NullableBackedBoolTrueDefault); Assert.Equal(Fixture.IntSentinel, entity.NullableBackedIntNonZeroDefault); Assert.Equal(!Fixture.BoolSentinel, entity.NullableBackedBoolFalseDefault); @@ -1513,9 +1507,9 @@ public virtual void Object_fields_store_non_defaults_when_set() }); [ConditionalFact] - public virtual void Object_fields_store_any_value_when_set() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Object_fields_store_any_value_when_set() + => ExecuteWithStrategyInTransactionAsync( + async context => { var entity = WithObjectBackingFields.Create(Fixture.NullableIntSentinel, Fixture.NullableBoolSentinel); entity.NullableBackedBoolTrueDefault = !Fixture.BoolSentinel; @@ -1525,7 +1519,7 @@ public virtual void Object_fields_store_any_value_when_set() context.Add(entity); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.NotEqual(0, entity.Id); Assert.Equal(!Fixture.BoolSentinel, entity.NullableBackedBoolTrueDefault); @@ -1533,9 +1527,9 @@ public virtual void Object_fields_store_any_value_when_set() Assert.Equal(!Fixture.BoolSentinel, entity.NullableBackedBoolFalseDefault); Assert.Equal(5, entity.NullableBackedIntZeroDefault); }, - context => + async context => { - var entity = context.Set().Single(); + var entity = await context.Set().SingleAsync(); Assert.Equal(!Fixture.BoolSentinel, entity.NullableBackedBoolTrueDefault); Assert.Equal(3, entity.NullableBackedIntNonZeroDefault); Assert.Equal(!Fixture.BoolSentinel, entity.NullableBackedBoolFalseDefault); @@ -2155,13 +2149,13 @@ protected class WrappedIntRecordDependentRequired } [ConditionalFact] - public virtual void Insert_update_and_delete_with_wrapped_int_key() + public virtual Task Insert_update_and_delete_with_wrapped_int_key() { var id1 = 0; var id2 = 0; var id3 = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var principal1 = context.Add( new WrappedIntClassPrincipal @@ -2193,7 +2187,7 @@ public virtual void Insert_update_and_delete_with_wrapped_int_key() RequiredDependents = { new WrappedIntRecordDependentRequired(), new WrappedIntRecordDependentRequired() } }).Entity; - context.SaveChanges(); + await context.SaveChangesAsync(); id1 = principal1.Id.Value; Assert.NotEqual(0, id1); @@ -2270,13 +2264,13 @@ public virtual void Insert_update_and_delete_with_wrapped_int_key() Assert.Equal(66, principal3.NonKey!.Value); }, - context => + async context => { - var principal1 = context.Set() + var principal1 = await context.Set() .Include(e => e.Dependents) .Include(e => e.OptionalDependents) .Include(e => e.RequiredDependents) - .Single(); + .SingleAsync(); Assert.Equal(principal1.Id.Value, id1); foreach (var dependent in principal1.Dependents) @@ -2297,11 +2291,11 @@ public virtual void Insert_update_and_delete_with_wrapped_int_key() Assert.Equal(id1, dependent.PrincipalId.Value); } - var principal2 = context.Set() + var principal2 = await context.Set() .Include(e => e.Dependents) .Include(e => e.OptionalDependents) .Include(e => e.RequiredDependents) - .Single(); + .SingleAsync(); Assert.Equal(principal2.Id.Value, id2); foreach (var dependent in principal2.Dependents) @@ -2322,11 +2316,11 @@ public virtual void Insert_update_and_delete_with_wrapped_int_key() Assert.Equal(id2, dependent.PrincipalId.Value); } - var principal3 = context.Set() + var principal3 = await context.Set() .Include(e => e.Dependents) .Include(e => e.OptionalDependents) .Include(e => e.RequiredDependents) - .Single(); + .SingleAsync(); Assert.Equal(principal3.Id.Value, id3); foreach (var dependent in principal3.Dependents) @@ -2359,47 +2353,47 @@ public virtual void Insert_update_and_delete_with_wrapped_int_key() principal2.RequiredDependents.Remove(principal2.RequiredDependents.First()); principal3.RequiredDependents.Remove(principal3.RequiredDependents.First()); - context.SaveChanges(); + await context.SaveChangesAsync(); }, - context => + async context => { - var dependents1 = context.Set().Include(e => e.Principal).ToList(); + var dependents1 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Equal(2, dependents1.Count); Assert.Null( context.Entry(dependents1.Single(e => e.Principal == null)) .Property("PrincipalId").CurrentValue); - var optionalDependents1 = context.Set().Include(e => e.Principal).ToList(); + var optionalDependents1 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Equal(2, optionalDependents1.Count); Assert.Null(optionalDependents1.Single(e => e.Principal == null).PrincipalId); - var requiredDependents1 = context.Set().Include(e => e.Principal).ToList(); + var requiredDependents1 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Single(requiredDependents1); - var dependents2 = context.Set().Include(e => e.Principal).ToList(); + var dependents2 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Equal(2, dependents2.Count); Assert.Null( context.Entry(dependents2.Single(e => e.Principal == null)) .Property("PrincipalId").CurrentValue); - var optionalDependents2 = context.Set().Include(e => e.Principal).ToList(); + var optionalDependents2 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Equal(2, optionalDependents2.Count); Assert.Null(optionalDependents2.Single(e => e.Principal == null).PrincipalId); - var requiredDependents2 = context.Set().Include(e => e.Principal).ToList(); + var requiredDependents2 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Single(requiredDependents2); - var dependents3 = context.Set().Include(e => e.Principal).ToList(); + var dependents3 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Equal(2, dependents3.Count); Assert.Null( context.Entry(dependents3.Single(e => e.Principal == null)) .Property("PrincipalId").CurrentValue); - var optionalDependents3 = context.Set().Include(e => e.Principal).ToList(); + var optionalDependents3 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Equal(2, optionalDependents3.Count); Assert.Null(optionalDependents3.Single(e => e.Principal == null).PrincipalId); - var requiredDependents3 = context.Set().Include(e => e.Principal).ToList(); + var requiredDependents3 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Single(requiredDependents3); context.Remove(dependents1.Single(e => e.Principal != null)); @@ -2417,21 +2411,21 @@ public virtual void Insert_update_and_delete_with_wrapped_int_key() context.Remove(requiredDependents3.Single()); context.Remove(requiredDependents3.Single().Principal); - context.SaveChanges(); + await context.SaveChangesAsync(); }, - context => + async context => { - Assert.Equal(1, context.Set().Count()); - Assert.Equal(1, context.Set().Count()); - Assert.Equal(1, context.Set().Count()); + Assert.Equal(1, await context.Set().CountAsync()); + Assert.Equal(1, await context.Set().CountAsync()); + Assert.Equal(1, await context.Set().CountAsync()); - Assert.Equal(1, context.Set().Count()); - Assert.Equal(1, context.Set().Count()); - Assert.Equal(1, context.Set().Count()); + Assert.Equal(1, await context.Set().CountAsync()); + Assert.Equal(1, await context.Set().CountAsync()); + Assert.Equal(1, await context.Set().CountAsync()); - Assert.Equal(0, context.Set().Count()); - Assert.Equal(0, context.Set().Count()); - Assert.Equal(0, context.Set().Count()); + Assert.Equal(0, await context.Set().CountAsync()); + Assert.Equal(0, await context.Set().CountAsync()); + Assert.Equal(0, await context.Set().CountAsync()); }); } @@ -2472,11 +2466,11 @@ protected class LongToIntDependentOptional } [ConditionalFact] - public virtual void Insert_update_and_delete_with_long_to_int_conversion() + public virtual Task Insert_update_and_delete_with_long_to_int_conversion() { var id1 = 0L; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var principal1 = context.Add( new LongToIntPrincipal @@ -2487,7 +2481,7 @@ public virtual void Insert_update_and_delete_with_long_to_int_conversion() RequiredDependents = { new LongToIntDependentRequired(), new LongToIntDependentRequired() } }).Entity; - context.SaveChanges(); + await context.SaveChangesAsync(); id1 = principal1.Id; Assert.NotEqual(0L, id1); @@ -2512,13 +2506,13 @@ public virtual void Insert_update_and_delete_with_long_to_int_conversion() Assert.Equal(id1, dependent.PrincipalId); } }, - context => + async context => { - var principal1 = context.Set() + var principal1 = await context.Set() .Include(e => e.Dependents) .Include(e => e.OptionalDependents) .Include(e => e.RequiredDependents) - .Single(); + .SingleAsync(); Assert.Equal(principal1.Id, id1); foreach (var dependent in principal1.Dependents) @@ -2543,21 +2537,21 @@ public virtual void Insert_update_and_delete_with_long_to_int_conversion() principal1.OptionalDependents.Remove(principal1.OptionalDependents.First()); principal1.RequiredDependents.Remove(principal1.RequiredDependents.First()); - context.SaveChanges(); + await context.SaveChangesAsync(); }, - context => + async context => { - var dependents1 = context.Set().Include(e => e.Principal).ToList(); + var dependents1 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Equal(2, dependents1.Count); Assert.Null( context.Entry(dependents1.Single(e => e.Principal == null)) .Property("PrincipalId").CurrentValue); - var optionalDependents1 = context.Set().Include(e => e.Principal).ToList(); + var optionalDependents1 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Equal(2, optionalDependents1.Count); Assert.Null(optionalDependents1.Single(e => e.Principal == null).PrincipalId); - var requiredDependents1 = context.Set().Include(e => e.Principal).ToList(); + var requiredDependents1 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Single(requiredDependents1); context.Remove(dependents1.Single(e => e.Principal != null)); @@ -2565,13 +2559,13 @@ public virtual void Insert_update_and_delete_with_long_to_int_conversion() context.Remove(requiredDependents1.Single()); context.Remove(requiredDependents1.Single().Principal); - context.SaveChanges(); + await context.SaveChangesAsync(); }, - context => + async context => { - Assert.Equal(1, context.Set().Count()); - Assert.Equal(1, context.Set().Count()); - Assert.Equal(0, context.Set().Count()); + Assert.Equal(1, await context.Set().CountAsync()); + Assert.Equal(1, await context.Set().CountAsync()); + Assert.Equal(0, await context.Set().CountAsync()); }); } @@ -2850,13 +2844,13 @@ protected class WrappedStringRecordDependentRequired } [ConditionalFact] - public virtual void Insert_update_and_delete_with_wrapped_string_key() + public virtual Task Insert_update_and_delete_with_wrapped_string_key() { string? id1 = null; string? id2 = null; string? id3 = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var principal1 = context.Add( new WrappedStringClassPrincipal @@ -2888,7 +2882,7 @@ public virtual void Insert_update_and_delete_with_wrapped_string_key() RequiredDependents = { new WrappedStringRecordDependentRequired(), new WrappedStringRecordDependentRequired() } }).Entity; - context.SaveChanges(); + await context.SaveChangesAsync(); id1 = principal1.Id.Value; Assert.NotNull(id1); @@ -2965,13 +2959,13 @@ public virtual void Insert_update_and_delete_with_wrapped_string_key() Assert.Equal("66", principal3.NonKey!.Value); }, - context => + async context => { - var principal1 = context.Set() + var principal1 = await context.Set() .Include(e => e.Dependents) .Include(e => e.OptionalDependents) .Include(e => e.RequiredDependents) - .Single(); + .SingleAsync(); Assert.Equal(principal1.Id.Value, id1); foreach (var dependent in principal1.Dependents) @@ -2992,11 +2986,11 @@ public virtual void Insert_update_and_delete_with_wrapped_string_key() Assert.Equal(id1, dependent.PrincipalId.Value); } - var principal2 = context.Set() + var principal2 = await context.Set() .Include(e => e.Dependents) .Include(e => e.OptionalDependents) .Include(e => e.RequiredDependents) - .Single(); + .SingleAsync(); Assert.Equal(principal2.Id.Value, id2); foreach (var dependent in principal2.Dependents) @@ -3017,11 +3011,11 @@ public virtual void Insert_update_and_delete_with_wrapped_string_key() Assert.Equal(id2, dependent.PrincipalId.Value); } - var principal3 = context.Set() + var principal3 = await context.Set() .Include(e => e.Dependents) .Include(e => e.OptionalDependents) .Include(e => e.RequiredDependents) - .Single(); + .SingleAsync(); Assert.Equal(principal3.Id.Value, id3); foreach (var dependent in principal3.Dependents) @@ -3054,47 +3048,47 @@ public virtual void Insert_update_and_delete_with_wrapped_string_key() principal2.RequiredDependents.Remove(principal2.RequiredDependents.First()); principal3.RequiredDependents.Remove(principal3.RequiredDependents.First()); - context.SaveChanges(); + await context.SaveChangesAsync(); }, - context => + async context => { - var dependents1 = context.Set().Include(e => e.Principal).ToList(); + var dependents1 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Equal(2, dependents1.Count); Assert.Null( context.Entry(dependents1.Single(e => e.Principal == null)) .Property("PrincipalId").CurrentValue); - var optionalDependents1 = context.Set().Include(e => e.Principal).ToList(); + var optionalDependents1 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Equal(2, optionalDependents1.Count); Assert.Null(optionalDependents1.Single(e => e.Principal == null).PrincipalId); - var requiredDependents1 = context.Set().Include(e => e.Principal).ToList(); + var requiredDependents1 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Single(requiredDependents1); - var dependents2 = context.Set().Include(e => e.Principal).ToList(); + var dependents2 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Equal(2, dependents2.Count); Assert.Null( context.Entry(dependents2.Single(e => e.Principal == null)) .Property("PrincipalId").CurrentValue); - var optionalDependents2 = context.Set().Include(e => e.Principal).ToList(); + var optionalDependents2 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Equal(2, optionalDependents2.Count); Assert.Null(optionalDependents2.Single(e => e.Principal == null).PrincipalId); - var requiredDependents2 = context.Set().Include(e => e.Principal).ToList(); + var requiredDependents2 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Single(requiredDependents2); - var dependents3 = context.Set().Include(e => e.Principal).ToList(); + var dependents3 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Equal(2, dependents3.Count); Assert.Null( context.Entry(dependents3.Single(e => e.Principal == null)) .Property("PrincipalId").CurrentValue); - var optionalDependents3 = context.Set().Include(e => e.Principal).ToList(); + var optionalDependents3 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Equal(2, optionalDependents3.Count); Assert.Null(optionalDependents3.Single(e => e.Principal == null).PrincipalId); - var requiredDependents3 = context.Set().Include(e => e.Principal).ToList(); + var requiredDependents3 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Single(requiredDependents3); context.Remove(dependents1.Single(e => e.Principal != null)); @@ -3112,21 +3106,21 @@ public virtual void Insert_update_and_delete_with_wrapped_string_key() context.Remove(requiredDependents3.Single()); context.Remove(requiredDependents3.Single().Principal); - context.SaveChanges(); + await context.SaveChangesAsync(); }, - context => + async context => { - Assert.Equal(1, context.Set().Count()); - Assert.Equal(1, context.Set().Count()); - Assert.Equal(1, context.Set().Count()); + Assert.Equal(1, await context.Set().CountAsync()); + Assert.Equal(1, await context.Set().CountAsync()); + Assert.Equal(1, await context.Set().CountAsync()); - Assert.Equal(1, context.Set().Count()); - Assert.Equal(1, context.Set().Count()); - Assert.Equal(1, context.Set().Count()); + Assert.Equal(1, await context.Set().CountAsync()); + Assert.Equal(1, await context.Set().CountAsync()); + Assert.Equal(1, await context.Set().CountAsync()); - Assert.Equal(0, context.Set().Count()); - Assert.Equal(0, context.Set().Count()); - Assert.Equal(0, context.Set().Count()); + Assert.Equal(0, await context.Set().CountAsync()); + Assert.Equal(0, await context.Set().CountAsync()); + Assert.Equal(0, await context.Set().CountAsync()); }); } @@ -3396,13 +3390,13 @@ protected class WrappedGuidRecordDependentRequired } [ConditionalFact] - public virtual void Insert_update_and_delete_with_wrapped_Guid_key() + public virtual Task Insert_update_and_delete_with_wrapped_Guid_key() { var id1 = Guid.Empty; var id2 = Guid.Empty; var id3 = Guid.Empty; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var principal1 = context.Add( new WrappedGuidClassPrincipal @@ -3434,7 +3428,7 @@ public virtual void Insert_update_and_delete_with_wrapped_Guid_key() RequiredDependents = { new WrappedGuidRecordDependentRequired(), new WrappedGuidRecordDependentRequired() } }).Entity; - context.SaveChanges(); + await context.SaveChangesAsync(); id1 = principal1.Id.Value; Assert.NotEqual(Guid.Empty, id1); @@ -3511,13 +3505,13 @@ public virtual void Insert_update_and_delete_with_wrapped_Guid_key() Assert.Equal(KnownGuid, principal3.NonKey!.Value); }, - context => + async context => { - var principal1 = context.Set() + var principal1 = await context.Set() .Include(e => e.Dependents) .Include(e => e.OptionalDependents) .Include(e => e.RequiredDependents) - .Single(); + .SingleAsync(); Assert.Equal(principal1.Id.Value, id1); foreach (var dependent in principal1.Dependents) @@ -3538,11 +3532,11 @@ public virtual void Insert_update_and_delete_with_wrapped_Guid_key() Assert.Equal(id1, dependent.PrincipalId.Value); } - var principal2 = context.Set() + var principal2 = await context.Set() .Include(e => e.Dependents) .Include(e => e.OptionalDependents) .Include(e => e.RequiredDependents) - .Single(); + .SingleAsync(); Assert.Equal(principal2.Id.Value, id2); foreach (var dependent in principal2.Dependents) @@ -3563,11 +3557,11 @@ public virtual void Insert_update_and_delete_with_wrapped_Guid_key() Assert.Equal(id2, dependent.PrincipalId.Value); } - var principal3 = context.Set() + var principal3 = await context.Set() .Include(e => e.Dependents) .Include(e => e.OptionalDependents) .Include(e => e.RequiredDependents) - .Single(); + .SingleAsync(); Assert.Equal(principal3.Id.Value, id3); foreach (var dependent in principal3.Dependents) @@ -3600,47 +3594,47 @@ public virtual void Insert_update_and_delete_with_wrapped_Guid_key() principal2.RequiredDependents.Remove(principal2.RequiredDependents.First()); principal3.RequiredDependents.Remove(principal3.RequiredDependents.First()); - context.SaveChanges(); + await context.SaveChangesAsync(); }, - context => + async context => { - var dependents1 = context.Set().Include(e => e.Principal).ToList(); + var dependents1 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Equal(2, dependents1.Count); Assert.Null( context.Entry(dependents1.Single(e => e.Principal == null)) .Property("PrincipalId").CurrentValue); - var optionalDependents1 = context.Set().Include(e => e.Principal).ToList(); + var optionalDependents1 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Equal(2, optionalDependents1.Count); Assert.Null(optionalDependents1.Single(e => e.Principal == null).PrincipalId); - var requiredDependents1 = context.Set().Include(e => e.Principal).ToList(); + var requiredDependents1 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Single(requiredDependents1); - var dependents2 = context.Set().Include(e => e.Principal).ToList(); + var dependents2 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Equal(2, dependents2.Count); Assert.Null( context.Entry(dependents2.Single(e => e.Principal == null)) .Property("PrincipalId").CurrentValue); - var optionalDependents2 = context.Set().Include(e => e.Principal).ToList(); + var optionalDependents2 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Equal(2, optionalDependents2.Count); Assert.Null(optionalDependents2.Single(e => e.Principal == null).PrincipalId); - var requiredDependents2 = context.Set().Include(e => e.Principal).ToList(); + var requiredDependents2 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Single(requiredDependents2); - var dependents3 = context.Set().Include(e => e.Principal).ToList(); + var dependents3 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Equal(2, dependents3.Count); Assert.Null( context.Entry(dependents3.Single(e => e.Principal == null)) .Property("PrincipalId").CurrentValue); - var optionalDependents3 = context.Set().Include(e => e.Principal).ToList(); + var optionalDependents3 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Equal(2, optionalDependents3.Count); Assert.Null(optionalDependents3.Single(e => e.Principal == null).PrincipalId); - var requiredDependents3 = context.Set().Include(e => e.Principal).ToList(); + var requiredDependents3 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Single(requiredDependents3); context.Remove(dependents1.Single(e => e.Principal != null)); @@ -3658,21 +3652,21 @@ public virtual void Insert_update_and_delete_with_wrapped_Guid_key() context.Remove(requiredDependents3.Single()); context.Remove(requiredDependents3.Single().Principal); - context.SaveChanges(); + await context.SaveChangesAsync(); }, - context => + async context => { - Assert.Equal(1, context.Set().Count()); - Assert.Equal(1, context.Set().Count()); - Assert.Equal(1, context.Set().Count()); + Assert.Equal(1, await context.Set().CountAsync()); + Assert.Equal(1, await context.Set().CountAsync()); + Assert.Equal(1, await context.Set().CountAsync()); - Assert.Equal(1, context.Set().Count()); - Assert.Equal(1, context.Set().Count()); - Assert.Equal(1, context.Set().Count()); + Assert.Equal(1, await context.Set().CountAsync()); + Assert.Equal(1, await context.Set().CountAsync()); + Assert.Equal(1, await context.Set().CountAsync()); - Assert.Equal(0, context.Set().Count()); - Assert.Equal(0, context.Set().Count()); - Assert.Equal(0, context.Set().Count()); + Assert.Equal(0, await context.Set().CountAsync()); + Assert.Equal(0, await context.Set().CountAsync()); + Assert.Equal(0, await context.Set().CountAsync()); }); } @@ -3942,13 +3936,13 @@ protected class WrappedUriRecordDependentRequired } [ConditionalFact] - public virtual void Insert_update_and_delete_with_wrapped_Uri_key() + public virtual Task Insert_update_and_delete_with_wrapped_Uri_key() { Uri? id1 = null; Uri? id2 = null; Uri? id3 = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var principal1 = context.Add( new WrappedUriClassPrincipal @@ -3980,7 +3974,7 @@ public virtual void Insert_update_and_delete_with_wrapped_Uri_key() RequiredDependents = { new WrappedUriRecordDependentRequired(), new WrappedUriRecordDependentRequired() } }).Entity; - context.SaveChanges(); + await context.SaveChangesAsync(); id1 = principal1.Id.Value; Assert.NotNull(id1); @@ -4057,13 +4051,13 @@ public virtual void Insert_update_and_delete_with_wrapped_Uri_key() Assert.Equal(new Uri("https://www.example.com"), principal3.NonKey!.Value); }, - context => + async context => { - var principal1 = context.Set() + var principal1 = await context.Set() .Include(e => e.Dependents) .Include(e => e.OptionalDependents) .Include(e => e.RequiredDependents) - .Single(); + .SingleAsync(); Assert.Equal(principal1.Id.Value, id1); foreach (var dependent in principal1.Dependents) @@ -4084,11 +4078,11 @@ public virtual void Insert_update_and_delete_with_wrapped_Uri_key() Assert.Equal(id1, dependent.PrincipalId.Value); } - var principal2 = context.Set() + var principal2 = await context.Set() .Include(e => e.Dependents) .Include(e => e.OptionalDependents) .Include(e => e.RequiredDependents) - .Single(); + .SingleAsync(); Assert.Equal(principal2.Id.Value, id2); foreach (var dependent in principal2.Dependents) @@ -4109,11 +4103,11 @@ public virtual void Insert_update_and_delete_with_wrapped_Uri_key() Assert.Equal(id2, dependent.PrincipalId.Value); } - var principal3 = context.Set() + var principal3 = await context.Set() .Include(e => e.Dependents) .Include(e => e.OptionalDependents) .Include(e => e.RequiredDependents) - .Single(); + .SingleAsync(); Assert.Equal(principal3.Id.Value, id3); foreach (var dependent in principal3.Dependents) @@ -4146,47 +4140,47 @@ public virtual void Insert_update_and_delete_with_wrapped_Uri_key() principal2.RequiredDependents.Remove(principal2.RequiredDependents.First()); principal3.RequiredDependents.Remove(principal3.RequiredDependents.First()); - context.SaveChanges(); + await context.SaveChangesAsync(); }, - context => + async context => { - var dependents1 = context.Set().Include(e => e.Principal).ToList(); + var dependents1 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Equal(2, dependents1.Count); Assert.Null( context.Entry(dependents1.Single(e => e.Principal == null)) .Property("PrincipalId").CurrentValue); - var optionalDependents1 = context.Set().Include(e => e.Principal).ToList(); + var optionalDependents1 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Equal(2, optionalDependents1.Count); Assert.Null(optionalDependents1.Single(e => e.Principal == null).PrincipalId); - var requiredDependents1 = context.Set().Include(e => e.Principal).ToList(); + var requiredDependents1 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Single(requiredDependents1); - var dependents2 = context.Set().Include(e => e.Principal).ToList(); + var dependents2 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Equal(2, dependents2.Count); Assert.Null( context.Entry(dependents2.Single(e => e.Principal == null)) .Property("PrincipalId").CurrentValue); - var optionalDependents2 = context.Set().Include(e => e.Principal).ToList(); + var optionalDependents2 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Equal(2, optionalDependents2.Count); Assert.Null(optionalDependents2.Single(e => e.Principal == null).PrincipalId); - var requiredDependents2 = context.Set().Include(e => e.Principal).ToList(); + var requiredDependents2 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Single(requiredDependents2); - var dependents3 = context.Set().Include(e => e.Principal).ToList(); + var dependents3 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Equal(2, dependents3.Count); Assert.Null( context.Entry(dependents3.Single(e => e.Principal == null)) .Property("PrincipalId").CurrentValue); - var optionalDependents3 = context.Set().Include(e => e.Principal).ToList(); + var optionalDependents3 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Equal(2, optionalDependents3.Count); Assert.Null(optionalDependents3.Single(e => e.Principal == null).PrincipalId); - var requiredDependents3 = context.Set().Include(e => e.Principal).ToList(); + var requiredDependents3 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Single(requiredDependents3); context.Remove(dependents1.Single(e => e.Principal != null)); @@ -4204,21 +4198,21 @@ public virtual void Insert_update_and_delete_with_wrapped_Uri_key() context.Remove(requiredDependents3.Single()); context.Remove(requiredDependents3.Single().Principal); - context.SaveChanges(); + await context.SaveChangesAsync(); }, - context => + async context => { - Assert.Equal(1, context.Set().Count()); - Assert.Equal(1, context.Set().Count()); - Assert.Equal(1, context.Set().Count()); + Assert.Equal(1, await context.Set().CountAsync()); + Assert.Equal(1, await context.Set().CountAsync()); + Assert.Equal(1, await context.Set().CountAsync()); - Assert.Equal(1, context.Set().Count()); - Assert.Equal(1, context.Set().Count()); - Assert.Equal(1, context.Set().Count()); + Assert.Equal(1, await context.Set().CountAsync()); + Assert.Equal(1, await context.Set().CountAsync()); + Assert.Equal(1, await context.Set().CountAsync()); - Assert.Equal(0, context.Set().Count()); - Assert.Equal(0, context.Set().Count()); - Assert.Equal(0, context.Set().Count()); + Assert.Equal(0, await context.Set().CountAsync()); + Assert.Equal(0, await context.Set().CountAsync()); + Assert.Equal(0, await context.Set().CountAsync()); }); } @@ -4259,11 +4253,11 @@ protected class UriDependentOptional } [ConditionalFact] - public virtual void Insert_update_and_delete_with_Uri_key() + public virtual Task Insert_update_and_delete_with_Uri_key() { Uri? id1 = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var principal1 = context.Add( new UriPrincipal @@ -4274,7 +4268,7 @@ public virtual void Insert_update_and_delete_with_Uri_key() RequiredDependents = { new UriDependentRequired(), new UriDependentRequired() } }).Entity; - context.SaveChanges(); + await context.SaveChangesAsync(); id1 = principal1.Id; Assert.NotNull(id1); @@ -4285,13 +4279,13 @@ public virtual void Insert_update_and_delete_with_Uri_key() Assert.Equal(id1, context.Entry(dependent).Property("PrincipalId").CurrentValue); } }, - context => + async context => { - var principal1 = context.Set() + var principal1 = await context.Set() .Include(e => e.Dependents) .Include(e => e.OptionalDependents) .Include(e => e.RequiredDependents) - .Single(); + .SingleAsync(); Assert.Equal(principal1.Id, id1); foreach (var dependent in principal1.Dependents) @@ -4303,19 +4297,19 @@ public virtual void Insert_update_and_delete_with_Uri_key() principal1.Dependents.Remove(principal1.Dependents.First()); principal1.OptionalDependents.Remove(principal1.OptionalDependents.First()); principal1.RequiredDependents.Remove(principal1.RequiredDependents.First()); - context.SaveChanges(); + await context.SaveChangesAsync(); }, - context => + async context => { - var dependents1 = context.Set().Include(e => e.Principal).ToList(); + var dependents1 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Equal(2, dependents1.Count); Assert.Null(context.Entry(dependents1.Single(e => e.Principal == null)).Property("PrincipalId").CurrentValue); - var optionalDependents1 = context.Set().Include(e => e.Principal).ToList(); + var optionalDependents1 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Equal(2, optionalDependents1.Count); Assert.Null(optionalDependents1.Single(e => e.Principal == null).PrincipalId); - var requiredDependents1 = context.Set().Include(e => e.Principal).ToList(); + var requiredDependents1 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Single(requiredDependents1); context.Remove(dependents1.Single(e => e.Principal != null)); @@ -4323,13 +4317,13 @@ public virtual void Insert_update_and_delete_with_Uri_key() context.Remove(requiredDependents1.Single()); context.Remove(requiredDependents1.Single().Principal); - context.SaveChanges(); + await context.SaveChangesAsync(); }, - context => + async context => { - Assert.Equal(1, context.Set().Count()); - Assert.Equal(1, context.Set().Count()); - Assert.Equal(0, context.Set().Count()); + Assert.Equal(1, await context.Set().CountAsync()); + Assert.Equal(1, await context.Set().CountAsync()); + Assert.Equal(0, await context.Set().CountAsync()); }); } @@ -4379,11 +4373,11 @@ protected class EnumDependentOptional } [ConditionalFact] - public virtual void Insert_update_and_delete_with_enum_key() + public virtual Task Insert_update_and_delete_with_enum_key() { KeyEnum? id1 = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var principal1 = context.Add( new EnumPrincipal @@ -4394,7 +4388,7 @@ public virtual void Insert_update_and_delete_with_enum_key() RequiredDependents = { new EnumDependentRequired(), new EnumDependentRequired() } }).Entity; - context.SaveChanges(); + await context.SaveChangesAsync(); id1 = principal1.Id; Assert.NotNull(id1); @@ -4404,13 +4398,13 @@ public virtual void Insert_update_and_delete_with_enum_key() Assert.Equal(id1, context.Entry(dependent).Property("PrincipalId").CurrentValue); } }, - context => + async context => { - var principal1 = context.Set() + var principal1 = await context.Set() .Include(e => e.Dependents) .Include(e => e.OptionalDependents) .Include(e => e.RequiredDependents) - .Single(); + .SingleAsync(); Assert.Equal(principal1.Id, id1); foreach (var dependent in principal1.Dependents) @@ -4422,19 +4416,19 @@ public virtual void Insert_update_and_delete_with_enum_key() principal1.Dependents.Remove(principal1.Dependents.First()); principal1.OptionalDependents.Remove(principal1.OptionalDependents.First()); principal1.RequiredDependents.Remove(principal1.RequiredDependents.First()); - context.SaveChanges(); + await context.SaveChangesAsync(); }, - context => + async context => { - var dependents1 = context.Set().Include(e => e.Principal).ToList(); + var dependents1 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Equal(2, dependents1.Count); Assert.Null(context.Entry(dependents1.Single(e => e.Principal == null)).Property("PrincipalId").CurrentValue); - var optionalDependents1 = context.Set().Include(e => e.Principal).ToList(); + var optionalDependents1 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Equal(2, optionalDependents1.Count); Assert.Null(optionalDependents1.Single(e => e.Principal == null).PrincipalId); - var requiredDependents1 = context.Set().Include(e => e.Principal).ToList(); + var requiredDependents1 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Single(requiredDependents1); context.Remove(dependents1.Single(e => e.Principal != null)); @@ -4442,13 +4436,13 @@ public virtual void Insert_update_and_delete_with_enum_key() context.Remove(requiredDependents1.Single()); context.Remove(requiredDependents1.Single().Principal); - context.SaveChanges(); + await context.SaveChangesAsync(); }, - context => + async context => { - Assert.Equal(1, context.Set().Count()); - Assert.Equal(1, context.Set().Count()); - Assert.Equal(0, context.Set().Count()); + Assert.Equal(1, await context.Set().CountAsync()); + Assert.Equal(1, await context.Set().CountAsync()); + Assert.Equal(0, await context.Set().CountAsync()); }); } @@ -4489,11 +4483,11 @@ protected class GuidAsStringDependentOptional } [ConditionalFact] - public virtual void Insert_update_and_delete_with_GuidAsString_key() + public virtual Task Insert_update_and_delete_with_GuidAsString_key() { Guid? id1 = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var principal1 = context.Add( new GuidAsStringPrincipal @@ -4504,7 +4498,7 @@ public virtual void Insert_update_and_delete_with_GuidAsString_key() RequiredDependents = { new GuidAsStringDependentRequired(), new GuidAsStringDependentRequired() } }).Entity; - context.SaveChanges(); + await context.SaveChangesAsync(); id1 = principal1.Id; Assert.NotNull(id1); @@ -4514,13 +4508,13 @@ public virtual void Insert_update_and_delete_with_GuidAsString_key() Assert.Equal(id1, context.Entry(dependent).Property("PrincipalId").CurrentValue); } }, - context => + async context => { - var principal1 = context.Set() + var principal1 = await context.Set() .Include(e => e.Dependents) .Include(e => e.OptionalDependents) .Include(e => e.RequiredDependents) - .Single(); + .SingleAsync(); Assert.Equal(principal1.Id, id1); foreach (var dependent in principal1.Dependents) @@ -4532,19 +4526,19 @@ public virtual void Insert_update_and_delete_with_GuidAsString_key() principal1.Dependents.Remove(principal1.Dependents.First()); principal1.OptionalDependents.Remove(principal1.OptionalDependents.First()); principal1.RequiredDependents.Remove(principal1.RequiredDependents.First()); - context.SaveChanges(); + await context.SaveChangesAsync(); }, - context => + async context => { - var dependents1 = context.Set().Include(e => e.Principal).ToList(); + var dependents1 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Equal(2, dependents1.Count); Assert.Null(context.Entry(dependents1.Single(e => e.Principal == null)).Property("PrincipalId").CurrentValue); - var optionalDependents1 = context.Set().Include(e => e.Principal).ToList(); + var optionalDependents1 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Equal(2, optionalDependents1.Count); Assert.Null(optionalDependents1.Single(e => e.Principal == null).PrincipalId); - var requiredDependents1 = context.Set().Include(e => e.Principal).ToList(); + var requiredDependents1 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Single(requiredDependents1); context.Remove(dependents1.Single(e => e.Principal != null)); @@ -4552,13 +4546,13 @@ public virtual void Insert_update_and_delete_with_GuidAsString_key() context.Remove(requiredDependents1.Single()); context.Remove(requiredDependents1.Single().Principal); - context.SaveChanges(); + await context.SaveChangesAsync(); }, - context => + async context => { - Assert.Equal(1, context.Set().Count()); - Assert.Equal(1, context.Set().Count()); - Assert.Equal(0, context.Set().Count()); + Assert.Equal(1, await context.Set().CountAsync()); + Assert.Equal(1, await context.Set().CountAsync()); + Assert.Equal(0, await context.Set().CountAsync()); }); } @@ -4599,11 +4593,11 @@ protected class StringAsGuidDependentOptional } [ConditionalFact] - public virtual void Insert_update_and_delete_with_StringAsGuid_key() + public virtual Task Insert_update_and_delete_with_StringAsGuid_key() { string? id1 = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var principal1 = context.Add( new StringAsGuidPrincipal @@ -4614,7 +4608,7 @@ public virtual void Insert_update_and_delete_with_StringAsGuid_key() RequiredDependents = { new StringAsGuidDependentRequired(), new StringAsGuidDependentRequired() } }).Entity; - context.SaveChanges(); + await context.SaveChangesAsync(); id1 = principal1.Id; Assert.NotNull(id1); @@ -4625,13 +4619,13 @@ public virtual void Insert_update_and_delete_with_StringAsGuid_key() Assert.Equal(id1, context.Entry(dependent).Property("PrincipalId").CurrentValue); } }, - context => + async context => { - var principal1 = context.Set() + var principal1 = await context.Set() .Include(e => e.Dependents) .Include(e => e.OptionalDependents) .Include(e => e.RequiredDependents) - .Single(); + .SingleAsync(); Assert.Equal(principal1.Id, id1); foreach (var dependent in principal1.Dependents) @@ -4643,19 +4637,19 @@ public virtual void Insert_update_and_delete_with_StringAsGuid_key() principal1.Dependents.Remove(principal1.Dependents.First()); principal1.OptionalDependents.Remove(principal1.OptionalDependents.First()); principal1.RequiredDependents.Remove(principal1.RequiredDependents.First()); - context.SaveChanges(); + await context.SaveChangesAsync(); }, - context => + async context => { - var dependents1 = context.Set().Include(e => e.Principal).ToList(); + var dependents1 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Equal(2, dependents1.Count); Assert.Null(context.Entry(dependents1.Single(e => e.Principal == null)).Property("PrincipalId").CurrentValue); - var optionalDependents1 = context.Set().Include(e => e.Principal).ToList(); + var optionalDependents1 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Equal(2, optionalDependents1.Count); Assert.Null(optionalDependents1.Single(e => e.Principal == null).PrincipalId); - var requiredDependents1 = context.Set().Include(e => e.Principal).ToList(); + var requiredDependents1 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Single(requiredDependents1); context.Remove(dependents1.Single(e => e.Principal != null)); @@ -4663,22 +4657,22 @@ public virtual void Insert_update_and_delete_with_StringAsGuid_key() context.Remove(requiredDependents1.Single()); context.Remove(requiredDependents1.Single().Principal); - context.SaveChanges(); + await context.SaveChangesAsync(); }, - context => + async context => { - Assert.Equal(1, context.Set().Count()); - Assert.Equal(1, context.Set().Count()); - Assert.Equal(0, context.Set().Count()); + Assert.Equal(1, await context.Set().CountAsync()); + Assert.Equal(1, await context.Set().CountAsync()); + Assert.Equal(0, await context.Set().CountAsync()); }); } - protected virtual void ExecuteWithStrategyInTransaction( - Action testOperation, - Action? nestedTestOperation1 = null, - Action? nestedTestOperation2 = null, - Action? nestedTestOperation3 = null) - => TestHelpers.ExecuteWithStrategyInTransaction( + protected virtual Task ExecuteWithStrategyInTransactionAsync( + Func testOperation, + Func? nestedTestOperation1 = null, + Func? nestedTestOperation2 = null, + Func? nestedTestOperation3 = null) + => TestHelpers.ExecuteWithStrategyInTransactionAsync( CreateContext, UseTransaction, testOperation, nestedTestOperation1, nestedTestOperation2, nestedTestOperation3); diff --git a/test/EFCore.Specification.Tests/TestModels/ComplexNavigationsModel/ComplexNavigationsData.cs b/test/EFCore.Specification.Tests/TestModels/ComplexNavigationsModel/ComplexNavigationsData.cs index eb27bc2e503..0329e3b8eb9 100644 --- a/test/EFCore.Specification.Tests/TestModels/ComplexNavigationsModel/ComplexNavigationsData.cs +++ b/test/EFCore.Specification.Tests/TestModels/ComplexNavigationsModel/ComplexNavigationsData.cs @@ -1118,7 +1118,7 @@ private static void WireUpInversePart2( l4s[8].OneToMany_Optional_Self_Inverse4 = l4s[9]; } - public static void Seed(ComplexNavigationsContext context, bool tableSplitting = false) + public static async Task SeedAsync(ComplexNavigationsContext context, bool tableSplitting = false) { var l1s = CreateLevelOnes(tableSplitting); var l2s = CreateLevelTwos(tableSplitting); @@ -1129,7 +1129,7 @@ public static void Seed(ComplexNavigationsContext context, bool tableSplitting = WireUpPart1(l1s, l2s, l3s, l4s, tableSplitting); - context.SaveChanges(); + await context.SaveChangesAsync(); WireUpPart2(l1s, l2s, l3s, l4s, tableSplitting); @@ -1155,10 +1155,10 @@ public static void Seed(ComplexNavigationsContext context, bool tableSplitting = context.InheritanceLeafTwo.AddRange(il2s); WireUpInheritancePart1(ib1s, ib2s, il1s, il2s); - context.SaveChanges(); + await context.SaveChangesAsync(); WireUpInheritancePart2(ib2s, il2s); - context.SaveChanges(); + await context.SaveChangesAsync(); var mls1 = new ComplexNavigationString { DefaultText = "MLS1", Globalizations = globalizations.Take(3).ToList() }; var mls2 = new ComplexNavigationString { DefaultText = "MLS2", Globalizations = globalizations.Skip(3).Take(3).ToList() }; @@ -1181,6 +1181,6 @@ public static void Seed(ComplexNavigationsContext context, bool tableSplitting = }; context.Fields.AddRange(field1, field2); - context.SaveChanges(); + await context.SaveChangesAsync(); } } diff --git a/test/EFCore.Specification.Tests/TestModels/ComplexTypeModel/ComplexTypeData.cs b/test/EFCore.Specification.Tests/TestModels/ComplexTypeModel/ComplexTypeData.cs index 036f1abfd3e..e1b1fc01304 100644 --- a/test/EFCore.Specification.Tests/TestModels/ComplexTypeModel/ComplexTypeData.cs +++ b/test/EFCore.Specification.Tests/TestModels/ComplexTypeModel/ComplexTypeData.cs @@ -78,7 +78,12 @@ private static IReadOnlyList CreateCustomers() AddressLine1 = "79 Main St.", ZipCode = 29293, Country = new Country { FullName = "Germany", Code = "DE" }, - Tags = new List { "a1", "a2", "a3" } + Tags = new List + { + "a1", + "a2", + "a3" + } } }; @@ -226,7 +231,7 @@ private static IReadOnlyList CreateValuedCustomerGroups(IRe }; } - public static void Seed(PoolableDbContext context) + public static Task SeedAsync(PoolableDbContext context) { var customers = CreateCustomers(); var customerGroups = CreateCustomerGroups(customers); @@ -238,6 +243,6 @@ public static void Seed(PoolableDbContext context) context.AddRange(valuedCustomers); context.AddRange(valuedCustomerGroups); - context.SaveChanges(); + return context.SaveChangesAsync(); } } diff --git a/test/EFCore.Specification.Tests/TestModels/CompositeKeysModel/CompositeKeysData.cs b/test/EFCore.Specification.Tests/TestModels/CompositeKeysModel/CompositeKeysData.cs index 486b9e8edd7..02315046974 100644 --- a/test/EFCore.Specification.Tests/TestModels/CompositeKeysModel/CompositeKeysData.cs +++ b/test/EFCore.Specification.Tests/TestModels/CompositeKeysModel/CompositeKeysData.cs @@ -1009,7 +1009,7 @@ private static void WireUpInversePart2( l4s[8].OneToMany_Optional_Self_Inverse4 = l4s[9]; } - public static void Seed(CompositeKeysContext context) + public static async Task SeedAsync(CompositeKeysContext context) { var l1s = CreateCompositeOnes(); var l2s = CreateCompositeTwos(); @@ -1020,10 +1020,10 @@ public static void Seed(CompositeKeysContext context) WireUpPart1(l1s, l2s, l3s, l4s); - context.SaveChanges(); + await context.SaveChangesAsync(); WireUpPart2(l1s, l2s, l3s, l4s); - context.SaveChanges(); + await context.SaveChangesAsync(); } } diff --git a/test/EFCore.Specification.Tests/TestModels/ConcurrencyModel/F1Context.cs b/test/EFCore.Specification.Tests/TestModels/ConcurrencyModel/F1Context.cs index 28f29c0310f..c962b5998c0 100644 --- a/test/EFCore.Specification.Tests/TestModels/ConcurrencyModel/F1Context.cs +++ b/test/EFCore.Specification.Tests/TestModels/ConcurrencyModel/F1Context.cs @@ -18,11 +18,11 @@ public class F1Context(DbContextOptions options) : PoolableDbContext(options) public DbSet Circuits { get; set; } - public static void Seed(F1Context context) + public static Task SeedAsync(F1Context context) { AddEntities(context); - context.SaveChanges(); + return context.SaveChangesAsync(); } private static void AddEntities(F1Context context) diff --git a/test/EFCore.Specification.Tests/TestModels/FunkyDataModel/FunkyDataContext.cs b/test/EFCore.Specification.Tests/TestModels/FunkyDataModel/FunkyDataContext.cs index 37e69665386..8b3cbb40f90 100644 --- a/test/EFCore.Specification.Tests/TestModels/FunkyDataModel/FunkyDataContext.cs +++ b/test/EFCore.Specification.Tests/TestModels/FunkyDataModel/FunkyDataContext.cs @@ -12,9 +12,9 @@ public class FunkyDataContext(DbContextOptions options) : PoolableDbContext(opti protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity().Property(e => e.Id).ValueGeneratedNever(); - public static void Seed(FunkyDataContext context) + public static Task SeedAsync(FunkyDataContext context) { context.FunkyCustomers.AddRange(FunkyDataData.CreateFunkyCustomers()); - context.SaveChanges(); + return context.SaveChangesAsync(); } } diff --git a/test/EFCore.Specification.Tests/TestModels/GearsOfWarModel/GearsOfWarContext.cs b/test/EFCore.Specification.Tests/TestModels/GearsOfWarModel/GearsOfWarContext.cs index 1a55d63417b..db3dc58b9ea 100644 --- a/test/EFCore.Specification.Tests/TestModels/GearsOfWarModel/GearsOfWarContext.cs +++ b/test/EFCore.Specification.Tests/TestModels/GearsOfWarModel/GearsOfWarContext.cs @@ -19,7 +19,7 @@ public class GearsOfWarContext(DbContextOptions options) : PoolableDbContext(opt public DbSet LocustLeaders { get; set; } public DbSet LocustHighCommands { get; set; } - public static void Seed(GearsOfWarContext context) + public static async Task SeedAsync(GearsOfWarContext context) { var squads = GearsOfWarData.CreateSquads(); var missions = GearsOfWarData.CreateMissions(); @@ -45,10 +45,10 @@ public static void Seed(GearsOfWarContext context) context.LocustLeaders.AddRange(locustLeaders); context.Factions.AddRange(factions); context.LocustHighCommands.AddRange(locustHighCommands); - context.SaveChanges(); + await context.SaveChangesAsync(); GearsOfWarData.WireUp2(locustLeaders, factions); - context.SaveChanges(); + await context.SaveChangesAsync(); } } diff --git a/test/EFCore.Specification.Tests/TestModels/InheritanceModel/InheritanceContext.cs b/test/EFCore.Specification.Tests/TestModels/InheritanceModel/InheritanceContext.cs index 91ad7968559..7741d56e87c 100644 --- a/test/EFCore.Specification.Tests/TestModels/InheritanceModel/InheritanceContext.cs +++ b/test/EFCore.Specification.Tests/TestModels/InheritanceModel/InheritanceContext.cs @@ -16,7 +16,7 @@ public class InheritanceContext(DbContextOptions options) : PoolableDbContext(op public DbSet Tea { get; set; } public DbSet Plants { get; set; } - public static void Seed(InheritanceContext context, bool useGeneratedKeys) + public static Task SeedAsync(InheritanceContext context, bool useGeneratedKeys) { var animals = InheritanceData.CreateAnimals(useGeneratedKeys); var countries = InheritanceData.CreateCountries(); @@ -30,6 +30,6 @@ public static void Seed(InheritanceContext context, bool useGeneratedKeys) context.Drinks.AddRange(drinks); context.Plants.AddRange(plants); - context.SaveChanges(); + return context.SaveChangesAsync(); } } diff --git a/test/EFCore.Specification.Tests/TestModels/InheritanceRelationshipsModel/InheritanceRelationshipsContext.cs b/test/EFCore.Specification.Tests/TestModels/InheritanceRelationshipsModel/InheritanceRelationshipsContext.cs index 6dff39b6952..0918cd40664 100644 --- a/test/EFCore.Specification.Tests/TestModels/InheritanceRelationshipsModel/InheritanceRelationshipsContext.cs +++ b/test/EFCore.Specification.Tests/TestModels/InheritanceRelationshipsModel/InheritanceRelationshipsContext.cs @@ -23,7 +23,7 @@ public class InheritanceRelationshipsContext(DbContextOptions options) : Poolabl public DbSet ReferencesOnBase { get; set; } public DbSet ReferencesOnDerived { get; set; } - public static void Seed(InheritanceRelationshipsContext context) + public static Task SeedAsync(InheritanceRelationshipsContext context) { var baseCollectionsOnBase = InheritanceRelationshipsData.CreateBaseCollectionsOnBase(); var baseCollectionsOnDerived = InheritanceRelationshipsData.CreateBaseCollectionsOnDerived(); @@ -66,6 +66,6 @@ public static void Seed(InheritanceRelationshipsContext context) context.ReferencesOnBase.AddRange(referencesOnBase); context.ReferencesOnDerived.AddRange(referencesOnDerived); - context.SaveChanges(); + return context.SaveChangesAsync(); } } diff --git a/test/EFCore.Specification.Tests/TestModels/MonsterContext.cs b/test/EFCore.Specification.Tests/TestModels/MonsterContext.cs index b208f4f3bc1..e189dd97eca 100644 --- a/test/EFCore.Specification.Tests/TestModels/MonsterContext.cs +++ b/test/EFCore.Specification.Tests/TestModels/MonsterContext.cs @@ -42,7 +42,7 @@ protected MonsterContext(DbContextOptions options) public abstract IQueryable Drivers { get; } public abstract IQueryable Licenses { get; } - public abstract void SeedUsingFKs(); - public abstract void SeedUsingNavigations(bool dependentNavs, bool principalNavs); - public abstract void SeedUsingNavigationsWithDeferredAdd(); + public abstract Task SeedUsingFKs(); + public abstract Task SeedUsingNavigations(bool dependentNavs, bool principalNavs); + public abstract Task SeedUsingNavigationsWithDeferredAdd(); } diff --git a/test/EFCore.Specification.Tests/TestModels/MonsterContext`.cs b/test/EFCore.Specification.Tests/TestModels/MonsterContext`.cs index 402ddb07be8..de7eab59d7f 100644 --- a/test/EFCore.Specification.Tests/TestModels/MonsterContext`.cs +++ b/test/EFCore.Specification.Tests/TestModels/MonsterContext`.cs @@ -388,7 +388,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .HasForeignKey(e => e.ProductId)); } - public override void SeedUsingFKs() + public override Task SeedUsingFKs() { var customer0 = Add( new TCustomer { Name = "Eeky Bear" }).Entity; @@ -884,10 +884,10 @@ public override void SeedUsingFKs() ExpirationDate = new DateTime(2018, 9, 19) }).Entity; - SaveChanges(); + return SaveChangesAsync(); } - public override void SeedUsingNavigations(bool dependentNavs, bool principalNavs) + public override Task SeedUsingNavigations(bool dependentNavs, bool principalNavs) { var customer0 = Add( new TCustomer { Name = "Eeky Bear" }).Entity; @@ -1517,10 +1517,10 @@ public override void SeedUsingNavigations(bool dependentNavs, bool principalNavs driver2.License = license2; } - SaveChanges(); + return SaveChangesAsync(); } - public override void SeedUsingNavigationsWithDeferredAdd() + public override Task SeedUsingNavigationsWithDeferredAdd() { var toAdd = new List[4]; @@ -1984,7 +1984,7 @@ public override void SeedUsingNavigationsWithDeferredAdd() Add(entity); } - SaveChanges(); + return SaveChangesAsync(); } } diff --git a/test/EFCore.Specification.Tests/TestModels/Northwind/NorthwindData.cs b/test/EFCore.Specification.Tests/TestModels/Northwind/NorthwindData.cs index ceb7ea8b530..f47989b2141 100644 --- a/test/EFCore.Specification.Tests/TestModels/Northwind/NorthwindData.cs +++ b/test/EFCore.Specification.Tests/TestModels/Northwind/NorthwindData.cs @@ -213,13 +213,6 @@ public IQueryable Set() throw new InvalidOperationException("Invalid entity type: " + typeof(TEntity)); } - public static void Seed(NorthwindContext context) - { - AddEntities(context); - - context.SaveChanges(); - } - public static Task SeedAsync(NorthwindContext context) { AddEntities(context); diff --git a/test/EFCore.Specification.Tests/TestModels/NullSemanticsModel/NullSemanticsContext.cs b/test/EFCore.Specification.Tests/TestModels/NullSemanticsModel/NullSemanticsContext.cs index 76c11b3e26e..7c01fc47f84 100644 --- a/test/EFCore.Specification.Tests/TestModels/NullSemanticsModel/NullSemanticsContext.cs +++ b/test/EFCore.Specification.Tests/TestModels/NullSemanticsModel/NullSemanticsContext.cs @@ -10,13 +10,13 @@ public class NullSemanticsContext(DbContextOptions options) : PoolableDbContext( public DbSet Entities1 { get; set; } public DbSet Entities2 { get; set; } - public static void Seed(NullSemanticsContext context) + public static Task SeedAsync(NullSemanticsContext context) { var entities1 = NullSemanticsData.CreateEntities1(); var entities2 = NullSemanticsData.CreateEntities2(); context.Entities1.AddRange(entities1); context.Entities2.AddRange(entities2); - context.SaveChanges(); + return context.SaveChangesAsync(); } } diff --git a/test/EFCore.Specification.Tests/TestModels/QueryFilterFuncletizationContext.cs b/test/EFCore.Specification.Tests/TestModels/QueryFilterFuncletizationContext.cs index eac950c1ee3..fc6fbba05b4 100644 --- a/test/EFCore.Specification.Tests/TestModels/QueryFilterFuncletizationContext.cs +++ b/test/EFCore.Specification.Tests/TestModels/QueryFilterFuncletizationContext.cs @@ -101,7 +101,8 @@ public void Configure(EntityTypeBuilder buil => builder.HasQueryFilter(e => e.IsEnabled == Context.Field); } - public class PropertyConfiguration(QueryFilterFuncletizationContext context) : IEntityTypeConfiguration + public class PropertyConfiguration(QueryFilterFuncletizationContext context) + : IEntityTypeConfiguration { private readonly QueryFilterFuncletizationContext _context = context; @@ -127,7 +128,7 @@ public void Configure(EntityTypeBuilder ProductTableView { get; set; } = null!; public DbSet Trotters { get; set; } = null!; - public static void Seed(UpdatesContext context) + public static Task SeedAsync(UpdatesContext context) { var productId1 = new Guid("984ade3c-2f7b-4651-a351-642e92ab7146"); var productId2 = new Guid("0edc9136-7eed-463b-9b97-bdb9648ab877"); @@ -40,6 +40,6 @@ public static void Seed(UpdatesContext context) DependentId = 778 }); - context.SaveChanges(); + return context.SaveChangesAsync(); } } diff --git a/test/EFCore.Specification.Tests/TestUtilities/TestHelpers.cs b/test/EFCore.Specification.Tests/TestUtilities/TestHelpers.cs index 41204be831b..132ed15072e 100644 --- a/test/EFCore.Specification.Tests/TestUtilities/TestHelpers.cs +++ b/test/EFCore.Specification.Tests/TestUtilities/TestHelpers.cs @@ -248,7 +248,8 @@ public InternalEntityEntry CreateInternalEntry( return entry; } - public virtual ModelAsserter ModelAsserter => ModelAsserter.Instance; + public virtual ModelAsserter ModelAsserter + => ModelAsserter.Instance; private static int AssertResults(IList expected, IList actual) { @@ -349,59 +350,6 @@ public static void AssertAllMethodsOverridden(Type testClass) "\r\n-- Missing test overrides --\r\n\r\n" + methodCalls); } - public static void ExecuteWithStrategyInTransaction( - Func createContext, - Action useTransaction, - Action testOperation, - Action? nestedTestOperation1 = null, - Action? nestedTestOperation2 = null, - Action? nestedTestOperation3 = null) - where TContext : DbContext - { - using var c = createContext(); - c.Database.CreateExecutionStrategy().Execute( - c, context => - { - using var transaction = context.Database.BeginTransaction(); - using (var innerContext = createContext()) - { - useTransaction(innerContext.Database, transaction); - testOperation(innerContext); - } - - if (nestedTestOperation1 == null) - { - return; - } - - using (var innerContext1 = createContext()) - { - useTransaction(innerContext1.Database, transaction); - nestedTestOperation1(innerContext1); - } - - if (nestedTestOperation2 == null) - { - return; - } - - using (var innerContext2 = createContext()) - { - useTransaction(innerContext2.Database, transaction); - nestedTestOperation2(innerContext2); - } - - if (nestedTestOperation3 == null) - { - return; - } - - using var innerContext3 = createContext(); - useTransaction(innerContext3.Database, transaction); - nestedTestOperation3(innerContext3); - }); - } - public static async Task ExecuteWithStrategyInTransactionAsync( Func createContext, Action useTransaction, @@ -460,7 +408,8 @@ public class TestModelBuilder( ModelDependencies modelDependencies, ModelConfiguration? modelConfiguration, IModelRuntimeInitializer modelRuntimeInitializer, - IDiagnosticsLogger validationLogger) : ModelBuilder(conventions, modelDependencies, modelConfiguration) + IDiagnosticsLogger validationLogger) + : ModelBuilder(conventions, modelDependencies, modelConfiguration) { private readonly IModelRuntimeInitializer _modelRuntimeInitializer = modelRuntimeInitializer; private readonly IDiagnosticsLogger _validationLogger = validationLogger; @@ -472,7 +421,8 @@ public IModel FinalizeModel(bool designTime = false, bool skipValidation = false => _modelRuntimeInitializer.Initialize((IModel)Model, designTime, skipValidation ? null : _validationLogger); } - public class TestModelConfigurationBuilder(ConventionSet conventionSet, IServiceProvider serviceProvider) : ModelConfigurationBuilder(conventionSet, serviceProvider) + public class TestModelConfigurationBuilder(ConventionSet conventionSet, IServiceProvider serviceProvider) + : ModelConfigurationBuilder(conventionSet, serviceProvider) { public ConventionSet ConventionSet { get; } = conventionSet; diff --git a/test/EFCore.Specification.Tests/TestUtilities/TestStore.cs b/test/EFCore.Specification.Tests/TestUtilities/TestStore.cs index 2c76bc9ff67..c8888f2fa65 100644 --- a/test/EFCore.Specification.Tests/TestUtilities/TestStore.cs +++ b/test/EFCore.Specification.Tests/TestUtilities/TestStore.cs @@ -13,11 +13,11 @@ public abstract class TestStore(string name, bool shared) : IDisposable public string Name { get; protected set; } = name; public bool Shared { get; } = shared; - public virtual TestStore Initialize( + public virtual async Task InitializeAsync( IServiceProvider? serviceProvider, Func? createContext, - Action? seed = null, - Action? clean = null) + Func? seed = null, + Func? clean = null) { ServiceProvider = serviceProvider; if (createContext == null) @@ -27,54 +27,58 @@ public virtual TestStore Initialize( if (Shared) { - GetTestStoreIndex(serviceProvider).CreateShared(GetType().Name + Name, () => Initialize(createContext, seed, clean)); + await GetTestStoreIndex(serviceProvider).CreateSharedAsync( + GetType().Name + Name, async () => await InitializeAsync(createContext, seed, clean)); } else { - GetTestStoreIndex(serviceProvider).CreateNonShared(GetType().Name + Name, () => Initialize(createContext, seed, clean)); + await GetTestStoreIndex(serviceProvider).CreateNonSharedAsync( + GetType().Name + Name, async () => await InitializeAsync(createContext, seed, clean)); } return this; } - public virtual TestStore Initialize( + public virtual Task InitializeAsync( IServiceProvider serviceProvider, Func createContext, - Action? seed = null, - Action? clean = null) - => Initialize(serviceProvider, () => createContext(this), seed, clean); + Func? seed = null, + Func? clean = null) + => InitializeAsync(serviceProvider, () => createContext(this), seed, clean); - public virtual TestStore Initialize( + public virtual Task InitializeAsync( IServiceProvider serviceProvider, Func createContext, - Action? seed = null, - Action? clean = null) + Func? seed = null, + Func? clean = null) where TContext : DbContext - => Initialize( + => InitializeAsync( serviceProvider, - createContext, + () => createContext(this), // ReSharper disable twice RedundantCast - seed == null ? (Action?)null : c => seed((TContext)c), - clean == null ? (Action?)null : c => clean((TContext)c)); + seed == null ? (Func?)null : c => seed((TContext)c), + clean == null ? (Func?)null : c => clean((TContext)c)); - protected virtual void Initialize(Func createContext, Action? seed, Action? clean) + protected virtual async Task InitializeAsync(Func createContext, Func? seed, Func? clean) { using var context = createContext(); - clean?.Invoke(context); + if (clean != null) + { + await clean(context); + } - Clean(context); + await CleanAsync(context); - seed?.Invoke(context); + if (seed != null) + { + await seed(context); + } } public abstract DbContextOptionsBuilder AddProviderOptions(DbContextOptionsBuilder builder); - public abstract void Clean(DbContext context); public virtual Task CleanAsync(DbContext context) - { - Clean(context); - return Task.CompletedTask; - } + => Task.CompletedTask; protected virtual DbContext CreateDefaultContext() => new(AddProviderOptions(new DbContextOptionsBuilder().EnableServiceProviderCaching(false)).Options); diff --git a/test/EFCore.Specification.Tests/TestUtilities/TestStoreIndex.cs b/test/EFCore.Specification.Tests/TestUtilities/TestStoreIndex.cs index e4319711b54..0ab66693ca9 100644 --- a/test/EFCore.Specification.Tests/TestUtilities/TestStoreIndex.cs +++ b/test/EFCore.Specification.Tests/TestUtilities/TestStoreIndex.cs @@ -8,61 +8,43 @@ namespace Microsoft.EntityFrameworkCore.TestUtilities; public class TestStoreIndex { private readonly HashSet _createdDatabases = []; - private readonly ConcurrentDictionary _creationLocks = new(); + private readonly ConcurrentDictionary _creationLocks = new(); private readonly object _hashSetLock = new(); - public virtual void CreateShared(string name, Action initializeDatabase) + public virtual async Task CreateSharedAsync(string name, Func initializeDatabase) { // ReSharper disable once InconsistentlySynchronizedField if (!_createdDatabases.Contains(name)) { - var creationLock = _creationLocks.GetOrAdd(name, new object()); - - lock (creationLock) + var creationLock = _creationLocks.GetOrAdd(name, new SemaphoreSlim(1, 1)); + await creationLock.WaitAsync(); + try { if (!_createdDatabases.Contains(name)) { - initializeDatabase?.Invoke(); + await initializeDatabase(); lock (_hashSetLock) { _createdDatabases.Add(name); } - - _creationLocks.TryRemove(name, out _); } } + finally + { + creationLock.Release(); + } } } public virtual void RemoveShared(string name) - => _createdDatabases.Remove(name); - - public virtual void CreateNonShared(string name, Action initializeDatabase) { - var creationLock = _creationLocks.GetOrAdd(name, new object()); - - if (Monitor.TryEnter(creationLock)) + lock (_hashSetLock) { - try - { - initializeDatabase?.Invoke(); - } - finally - { - Monitor.Exit(creationLock); - if (!_creationLocks.TryRemove(name, out _)) - { - throw new InvalidOperationException( - $"An attempt was made to initialize a non-shared store {name} from two different threads."); - } - } - } - else - { - _creationLocks.TryRemove(name, out _); - throw new InvalidOperationException( - $"An attempt was made to initialize a non-shared store {name} from two different threads."); + _createdDatabases.Remove(name); } } + + public virtual Task CreateNonSharedAsync(string name, Func initializeDatabase) + => initializeDatabase(); } diff --git a/test/EFCore.Specification.Tests/UnidirectionalManyToManyTrackingTestBase.cs b/test/EFCore.Specification.Tests/UnidirectionalManyToManyTrackingTestBase.cs index 963a543fe89..808b986088d 100644 --- a/test/EFCore.Specification.Tests/UnidirectionalManyToManyTrackingTestBase.cs +++ b/test/EFCore.Specification.Tests/UnidirectionalManyToManyTrackingTestBase.cs @@ -80,7 +80,7 @@ await ExecuteWithStrategyInTransactionAsync( } else { - context.SaveChanges(); + await context.SaveChangesAsync(); } ValidateFixup(context, leftEntities, rightEntities); @@ -138,14 +138,14 @@ void ValidateFixup( } [ConditionalFact] - public virtual void Can_update_many_to_many_composite_with_navs_unidirectional() + public virtual Task Can_update_many_to_many_composite_with_navs_unidirectional() { - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var leftEntities = context.Set().ToList(); - var rightEntities = context.Set().Include(e => e.CompositeKeySkipFull).OrderBy(e => e.Name) - .ToList(); + var leftEntities = await context.Set().ToListAsync(); + var rightEntities = await context.Set().Include(e => e.CompositeKeySkipFull).OrderBy(e => e.Name) + .ToListAsync(); rightEntities[0].CompositeKeySkipFull.Add( context.UnidirectionalEntityCompositeKeys.CreateInstance( @@ -195,15 +195,15 @@ public virtual void Can_update_many_to_many_composite_with_navs_unidirectional() ValidateFixup(context, leftEntities, rightEntities, 24, 4, 35); - context.SaveChanges(); + await context.SaveChangesAsync(); ValidateFixup(context, leftEntities, rightEntities, 24, 4, 35 - 2); }, - context => + async context => { - var leftEntities = context.Set().ToList(); - var rightEntities = context.Set().Include(e => e.CompositeKeySkipFull).OrderBy(e => e.Name) - .ToList(); + var leftEntities = await context.Set().ToListAsync(); + var rightEntities = await context.Set().Include(e => e.CompositeKeySkipFull).OrderBy(e => e.Name) + .ToListAsync(); ValidateFixup(context, leftEntities, rightEntities, 24, 4, 35 - 2); }); @@ -270,18 +270,20 @@ void ValidateFixup( } [ConditionalFact] - public virtual void Can_delete_with_many_to_many_composite_with_navs_unidirectional() + public virtual Task Can_delete_with_many_to_many_composite_with_navs_unidirectional() { var key1 = 0; var key2 = ""; var key3 = default(DateTime); var id = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var ones = context.Set().Include(e => e.RootSkipShared).OrderBy(e => e.Key2).ToList(); - var threes = context.Set().Include(e => e.CompositeKeySkipFull).OrderBy(e => e.Name).ToList(); + var ones = await context.Set().Include(e => e.RootSkipShared).OrderBy(e => e.Key2) + .ToListAsync(); + var threes = await context.Set().Include(e => e.CompositeKeySkipFull).OrderBy(e => e.Name) + .ToListAsync(); // Make sure other related entities are loaded for delete fixup context.Set().Load(); @@ -334,7 +336,7 @@ public virtual void Can_delete_with_many_to_many_composite_with_navs_unidirectio ? EntityState.Deleted : EntityState.Unchanged, e.State)); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.Equal(0, threes.SelectMany(e => e.CompositeKeySkipFull).Count(e => e == toRemoveOne)); Assert.Equal(0, ones.SelectMany(e => e.RootSkipShared).Count(e => e == toRemoveThree)); @@ -354,10 +356,12 @@ public virtual void Can_delete_with_many_to_many_composite_with_navs_unidirectio && e.Entity.CompositeId3 == key3) || e.Entity.LeafId == id); }, - context => + async context => { - var ones = context.Set().Include(e => e.RootSkipShared).OrderBy(e => e.Key2).ToList(); - var threes = context.Set().Include(e => e.CompositeKeySkipFull).OrderBy(e => e.Name).ToList(); + var ones = await context.Set().Include(e => e.RootSkipShared).OrderBy(e => e.Key2) + .ToListAsync(); + var threes = await context.Set().Include(e => e.CompositeKeySkipFull).OrderBy(e => e.Name) + .ToListAsync(); ValidateNavigations(ones, threes); @@ -514,7 +518,7 @@ await ExecuteWithStrategyInTransactionAsync( } else { - context.SaveChanges(); + await context.SaveChangesAsync(); } ValidateFixup(context, leftEntities, rightEntities, postSave: true); @@ -582,17 +586,17 @@ void ValidateFixup( } [ConditionalFact] - public virtual void Can_update_many_to_many_composite_additional_pk_with_navs_unidirectional() + public virtual Task Can_update_many_to_many_composite_additional_pk_with_navs_unidirectional() { List threeIds = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var leftEntities = context.Set().Include(e => e.ThreeSkipFull).OrderBy(e => e.Key2) - .ToList(); - var rightEntities = context.Set().Include("UnidirectionalEntityCompositeKey") - .OrderBy(e => e.Name).ToList(); + var leftEntities = await context.Set().Include(e => e.ThreeSkipFull).OrderBy(e => e.Key2) + .ToListAsync(); + var rightEntities = await context.Set().Include("UnidirectionalEntityCompositeKey") + .OrderBy(e => e.Name).ToListAsync(); var threes = new[] { @@ -686,19 +690,19 @@ public virtual void Can_update_many_to_many_composite_additional_pk_with_navs_un ValidateFixup(context, leftEntities, rightEntities, 24, 24, 53); - context.SaveChanges(); + await context.SaveChangesAsync(); threeIds = threes.Select(e => e.Id).ToList(); ValidateFixup(context, leftEntities, rightEntities, 24, 24, 53 - 4); }, - context => + async context => { - var leftEntities = context.Set().Include(e => e.ThreeSkipFull).OrderBy(e => e.Key2) - .ToList(); - var rightEntities = context.Set().Include("UnidirectionalEntityCompositeKey") + var leftEntities = await context.Set().Include(e => e.ThreeSkipFull).OrderBy(e => e.Key2) + .ToListAsync(); + var rightEntities = await context.Set().Include("UnidirectionalEntityCompositeKey") .OrderBy(e => e.Name) - .ToList(); + .ToListAsync(); ValidateFixup(context, leftEntities, rightEntities, 24, 24, 53 - 4); }); @@ -792,16 +796,17 @@ void ValidateFixup( } [ConditionalFact] - public virtual void Can_delete_with_many_to_many_composite_additional_pk_with_navs_unidirectional() + public virtual Task Can_delete_with_many_to_many_composite_additional_pk_with_navs_unidirectional() { var threeId = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var ones = context.Set().Include(e => e.ThreeSkipFull).OrderBy(e => e.Key2).ToList(); - var threes = context.Set().Include("UnidirectionalEntityCompositeKey").OrderBy(e => e.Name) - .ToList(); + var ones = await context.Set().Include(e => e.ThreeSkipFull).OrderBy(e => e.Key2) + .ToListAsync(); + var threes = await context.Set().Include("UnidirectionalEntityCompositeKey").OrderBy(e => e.Name) + .ToListAsync(); // Make sure other related entities are loaded for delete fixup context.Set().Load(); @@ -847,7 +852,7 @@ public virtual void Can_delete_with_many_to_many_composite_additional_pk_with_na ? EntityState.Deleted : EntityState.Unchanged, e.State)); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.Equal(0, ones.SelectMany(e => e.ThreeSkipFull).Count(e => e == toRemoveThree)); @@ -864,11 +869,12 @@ public virtual void Can_delete_with_many_to_many_composite_additional_pk_with_na && e.Entity.CompositeId3 == new DateTime(2006, 1, 1)) || e.Entity.ThreeId == threeId); }, - context => + async context => { - var ones = context.Set().Include(e => e.ThreeSkipFull).OrderBy(e => e.Key2).ToList(); - var threes = context.Set().Include("UnidirectionalEntityCompositeKey").OrderBy(e => e.Name) - .ToList(); + var ones = await context.Set().Include(e => e.ThreeSkipFull).OrderBy(e => e.Key2) + .ToListAsync(); + var threes = await context.Set().Include("UnidirectionalEntityCompositeKey").OrderBy(e => e.Name) + .ToListAsync(); ValidateNavigations(context, ones, threes); @@ -1000,7 +1006,7 @@ await ExecuteWithStrategyInTransactionAsync( } else { - context.SaveChanges(); + await context.SaveChangesAsync(); } ValidateFixup(context, leftEntities, rightEntities); @@ -1053,15 +1059,17 @@ void ValidateFixup(DbContext context, IList leftEntitie } [ConditionalFact] - public virtual void Can_update_many_to_many_self_unidirectional() + public virtual Task Can_update_many_to_many_self_unidirectional() { List ids = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var leftEntities = context.Set().Include(e => e.SelfSkipSharedRight).OrderBy(e => e.Name).ToList(); - var rightEntities = context.Set().Include("UnidirectionalEntityTwo").OrderBy(e => e.Name).ToList(); + var leftEntities = await context.Set().Include(e => e.SelfSkipSharedRight).OrderBy(e => e.Name) + .ToListAsync(); + var rightEntities = await context.Set().Include("UnidirectionalEntityTwo").OrderBy(e => e.Name) + .ToListAsync(); var twos = new[] { @@ -1147,16 +1155,18 @@ public virtual void Can_update_many_to_many_self_unidirectional() ValidateFixup(context, leftEntities, rightEntities, 28, 42); - context.SaveChanges(); + await context.SaveChangesAsync(); ids = twos.Select(e => e.Id).ToList(); ValidateFixup(context, leftEntities, rightEntities, 28, 42 - 4); }, - context => + async context => { - var leftEntities = context.Set().Include(e => e.SelfSkipSharedRight).OrderBy(e => e.Name).ToList(); - var rightEntities = context.Set().Include("UnidirectionalEntityTwo").OrderBy(e => e.Name).ToList(); + var leftEntities = await context.Set().Include(e => e.SelfSkipSharedRight).OrderBy(e => e.Name) + .ToListAsync(); + var rightEntities = await context.Set().Include("UnidirectionalEntityTwo").OrderBy(e => e.Name) + .ToListAsync(); ValidateFixup(context, leftEntities, rightEntities, 28, 42 - 4); }); @@ -1275,7 +1285,7 @@ await ExecuteWithStrategyInTransactionAsync( } else { - context.SaveChanges(); + await context.SaveChangesAsync(); } ValidateFixup(context, leftEntities, rightEntities); @@ -1317,14 +1327,15 @@ void ValidateFixup(DbContext context, IList leftEntitie } [ConditionalFact] - public virtual void Can_update_many_to_many_with_inheritance_unidirectional() + public virtual Task Can_update_many_to_many_with_inheritance_unidirectional() { - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var leftEntities = context.Set().Include(e => e.BranchSkip).OrderBy(e => e.Name).ToList(); - var rightEntities = context.Set().Include("UnidirectionalEntityOne").OrderBy(e => e.Name) - .ToList(); + var leftEntities = await context.Set().Include(e => e.BranchSkip).OrderBy(e => e.Name) + .ToListAsync(); + var rightEntities = await context.Set().Include("UnidirectionalEntityOne").OrderBy(e => e.Name) + .ToListAsync(); leftEntities[0].BranchSkip.Add( context.Set().CreateInstance( @@ -1405,15 +1416,16 @@ public virtual void Can_update_many_to_many_with_inheritance_unidirectional() ValidateFixup(context, leftEntities, rightEntities, 24, 14, 55); - context.SaveChanges(); + await context.SaveChangesAsync(); ValidateFixup(context, leftEntities, rightEntities, 24, 14, 55 - 4); }, - context => + async context => { - var leftEntities = context.Set().Include(e => e.BranchSkip).OrderBy(e => e.Name).ToList(); - var rightEntities = context.Set().Include("UnidirectionalEntityOne").OrderBy(e => e.Name) - .ToList(); + var leftEntities = await context.Set().Include(e => e.BranchSkip).OrderBy(e => e.Name) + .ToListAsync(); + var rightEntities = await context.Set().Include("UnidirectionalEntityOne").OrderBy(e => e.Name) + .ToListAsync(); ValidateFixup(context, leftEntities, rightEntities, 24, 14, 55 - 4); }); @@ -1534,7 +1546,7 @@ await ExecuteWithStrategyInTransactionAsync( } else { - context.SaveChanges(); + await context.SaveChangesAsync(); } ValidateFixup(context, leftEntities, rightEntities, postSave: true); @@ -1611,16 +1623,17 @@ void ValidateFixup( } [ConditionalFact] - public virtual void Can_update_many_to_many_self_with_payload_unidirectional() + public virtual Task Can_update_many_to_many_self_with_payload_unidirectional() { List keys = null; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var leftEntities = context.Set().Include("UnidirectionalEntityOne").OrderBy(e => e.Name).ToList(); - var rightEntities = context.Set().Include(e => e.SelfSkipPayloadLeft).OrderBy(e => e.Name) - .ToList(); + var leftEntities = await context.Set().Include("UnidirectionalEntityOne").OrderBy(e => e.Name) + .ToListAsync(); + var rightEntities = await context.Set().Include(e => e.SelfSkipPayloadLeft).OrderBy(e => e.Name) + .ToListAsync(); var ones = new[] { @@ -1720,18 +1733,18 @@ public virtual void Can_update_many_to_many_self_with_payload_unidirectional() ValidateFixup(context, leftEntities, rightEntities, 28, 37, postSave: false); - context.SaveChanges(); + await context.SaveChangesAsync(); keys = ones.Select(e => e.Id).ToList(); ValidateFixup(context, leftEntities, rightEntities, 28, 37 - 4, postSave: true); }, - context => + async context => { - var leftEntities = context.Set().Include("UnidirectionalEntityOne").OrderBy(e => e.Name) - .ToList(); - var rightEntities = context.Set().Include(e => e.SelfSkipPayloadLeft).OrderBy(e => e.Name) - .ToList(); + var leftEntities = await context.Set().Include("UnidirectionalEntityOne").OrderBy(e => e.Name) + .ToListAsync(); + var rightEntities = await context.Set().Include(e => e.SelfSkipPayloadLeft).OrderBy(e => e.Name) + .ToListAsync(); ValidateFixup(context, leftEntities, rightEntities, 28, 37 - 4, postSave: true); }); @@ -1878,7 +1891,7 @@ await ExecuteWithStrategyInTransactionAsync( } else { - context.SaveChanges(); + await context.SaveChangesAsync(); } ValidateFixup(context, leftEntities, rightEntities, postSave: true); @@ -1935,15 +1948,16 @@ void ValidateFixup( } [ConditionalFact] - public virtual void Can_update_many_to_many_shared_with_payload_unidirectional() + public virtual Task Can_update_many_to_many_shared_with_payload_unidirectional() { - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var leftEntities = context.Set().Include(e => e.ThreeSkipPayloadFullShared).OrderBy(e => e.Name) - .ToList(); - var rightEntities = context.Set().Include("UnidirectionalEntityOne1").OrderBy(e => e.Name) - .ToList(); + var leftEntities = await context.Set().Include(e => e.ThreeSkipPayloadFullShared) + .OrderBy(e => e.Name) + .ToListAsync(); + var rightEntities = await context.Set().Include("UnidirectionalEntityOne1").OrderBy(e => e.Name) + .ToListAsync(); leftEntities[0].ThreeSkipPayloadFullShared.Add( context.UnidirectionalEntityThrees.CreateInstance( @@ -2026,21 +2040,24 @@ public virtual void Can_update_many_to_many_shared_with_payload_unidirectional() } var joinSet = context.Set>("UnidirectionalJoinOneToThreePayloadFullShared"); - joinSet.Find(GetEntityOneId(context, "Z7712"), GetEntityThreeId(context, "EntityThree 1"))["Payload"] = "Set!"; - joinSet.Find(GetEntityOneId(context, "EntityOne 20"), GetEntityThreeId(context, "EntityThree 16"))["Payload"] = "Changed!"; + (await joinSet.FindAsync(GetEntityOneId(context, "Z7712"), GetEntityThreeId(context, "EntityThree 1")))!["Payload"] = + "Set!"; + (await joinSet.FindAsync( + GetEntityOneId(context, "EntityOne 20"), GetEntityThreeId(context, "EntityThree 16")))!["Payload"] = "Changed!"; ValidateFixup(context, leftEntities, rightEntities, 24, 24, 48, postSave: false); - context.SaveChanges(); + await context.SaveChangesAsync(); ValidateFixup(context, leftEntities, rightEntities, 24, 24, 48 - 4, postSave: true); }, - context => + async context => { - var leftEntities = context.Set().Include(e => e.ThreeSkipPayloadFullShared).OrderBy(e => e.Name) - .ToList(); - var rightEntities = context.Set().Include("UnidirectionalEntityOne1").OrderBy(e => e.Name) - .ToList(); + var leftEntities = await context.Set().Include(e => e.ThreeSkipPayloadFullShared) + .OrderBy(e => e.Name) + .ToListAsync(); + var rightEntities = await context.Set().Include("UnidirectionalEntityOne1").OrderBy(e => e.Name) + .ToListAsync(); ValidateFixup(context, leftEntities, rightEntities, 24, 24, 48 - 4, postSave: true); }); @@ -2194,7 +2211,7 @@ await ExecuteWithStrategyInTransactionAsync( } else { - context.SaveChanges(); + await context.SaveChangesAsync(); } ValidateFixup(context, leftEntities, rightEntities); @@ -2236,13 +2253,15 @@ void ValidateFixup(DbContext context, IList leftEntitie } [ConditionalFact] - public virtual void Can_update_many_to_many_shared_unidirectional() + public virtual Task Can_update_many_to_many_shared_unidirectional() { - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { - var leftEntities = context.Set().Include(e => e.TwoSkipShared).OrderBy(e => e.Name).ToList(); - var rightEntities = context.Set().Include("UnidirectionalEntityOne").OrderBy(e => e.Name).ToList(); + var leftEntities = await context.Set().Include(e => e.TwoSkipShared).OrderBy(e => e.Name) + .ToListAsync(); + var rightEntities = await context.Set().Include("UnidirectionalEntityOne").OrderBy(e => e.Name) + .ToListAsync(); var twos = new[] { @@ -2330,14 +2349,16 @@ public virtual void Can_update_many_to_many_shared_unidirectional() ValidateFixup(context, leftEntities, rightEntities, 24, 24, 53); - context.SaveChanges(); + await context.SaveChangesAsync(); ValidateFixup(context, leftEntities, rightEntities, 24, 24, 49); }, - context => + async context => { - var leftEntities = context.Set().Include(e => e.TwoSkipShared).OrderBy(e => e.Name).ToList(); - var rightEntities = context.Set().Include("UnidirectionalEntityOne").OrderBy(e => e.Name).ToList(); + var leftEntities = await context.Set().Include(e => e.TwoSkipShared).OrderBy(e => e.Name) + .ToListAsync(); + var rightEntities = await context.Set().Include("UnidirectionalEntityOne").OrderBy(e => e.Name) + .ToListAsync(); ValidateFixup(context, leftEntities, rightEntities, 24, 24, 49); }); @@ -2538,7 +2559,7 @@ await ExecuteWithStrategyInTransactionAsync( } else { - context.SaveChanges(); + await context.SaveChangesAsync(); } ValidateFixup(context, leftEntities, rightEntities); @@ -2680,7 +2701,7 @@ await ExecuteWithStrategyInTransactionAsync( } else { - context.SaveChanges(); + await context.SaveChangesAsync(); } ValidateFixup(context, leftEntities, rightEntities); @@ -2737,12 +2758,12 @@ void ValidateFixup(DbContext context, IList leftEntitie } [ConditionalFact] - public virtual void Can_insert_update_delete_proxyable_shared_type_entity_type_unidirectional() + public virtual Task Can_insert_update_delete_proxyable_shared_type_entity_type_unidirectional() { var id = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var entity = context.Set("PST").CreateInstance( (e, p) => @@ -2753,13 +2774,13 @@ public virtual void Can_insert_update_delete_proxyable_shared_type_entity_type_u context.Set("PST").Add(entity); - context.SaveChanges(); + await context.SaveChangesAsync(); id = (int)entity["Id"]; }, - context => + async context => { - var entity = context.Set("PST").Single(e => (int)e["Id"] == id); + var entity = await context.Set("PST").SingleAsync(e => (int)e["Id"] == id); Assert.Equal("NewlyAdded", (string)entity["Payload"]); @@ -2770,19 +2791,19 @@ public virtual void Can_insert_update_delete_proxyable_shared_type_entity_type_u context.ChangeTracker.DetectChanges(); } - context.SaveChanges(); + await context.SaveChangesAsync(); }, - context => + async context => { - var entity = context.Set("PST").Single(e => (int)e["Id"] == id); + var entity = await context.Set("PST").SingleAsync(e => (int)e["Id"] == id); Assert.Equal("AlreadyUpdated", (string)entity["Payload"]); context.Set("PST").Remove(entity); - context.SaveChanges(); + await context.SaveChangesAsync(); - Assert.False(context.Set("PST").Any(e => (int)e["Id"] == id)); + Assert.False(await context.Set("PST").AnyAsync(e => (int)e["Id"] == id)); }); } @@ -2888,7 +2909,7 @@ await ExecuteWithStrategyInTransactionAsync( } else { - context.SaveChanges(); + await context.SaveChangesAsync(); } ValidateFixup(context, leftEntities, rightEntities); diff --git a/test/EFCore.Specification.Tests/Update/UpdatesTestBase.cs b/test/EFCore.Specification.Tests/Update/UpdatesTestBase.cs index 3c30fb91401..f03ec477d41 100644 --- a/test/EFCore.Specification.Tests/Update/UpdatesTestBase.cs +++ b/test/EFCore.Specification.Tests/Update/UpdatesTestBase.cs @@ -37,7 +37,7 @@ public virtual async Task Can_delete_and_add_for_same_key(bool async) else { context.Add(rodney1); - context.SaveChanges(); + await context.SaveChangesAsync(); } context.Remove(rodney1); @@ -51,7 +51,7 @@ public virtual async Task Can_delete_and_add_for_same_key(bool async) else { context.Add(rodney2); - context.SaveChanges(); + await context.SaveChangesAsync(); } Assert.Equal(1, context.ChangeTracker.Entries().Count()); @@ -68,14 +68,14 @@ public virtual async Task Can_change_type_of_pk_to_pk_dependent_by_replacing_wit { var gift = new Gift { Recipient = "Alice", Obscurer = new GiftPaper { Pattern = "Stripes" } }; await context.AddAsync(gift); - _ = async ? await context.SaveChangesAsync() : context.SaveChanges(); + _ = async ? await context.SaveChangesAsync() : await context.SaveChangesAsync(); }, async context => { var gift = await context.Set().Include(e => e.Obscurer).SingleAsync(); var bag = new GiftBag { Pattern = "Gold stars" }; gift.Obscurer = bag; - _ = async ? await context.SaveChangesAsync() : context.SaveChanges(); + _ = async ? await context.SaveChangesAsync() : await context.SaveChangesAsync(); }, async context => { @@ -95,14 +95,14 @@ public virtual async Task Can_change_type_of__dependent_by_replacing_with_new_de { var lift = new Lift { Recipient = "Alice", Obscurer = new LiftPaper { Pattern = "Stripes" } }; await context.AddAsync(lift); - _ = async ? await context.SaveChangesAsync() : context.SaveChanges(); + _ = async ? await context.SaveChangesAsync() : await context.SaveChangesAsync(); }, async context => { var lift = await context.Set().Include(e => e.Obscurer).SingleAsync(); var bag = new LiftBag { Pattern = "Gold stars" }; lift.Obscurer = bag; - _ = async ? await context.SaveChangesAsync() : context.SaveChanges(); + _ = async ? await context.SaveChangesAsync() : await context.SaveChangesAsync(); }, async context => { @@ -114,27 +114,27 @@ public virtual async Task Can_change_type_of__dependent_by_replacing_with_new_de }); [ConditionalFact] - public virtual void Mutation_of_tracked_values_does_not_mutate_values_in_store() + public virtual Task Mutation_of_tracked_values_does_not_mutate_values_in_store() { var id1 = Guid.NewGuid(); var id2 = Guid.NewGuid(); var bytes = new byte[] { 1, 2, 3, 4 }; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.AFewBytes.AddRange( new AFewBytes { Id = id1, Bytes = bytes }, new AFewBytes { Id = id2, Bytes = bytes }); - context.SaveChanges(); + await context.SaveChangesAsync(); }, - context => + async context => { bytes[1] = 22; - var fromStore1 = context.AFewBytes.First(p => p.Id == id1); - var fromStore2 = context.AFewBytes.First(p => p.Id == id2); + var fromStore1 = await context.AFewBytes.FirstAsync(p => p.Id == id1); + var fromStore2 = await context.AFewBytes.FirstAsync(p => p.Id == id2); Assert.Equal(2, fromStore1.Bytes[1]); Assert.Equal(2, fromStore2.Bytes[1]); @@ -144,12 +144,12 @@ public virtual void Mutation_of_tracked_values_does_not_mutate_values_in_store() context.Entry(fromStore1).State = EntityState.Modified; - context.SaveChanges(); + await context.SaveChangesAsync(); }, - context => + async context => { - var fromStore1 = context.AFewBytes.First(p => p.Id == id1); - var fromStore2 = context.AFewBytes.First(p => p.Id == id2); + var fromStore1 = await context.AFewBytes.FirstAsync(p => p.Id == id1); + var fromStore2 = await context.AFewBytes.FirstAsync(p => p.Id == id2); Assert.Equal(222, fromStore1.Bytes[1]); Assert.Equal(2, fromStore2.Bytes[1]); @@ -157,12 +157,12 @@ public virtual void Mutation_of_tracked_values_does_not_mutate_values_in_store() } [ConditionalFact] - public virtual void Save_partial_update() + public virtual Task Save_partial_update() { var productId = new Guid("984ade3c-2f7b-4651-a351-642e92ab7146"); - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var entry = context.Products.Attach( new Product { Id = productId, Price = 1.49M }); @@ -173,11 +173,11 @@ public virtual void Save_partial_update() Assert.False(entry.Property(p => p.DependentId).IsModified); Assert.False(entry.Property(p => p.Name).IsModified); - context.SaveChanges(); + await context.SaveChangesAsync(); }, - context => + async context => { - var product = context.Products.First(p => p.Id == productId); + var product = await context.Products.FirstAsync(p => p.Id == productId); Assert.Equal(1.99M, product.Price); Assert.Equal("Apple Cider", product.Name); @@ -185,9 +185,9 @@ public virtual void Save_partial_update() } [ConditionalFact] - public virtual void Save_partial_update_on_missing_record_throws() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Save_partial_update_on_missing_record_throws() + => ExecuteWithStrategyInTransactionAsync( + async context => { var entry = context.Products.Attach( new Product { Id = new Guid("3d1302c5-4cf8-4043-9758-de9398f6fe10"), Name = "Apple Fritter" }); @@ -196,17 +196,17 @@ public virtual void Save_partial_update_on_missing_record_throws() Assert.Equal( UpdateConcurrencyMessage, - Assert.Throws( - () => context.SaveChanges()).Message); + (await Assert.ThrowsAsync( + () => context.SaveChangesAsync())).Message); }); [ConditionalFact] - public virtual void Save_partial_update_on_concurrency_token_original_value_mismatch_throws() + public virtual Task Save_partial_update_on_concurrency_token_original_value_mismatch_throws() { var productId = new Guid("984ade3c-2f7b-4651-a351-642e92ab7146"); - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var entry = context.Products.Attach( new Product @@ -220,18 +220,18 @@ public virtual void Save_partial_update_on_concurrency_token_original_value_mism Assert.Equal( UpdateConcurrencyTokenMessage, - Assert.Throws( - () => context.SaveChanges()).Message); + (await Assert.ThrowsAsync( + () => context.SaveChangesAsync())).Message); }); } [ConditionalFact] - public virtual void Update_on_bytes_concurrency_token_original_value_mismatch_throws() + public virtual Task Update_on_bytes_concurrency_token_original_value_mismatch_throws() { var productId = Guid.NewGuid(); - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.Add( new ProductWithBytes @@ -241,9 +241,9 @@ public virtual void Update_on_bytes_concurrency_token_original_value_mismatch_th Bytes = [1, 2, 3, 4, 5, 6, 7, 8] }); - context.SaveChanges(); + await context.SaveChangesAsync(); }, - context => + async context => { var entry = context.ProductWithBytes.Attach( new ProductWithBytes @@ -255,19 +255,19 @@ public virtual void Update_on_bytes_concurrency_token_original_value_mismatch_th entry.Entity.Name = "GigaChips"; - Assert.Throws( - () => context.SaveChanges()); + await Assert.ThrowsAsync( + () => context.SaveChangesAsync()); }, - context => Assert.Equal("MegaChips", context.ProductWithBytes.Find(productId)!.Name)); + async context => Assert.Equal("MegaChips", (await context.ProductWithBytes.FindAsync(productId))!.Name)); } [ConditionalFact] - public virtual void Update_on_bytes_concurrency_token_original_value_matches_does_not_throw() + public virtual Task Update_on_bytes_concurrency_token_original_value_matches_does_not_throw() { var productId = Guid.NewGuid(); - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.Add( new ProductWithBytes @@ -277,9 +277,9 @@ public virtual void Update_on_bytes_concurrency_token_original_value_matches_doe Bytes = [1, 2, 3, 4, 5, 6, 7, 8] }); - context.SaveChanges(); + await context.SaveChangesAsync(); }, - context => + async context => { var entry = context.ProductWithBytes.Attach( new ProductWithBytes @@ -291,18 +291,18 @@ public virtual void Update_on_bytes_concurrency_token_original_value_matches_doe entry.Entity.Name = "GigaChips"; - Assert.Equal(1, context.SaveChanges()); + Assert.Equal(1, await context.SaveChangesAsync()); }, - context => Assert.Equal("GigaChips", context.ProductWithBytes.Find(productId)!.Name)); + async context => Assert.Equal("GigaChips", (await context.ProductWithBytes.FindAsync(productId))!.Name)); } [ConditionalFact] - public virtual void Remove_on_bytes_concurrency_token_original_value_mismatch_throws() + public virtual Task Remove_on_bytes_concurrency_token_original_value_mismatch_throws() { var productId = Guid.NewGuid(); - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.Add( new ProductWithBytes @@ -312,9 +312,9 @@ public virtual void Remove_on_bytes_concurrency_token_original_value_mismatch_th Bytes = [1, 2, 3, 4, 5, 6, 7, 8] }); - context.SaveChanges(); + await context.SaveChangesAsync(); }, - context => + async context => { var entry = context.ProductWithBytes.Attach( new ProductWithBytes @@ -326,19 +326,19 @@ public virtual void Remove_on_bytes_concurrency_token_original_value_mismatch_th entry.State = EntityState.Deleted; - Assert.Throws( - () => context.SaveChanges()); + await Assert.ThrowsAsync( + () => context.SaveChangesAsync()); }, - context => Assert.Equal("MegaChips", context.ProductWithBytes.Find(productId)!.Name)); + async context => Assert.Equal("MegaChips", (await context.ProductWithBytes.FindAsync(productId))!.Name)); } [ConditionalFact] - public virtual void Remove_on_bytes_concurrency_token_original_value_matches_does_not_throw() + public virtual Task Remove_on_bytes_concurrency_token_original_value_matches_does_not_throw() { var productId = Guid.NewGuid(); - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.Add( new ProductWithBytes @@ -348,9 +348,9 @@ public virtual void Remove_on_bytes_concurrency_token_original_value_matches_doe Bytes = [1, 2, 3, 4, 5, 6, 7, 8] }); - context.SaveChanges(); + await context.SaveChangesAsync(); }, - context => + async context => { var entry = context.ProductWithBytes.Attach( new ProductWithBytes @@ -362,15 +362,15 @@ public virtual void Remove_on_bytes_concurrency_token_original_value_matches_doe entry.State = EntityState.Deleted; - Assert.Equal(1, context.SaveChanges()); + Assert.Equal(1, await context.SaveChangesAsync()); }, - context => Assert.Null(context.ProductWithBytes.Find(productId))); + async context => Assert.Null(await context.ProductWithBytes.FindAsync(productId))); } [ConditionalFact] - public virtual void Can_add_and_remove_self_refs() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Can_add_and_remove_self_refs() + => ExecuteWithStrategyInTransactionAsync( + async context => { var parent = new Person("1", null); var child1 = new Person("2", parent); @@ -388,7 +388,7 @@ public virtual void Can_add_and_remove_self_refs() context.Add(grandchild3); context.Add(grandchild4); - context.SaveChanges(); + await context.SaveChangesAsync(); context.Remove(parent); context.Remove(child1); @@ -414,33 +414,32 @@ public virtual void Can_add_and_remove_self_refs() context.Add(grandchild3); context.Add(grandchild4); - context.SaveChanges(); + await context.SaveChangesAsync(); }, - context => + async context => { - var people = context.Set() + var people = await context.Set() .Include(p => p.Parent!).ThenInclude(c => c.Parent!).ThenInclude(c => c.Parent) - .ToList(); + .ToListAsync(); Assert.Equal(7, people.Count); Assert.Equal("1", people.Single(p => p.Parent == null).Name); }); [ConditionalFact] - public virtual void Can_change_enums_with_conversion() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Can_change_enums_with_conversion() + => ExecuteWithStrategyInTransactionAsync( + async context => { var person = new Person("1", null) { - Address = new Address { Country = Country.Eswatini, City = "Bulembu" }, - Country = "Eswatini" + Address = new Address { Country = Country.Eswatini, City = "Bulembu" }, Country = "Eswatini" }; context.Add(person); - context.SaveChanges(); + await context.SaveChangesAsync(); }, - context => + async context => { var person = context.Set().Single(); person.Address = new Address @@ -452,11 +451,11 @@ public virtual void Can_change_enums_with_conversion() person.Country = "Türkiye"; person.ZipCode = "42100"; - context.SaveChanges(); + await context.SaveChangesAsync(); }, - context => + async context => { - var person = context.Set().Single(); + var person = await context.Set().SingleAsync(); Assert.Equal(Country.Türkiye, person.Address!.Country); Assert.Equal("Konya", person.Address.City); @@ -466,66 +465,65 @@ public virtual void Can_change_enums_with_conversion() }); [ConditionalFact] - public virtual void Can_remove_partial() + public virtual Task Can_remove_partial() { var productId = new Guid("984ade3c-2f7b-4651-a351-642e92ab7146"); - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.Products.Remove( new Product { Id = productId, Price = 1.49M }); - context.SaveChanges(); + await context.SaveChangesAsync(); }, - context => + async context => { - var product = context.Products.FirstOrDefault(f => f.Id == productId); + var product = await context.Products.FirstOrDefaultAsync(f => f.Id == productId); Assert.Null(product); }); } [ConditionalFact] - public virtual void Remove_partial_on_missing_record_throws() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Remove_partial_on_missing_record_throws() + => ExecuteWithStrategyInTransactionAsync( + async context => { context.Products.Remove( new Product { Id = new Guid("3d1302c5-4cf8-4043-9758-de9398f6fe10") }); Assert.Equal( UpdateConcurrencyMessage, - Assert.Throws( - () => context.SaveChanges()).Message); + (await Assert.ThrowsAsync( + () => context.SaveChangesAsync())).Message); }); [ConditionalFact] - public virtual void Remove_partial_on_concurrency_token_original_value_mismatch_throws() + public virtual Task Remove_partial_on_concurrency_token_original_value_mismatch_throws() { var productId = new Guid("984ade3c-2f7b-4651-a351-642e92ab7146"); - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { context.Products.Remove( new Product { - Id = productId, - Price = 3.49M // Not the same as the value stored in the database + Id = productId, Price = 3.49M // Not the same as the value stored in the database }); Assert.Equal( UpdateConcurrencyTokenMessage, - Assert.Throws( - () => context.SaveChanges()).Message); + (await Assert.ThrowsAsync( + () => context.SaveChangesAsync())).Message); }); } [ConditionalFact] - public virtual void Save_replaced_principal() - => ExecuteWithStrategyInTransaction( - context => + public virtual Task Save_replaced_principal() + => ExecuteWithStrategyInTransactionAsync( + async context => { var category = context.Categories.AsNoTracking().Single(); var products = context.Products.AsNoTracking().Where(p => p.DependentId == category.PrincipalId).ToList(); @@ -541,12 +539,12 @@ public virtual void Save_replaced_principal() context.Remove(category); context.Add(newCategory); - context.SaveChanges(); + await context.SaveChangesAsync(); }, - context => + async context => { - var category = context.Categories.Single(); - var products = context.Products.Where(p => p.DependentId == category.PrincipalId).ToList(); + var category = await context.Categories.SingleAsync(); + var products = await context.Products.Where(p => p.DependentId == category.PrincipalId).ToListAsync(); Assert.Equal("New Category", category.Name); Assert.Equal(2, products.Count); @@ -690,7 +688,7 @@ public Task Ignore_before_save_property_is_still_generated(bool async) else { context.AddRange(entities); - context.SaveChanges(); + await context.SaveChangesAsync(); } }, async context => @@ -820,7 +818,7 @@ public Task Ignore_before_save_property_is_still_generated_graph(bool async) else { context.AddRange(entities); - context.SaveChanges(); + await context.SaveChangesAsync(); } }, async context => @@ -901,14 +899,6 @@ protected class Top protected abstract string UpdateConcurrencyTokenMessage { get; } - protected virtual void ExecuteWithStrategyInTransaction( - Action testOperation, - Action? nestedTestOperation1 = null, - Action? nestedTestOperation2 = null) - => TestHelpers.ExecuteWithStrategyInTransaction( - CreateContext, UseTransaction, - testOperation, nestedTestOperation1, nestedTestOperation2); - protected virtual Task ExecuteWithStrategyInTransactionAsync( Func testOperation, Func? nestedTestOperation1 = null, @@ -1085,7 +1075,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con modelBuilder.Entity(); } - protected override void Seed(UpdatesContext context) - => UpdatesContext.Seed(context); + protected override Task SeedAsync(UpdatesContext context) + => UpdatesContext.SeedAsync(context); } } diff --git a/test/EFCore.Specification.Tests/ValueConvertersEndToEndTestBase.cs b/test/EFCore.Specification.Tests/ValueConvertersEndToEndTestBase.cs index db8b9d94bba..72122064f31 100644 --- a/test/EFCore.Specification.Tests/ValueConvertersEndToEndTestBase.cs +++ b/test/EFCore.Specification.Tests/ValueConvertersEndToEndTestBase.cs @@ -154,9 +154,7 @@ protected ValueConvertersEndToEndTestBase(TFixture fixture) nameof(TheExperience.Jimi), nameof(TheExperience.Mitch), nameof(TheExperience.Noel), nameof(TheExperience.Jimi) ] }, - { - typeof(Guid), [Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString()] - }, + { typeof(Guid), [Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString()] }, { typeof(ulong), ["77", "0", "78", "0"] }, { typeof(sbyte), ["-77", "75", "-78", "0"] }, { typeof(byte), ["77", "75", "78", "0"] }, @@ -167,7 +165,7 @@ protected ValueConvertersEndToEndTestBase(TFixture fixture) [InlineData(new[] { 0, 1, 2, 3 })] [InlineData(new[] { 3, 2, 1, 0 })] [InlineData(new[] { 0, 2, 0, 2 })] - public virtual void Can_insert_and_read_back_with_conversions(int[] valueOrder) + public virtual async Task Can_insert_and_read_back_with_conversions(int[] valueOrder) { var id = Guid.Empty; @@ -178,27 +176,27 @@ public virtual void Can_insert_and_read_back_with_conversions(int[] valueOrder) SetPropertyValues(context, entity, valueOrder[0], -1); context.Add(entity); - context.SaveChanges(); + await context.SaveChangesAsync(); id = entity.Id; } using (var context = CreateContext()) { - SetPropertyValues(context, context.Set().Single(e => e.Id == id), valueOrder[1], valueOrder[0]); - context.SaveChanges(); + SetPropertyValues(context, await context.Set().SingleAsync(e => e.Id == id), valueOrder[1], valueOrder[0]); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - SetPropertyValues(context, context.Set().Single(e => e.Id == id), valueOrder[2], valueOrder[1]); - context.SaveChanges(); + SetPropertyValues(context, await context.Set().SingleAsync(e => e.Id == id), valueOrder[2], valueOrder[1]); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - SetPropertyValues(context, context.Set().Single(e => e.Id == id), valueOrder[3], valueOrder[2]); - context.SaveChanges(); + SetPropertyValues(context, await context.Set().SingleAsync(e => e.Id == id), valueOrder[3], valueOrder[2]); + await context.SaveChangesAsync(); } } diff --git a/test/EFCore.Specification.Tests/WithConstructorsTestBase.cs b/test/EFCore.Specification.Tests/WithConstructorsTestBase.cs index 9c759b1377b..4d55c475caa 100644 --- a/test/EFCore.Specification.Tests/WithConstructorsTestBase.cs +++ b/test/EFCore.Specification.Tests/WithConstructorsTestBase.cs @@ -32,10 +32,9 @@ protected virtual void UseTransaction(DatabaseFacade facade, IDbContextTransacti } [ConditionalFact] - public virtual void Query_and_update_using_constructors_with_property_parameters() - => TestHelpers.ExecuteWithStrategyInTransaction( - CreateContext, UseTransaction, - context => + public virtual Task Query_and_update_using_constructors_with_property_parameters() + => TestHelpers.ExecuteWithStrategyInTransactionAsync( + CreateContext, UseTransaction, async context => { var blog = context.Set().Include(e => e.Posts).Single(); @@ -58,11 +57,10 @@ public virtual void Query_and_update_using_constructors_with_property_parameters var newBlog = context.Add(new Blog("Cats", 100)).Entity; newBlog.AddPost(new Post("Baxter is a cat.", "With dog friends.")); - context.SaveChanges(); - }, - context => + await context.SaveChangesAsync(); + }, async context => { - var blogs = context.Set().Include(e => e.Posts).OrderBy(e => e.Title).ToList(); + var blogs = await context.Set().Include(e => e.Posts).OrderBy(e => e.Title).ToListAsync(); Assert.Equal(2, blogs.Count); @@ -1648,7 +1646,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con modelBuilder.Entity(); } - protected override void Seed(WithConstructorsContext context) + protected override Task SeedAsync(WithConstructorsContext context) { var blog = new Blog("Puppies"); @@ -1749,7 +1747,7 @@ protected override void Seed(WithConstructorsContext context) context.Add(lazyPcsBlog); - context.SaveChanges(); + return context.SaveChangesAsync(); } } } diff --git a/test/EFCore.SqlServer.FunctionalTests/BatchingTest.cs b/test/EFCore.SqlServer.FunctionalTests/BatchingTest.cs index 98acc312378..48996aa4a16 100644 --- a/test/EFCore.SqlServer.FunctionalTests/BatchingTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/BatchingTest.cs @@ -31,10 +31,10 @@ public BatchingTest(BatchingTestFixture fixture) [InlineData(false, true, false)] [InlineData(true, false, false)] [InlineData(false, false, false)] - public void Inserts_are_batched_correctly(bool clientPk, bool clientFk, bool clientOrder) + public Task Inserts_are_batched_correctly(bool clientPk, bool clientFk, bool clientOrder) { var expectedBlogs = new List(); - ExecuteWithStrategyInTransaction( + return ExecuteWithStrategyInTransactionAsync( context => { var owner1 = new Owner(); @@ -64,18 +64,18 @@ public void Inserts_are_batched_correctly(bool clientPk, bool clientFk, bool cli expectedBlogs.Add(blog); } - context.SaveChanges(); + return context.SaveChangesAsync(); }, context => AssertDatabaseState(context, clientOrder, expectedBlogs)); } [ConditionalFact] - public void Inserts_and_updates_are_batched_correctly() + public Task Inserts_and_updates_are_batched_correctly() { var expectedBlogs = new List(); - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var owner1 = new Owner { Name = "0" }; var owner2 = new Owner { Name = "1" }; @@ -92,7 +92,7 @@ public void Inserts_and_updates_are_batched_correctly() context.Set().Add(blog1); expectedBlogs.Add(blog1); - context.SaveChanges(); + await context.SaveChangesAsync(); owner2.Name = "2"; @@ -117,7 +117,7 @@ public void Inserts_and_updates_are_batched_correctly() context.Set().Add(blog3); expectedBlogs.Add(blog3); - context.SaveChanges(); + await context.SaveChangesAsync(); }, context => AssertDatabaseState(context, true, expectedBlogs)); } @@ -127,14 +127,13 @@ public void Inserts_and_updates_are_batched_correctly() [InlineData(3)] [InlineData(4)] [InlineData(100)] - public void Insertion_order_is_preserved(int maxBatchSize) + public Task Insertion_order_is_preserved(int maxBatchSize) { var blogId = new Guid(); - TestHelpers.ExecuteWithStrategyInTransaction( + return TestHelpers.ExecuteWithStrategyInTransactionAsync( () => (BloggingContext)Fixture.CreateContext(maxBatchSize: maxBatchSize), - UseTransaction, - context => + UseTransaction, async context => { var owner = new Owner(); var blog = new Blog { Owner = owner }; @@ -144,15 +143,14 @@ public void Insertion_order_is_preserved(int maxBatchSize) context.Add(new Post { Order = i, Blog = blog }); } - context.SaveChanges(); + await context.SaveChangesAsync(); blogId = blog.Id; - }, - context => + }, async context => { var posts = context.Set().Where(p => p.BlogId == blogId).OrderBy(p => p.Order); var lastId = 0; - foreach (var post in posts) + foreach (var post in await posts.ToListAsync()) { Assert.True(post.PostId > lastId, $"Last ID: {lastId}, current ID: {post.PostId}"); lastId = post.PostId; @@ -161,7 +159,7 @@ public void Insertion_order_is_preserved(int maxBatchSize) } [ConditionalFact] - public void Deadlock_on_inserts_and_deletes_with_dependents_is_handled_correctly() + public async Task Deadlock_on_inserts_and_deletes_with_dependents_is_handled_correctly() { var blogs = new List(); @@ -203,19 +201,21 @@ public void Deadlock_on_inserts_and_deletes_with_dependents_is_handled_correctly context.AddRange(blogs); - context.SaveChanges(); + await context.SaveChangesAsync(); } + var tasks = new List(); for (var i = 0; i < 10; i++) { - Parallel.ForEach( - blogs, blog => - { - RemoveAndAddPosts(blog); - }); + foreach (var blog in blogs) + { + tasks.Add(RemoveAndAddPosts(blog)); + } } - void RemoveAndAddPosts(Blog blog) + Task.WaitAll(tasks.ToArray()); + + async Task RemoveAndAddPosts(Blog blog) { using var context = (BloggingContext)Fixture.CreateContext(useConnectionString: true); @@ -226,14 +226,14 @@ void RemoveAndAddPosts(Blog blog) blog.Posts.Add(new Post { Comments = { new Comment() } }); blog.Posts.Add(new Post { Comments = { new Comment() } }); - context.SaveChanges(); + await context.SaveChangesAsync(); } - Fixture.Reseed(); + await Fixture.ReseedAsync(); } [ConditionalFact] - public void Deadlock_on_deletes_with_dependents_is_handled_correctly() + public async Task Deadlock_on_deletes_with_dependents_is_handled_correctly() { var owners = new[] { new Owner { Name = "0" }, new Owner { Name = "1" } }; using (var context = CreateContext()) @@ -258,30 +258,37 @@ public void Deadlock_on_deletes_with_dependents_is_handled_correctly() context.Add(blog); } - context.SaveChanges(); + await context.SaveChangesAsync(); } - Parallel.ForEach( - owners, owner => - { - using var context = (BloggingContext)Fixture.CreateContext(useConnectionString: true); + async Task Action(Owner owner) + { + using var context = (BloggingContext)Fixture.CreateContext(useConnectionString: true); - context.RemoveRange(context.Blogs.Where(b => b.OwnerId == owner.Id)); + context.RemoveRange(await context.Blogs.Where(b => b.OwnerId == owner.Id).ToListAsync()); - context.SaveChanges(); - }); + await context.SaveChangesAsync(); + } + + var tasks = new List(); + foreach (var owner in owners) + { + tasks.Add(Action(owner)); + } + + Task.WaitAll(tasks.ToArray()); using (var context = CreateContext()) { - Assert.Empty(context.Blogs); + Assert.Empty(await context.Blogs.ToListAsync()); } - Fixture.Reseed(); + await Fixture.ReseedAsync(); } [ConditionalFact] - public void Inserts_when_database_type_is_different() - => ExecuteWithStrategyInTransaction( + public Task Inserts_when_database_type_is_different() + => ExecuteWithStrategyInTransactionAsync( context => { var owner1 = new Owner { Id = "0", Name = "Zero" }; @@ -289,20 +296,18 @@ public void Inserts_when_database_type_is_different() context.Owners.Add(owner1); context.Owners.Add(owner2); - context.SaveChanges(); - }, - context => Assert.Equal(2, context.Owners.Count())); + return context.SaveChangesAsync(); + }, async context => Assert.Equal(2, await context.Owners.CountAsync())); [ConditionalTheory] [InlineData(3)] [InlineData(4)] - public void Inserts_are_batched_only_when_necessary(int minBatchSize) + public Task Inserts_are_batched_only_when_necessary(int minBatchSize) { var expectedBlogs = new List(); - TestHelpers.ExecuteWithStrategyInTransaction( + return TestHelpers.ExecuteWithStrategyInTransactionAsync( () => (BloggingContext)Fixture.CreateContext(minBatchSize), - UseTransaction, - context => + UseTransaction, async context => { var owner = new Owner(); context.Owners.Add(owner); @@ -317,7 +322,7 @@ public void Inserts_are_batched_only_when_necessary(int minBatchSize) Fixture.TestSqlLoggerFactory.Clear(); - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.Contains( minBatchSize == 3 @@ -331,13 +336,13 @@ public void Inserts_are_batched_only_when_necessary(int minBatchSize) }, context => AssertDatabaseState(context, false, expectedBlogs)); } - private void AssertDatabaseState(DbContext context, bool clientOrder, List expectedBlogs) + private async Task AssertDatabaseState(DbContext context, bool clientOrder, List expectedBlogs) { expectedBlogs = clientOrder ? expectedBlogs.OrderBy(b => b.Order).ToList() : expectedBlogs.OrderBy(b => b.Id).ToList(); var actualBlogs = clientOrder - ? context.Set().OrderBy(b => b.Order).ToList() + ? await context.Set().OrderBy(b => b.Order).ToListAsync() : expectedBlogs.OrderBy(b => b.Id).ToList(); Assert.Equal(expectedBlogs.Count, actualBlogs.Count); @@ -355,10 +360,10 @@ private void AssertDatabaseState(DbContext context, bool clientOrder, List private BloggingContext CreateContext() => (BloggingContext)Fixture.CreateContext(); - private void ExecuteWithStrategyInTransaction( - Action testOperation, - Action nestedTestOperation) - => TestHelpers.ExecuteWithStrategyInTransaction( + private Task ExecuteWithStrategyInTransactionAsync( + Func testOperation, + Func nestedTestOperation) + => TestHelpers.ExecuteWithStrategyInTransactionAsync( CreateContext, UseTransaction, testOperation, nestedTestOperation); protected void UseTransaction(DatabaseFacade facade, IDbContextTransaction transaction) @@ -440,10 +445,10 @@ protected override ITestStoreFactory TestStoreFactory protected override bool ShouldLogCategory(string logCategory) => logCategory == DbLoggerCategory.Update.Name; - protected override void Seed(PoolableDbContext context) + protected override async Task SeedAsync(PoolableDbContext context) { - context.Database.EnsureCreatedResiliently(); - context.Database.ExecuteSqlRaw( + await context.Database.EnsureCreatedResilientlyAsync(); + await context.Database.ExecuteSqlRawAsync( @" ALTER TABLE dbo.Owners ALTER COLUMN Name nvarchar(MAX);"); diff --git a/test/EFCore.SqlServer.FunctionalTests/BuiltInDataTypesSqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/BuiltInDataTypesSqlServerTest.cs index b014f814d79..0eb93759021 100644 --- a/test/EFCore.SqlServer.FunctionalTests/BuiltInDataTypesSqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/BuiltInDataTypesSqlServerTest.cs @@ -4266,9 +4266,9 @@ public void Can_get_column_types_from_built_model() } } - public override void Object_to_string_conversion() + public override async Task Object_to_string_conversion() { - base.Object_to_string_conversion(); + await base.Object_to_string_conversion(); AssertSql( """ diff --git a/test/EFCore.SqlServer.FunctionalTests/CommandConfigurationTest.cs b/test/EFCore.SqlServer.FunctionalTests/CommandConfigurationTest.cs index 6338a4c2d78..2f11a4990a8 100644 --- a/test/EFCore.SqlServer.FunctionalTests/CommandConfigurationTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/CommandConfigurationTest.cs @@ -30,9 +30,9 @@ public void Constructed_select_query_CommandBuilder_throws_when_negative_Command [InlineData(50, 5)] [InlineData(20, 2)] [InlineData(2, 1)] - public void Keys_generated_in_batches(int count, int expected) + public async Task Keys_generated_in_batches(int count, int expected) { - TestHelpers.ExecuteWithStrategyInTransaction( + await TestHelpers.ExecuteWithStrategyInTransactionAsync( Fixture.CreateContext, UseTransaction, context => { @@ -41,7 +41,7 @@ public void Keys_generated_in_batches(int count, int expected) context.Set().Add(new KettleChips { BestBuyDate = DateTime.Now, Name = "Doritos Locos Tacos " + i }); } - context.SaveChanges(); + return context.SaveChangesAsync(); }); Assert.Equal(expected, CountSqlLinesContaining("SELECT NEXT VALUE FOR", Fixture.TestSqlLoggerFactory.Sql)); diff --git a/test/EFCore.SqlServer.FunctionalTests/CommandInterceptionSqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/CommandInterceptionSqlServerTest.cs index 324f82539d3..b91ed44ac91 100644 --- a/test/EFCore.SqlServer.FunctionalTests/CommandInterceptionSqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/CommandInterceptionSqlServerTest.cs @@ -55,7 +55,7 @@ public override async Task Intercept_query_to_replace_execution(bool asy [InlineData(true, true)] public virtual async Task Intercept_query_to_get_statistics(bool async, bool inject) // Issue #23535 { - var (context, interceptor) = CreateContext(inject); + var (context, interceptor) = await CreateContextAsync(inject); using (context) { using (async @@ -186,7 +186,8 @@ public override DbContextOptionsBuilder AddOptions(DbContextOptionsBuilder build } } - public class CommandInterceptionWithDiagnosticsSqlServerTest(CommandInterceptionWithDiagnosticsSqlServerTest.InterceptionSqlServerFixture fixture) + public class CommandInterceptionWithDiagnosticsSqlServerTest( + CommandInterceptionWithDiagnosticsSqlServerTest.InterceptionSqlServerFixture fixture) : CommandInterceptionSqlServerTestBase(fixture), IClassFixture { diff --git a/test/EFCore.SqlServer.FunctionalTests/ComputedColumnTest.cs b/test/EFCore.SqlServer.FunctionalTests/ComputedColumnTest.cs index ce22c4c61de..009d5739827 100644 --- a/test/EFCore.SqlServer.FunctionalTests/ComputedColumnTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/ComputedColumnTest.cs @@ -5,7 +5,7 @@ namespace Microsoft.EntityFrameworkCore; #nullable disable -public class ComputedColumnTest : IDisposable +public class ComputedColumnTest : IAsyncLifetime { [ConditionalFact] public void Can_use_computed_columns() @@ -51,15 +51,12 @@ public void Can_use_computed_columns_with_null_values() private class Context(IServiceProvider serviceProvider, string databaseName) : DbContext { - private readonly IServiceProvider _serviceProvider = serviceProvider; - private readonly string _databaseName = databaseName; - public DbSet Entities { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder - .UseSqlServer(SqlServerTestStore.CreateConnectionString(_databaseName), b => b.ApplyConfiguration()) - .UseInternalServiceProvider(_serviceProvider); + .UseSqlServer(SqlServerTestStore.CreateConnectionString(databaseName), b => b.ApplyConfiguration()) + .UseInternalServiceProvider(serviceProvider); protected override void OnModelCreating(ModelBuilder modelBuilder) { @@ -101,16 +98,13 @@ public class EnumItem private class NullableContext(IServiceProvider serviceProvider, string databaseName) : DbContext { - private readonly IServiceProvider _serviceProvider = serviceProvider; - private readonly string _databaseName = databaseName; - // ReSharper disable once UnusedAutoPropertyAccessor.Local public DbSet EnumItems { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder - .UseSqlServer(SqlServerTestStore.CreateConnectionString(_databaseName), b => b.ApplyConfiguration()) - .UseInternalServiceProvider(_serviceProvider); + .UseSqlServer(SqlServerTestStore.CreateConnectionString(databaseName), b => b.ApplyConfiguration()) + .UseInternalServiceProvider(serviceProvider); protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity() @@ -134,13 +128,14 @@ public void Can_use_computed_columns_with_nullable_enum() Assert.Equal(FlagEnum.AValue | FlagEnum.BValue, entity.CalculatedFlagEnum); } - public ComputedColumnTest() - { - TestStore = SqlServerTestStore.CreateInitialized("ComputedColumnTest"); - } + protected SqlServerTestStore TestStore { get; private set; } - protected SqlServerTestStore TestStore { get; } + public async Task InitializeAsync() + => TestStore = await SqlServerTestStore.CreateInitializedAsync("ComputedColumnTest"); - public virtual void Dispose() - => TestStore.Dispose(); + public Task DisposeAsync() + { + TestStore.Dispose(); + return Task.CompletedTask; + } } diff --git a/test/EFCore.SqlServer.FunctionalTests/ConnectionSpecificationTest.cs b/test/EFCore.SqlServer.FunctionalTests/ConnectionSpecificationTest.cs index 1a9a90333d5..5e25523b0ef 100644 --- a/test/EFCore.SqlServer.FunctionalTests/ConnectionSpecificationTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/ConnectionSpecificationTest.cs @@ -15,45 +15,45 @@ namespace Microsoft.EntityFrameworkCore; public class ConnectionSpecificationTest { [ConditionalFact] - public void Can_specify_no_connection_string_in_OnConfiguring() + public async Task Can_specify_no_connection_string_in_OnConfiguring() { var serviceProvider = new ServiceCollection() .AddDbContext() .BuildServiceProvider(validateScopes: true); - using (SqlServerTestStore.GetNorthwindStore()) + using (await SqlServerTestStore.GetNorthwindStoreAsync()) { using var scope = serviceProvider.CreateScope(); var context = scope.ServiceProvider.GetRequiredService(); context.Database.SetConnectionString(SqlServerNorthwindTestStoreFactory.NorthwindConnectionString); - Assert.True(context.Customers.Any()); + Assert.True(await context.Customers.AnyAsync()); } } [ConditionalFact] - public void Can_specify_no_connection_string_in_OnConfiguring_with_default_service_provider() + public async Task Can_specify_no_connection_string_in_OnConfiguring_with_default_service_provider() { - using (SqlServerTestStore.GetNorthwindStore()) + using (await SqlServerTestStore.GetNorthwindStoreAsync()) { using var context = new NoneInOnConfiguringContext(); context.Database.SetConnectionString(SqlServerNorthwindTestStoreFactory.NorthwindConnectionString); - Assert.True(context.Customers.Any()); + Assert.True(await context.Customers.AnyAsync()); } } [ConditionalFact] - public void Throws_if_context_used_with_no_connection_or_connection_string() + public async Task Throws_if_context_used_with_no_connection_or_connection_string() { - using (SqlServerTestStore.GetNorthwindStore()) + using (await SqlServerTestStore.GetNorthwindStoreAsync()) { using var context = new NoneInOnConfiguringContext(); - Assert.Throws(() => context.Customers.Any()); + await Assert.ThrowsAsync(() => context.Customers.AnyAsync()); } } @@ -66,28 +66,28 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) } [ConditionalFact] - public void Can_specify_connection_string_in_OnConfiguring() + public async Task Can_specify_connection_string_in_OnConfiguring() { var serviceProvider = new ServiceCollection() .AddDbContext() .BuildServiceProvider(validateScopes: true); - using (SqlServerTestStore.GetNorthwindStore()) + using (await SqlServerTestStore.GetNorthwindStoreAsync()) { using var scope = serviceProvider.CreateScope(); var context = scope.ServiceProvider.GetRequiredService(); - Assert.True(context.Customers.Any()); + Assert.True(await context.Customers.AnyAsync()); } } [ConditionalFact] - public void Can_specify_connection_string_in_OnConfiguring_with_default_service_provider() + public async Task Can_specify_connection_string_in_OnConfiguring_with_default_service_provider() { - using (SqlServerTestStore.GetNorthwindStore()) + using (await SqlServerTestStore.GetNorthwindStoreAsync()) { using var context = new StringInOnConfiguringContext(); - Assert.True(context.Customers.Any()); + Assert.True(await context.Customers.AnyAsync()); } } @@ -102,7 +102,7 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) [ConditionalTheory] [InlineData(false)] [InlineData(true)] - public void Can_specify_no_connection_in_OnConfiguring(bool contextOwnsConnection) + public async Task Can_specify_no_connection_in_OnConfiguring(bool contextOwnsConnection) { var serviceProvider = new ServiceCollection() @@ -111,7 +111,7 @@ var serviceProvider SqlConnection connection; - using (SqlServerTestStore.GetNorthwindStore()) + using (await SqlServerTestStore.GetNorthwindStoreAsync()) { using var scope = serviceProvider.CreateScope(); var context = scope.ServiceProvider.GetRequiredService(); @@ -119,36 +119,36 @@ var serviceProvider connection = new SqlConnection(SqlServerNorthwindTestStoreFactory.NorthwindConnectionString); context.Database.SetDbConnection(connection, contextOwnsConnection); - Assert.True(context.Customers.Any()); + Assert.True(await context.Customers.AnyAsync()); } if (contextOwnsConnection) { - Assert.Throws(() => connection.Open()); // Disposed + await Assert.ThrowsAsync(() => connection.OpenAsync()); // Disposed } else { - connection.Open(); - connection.Close(); - connection.Dispose(); + await connection.OpenAsync(); + await connection.CloseAsync(); + await connection.DisposeAsync(); } } [ConditionalTheory] [InlineData(false)] [InlineData(true)] - public void Can_specify_no_connection_in_OnConfiguring_with_default_service_provider(bool contextOwnsConnection) + public async Task Can_specify_no_connection_in_OnConfiguring_with_default_service_provider(bool contextOwnsConnection) { SqlConnection connection; - using (SqlServerTestStore.GetNorthwindStore()) + using (await SqlServerTestStore.GetNorthwindStoreAsync()) { using var context = new NoneInOnConfiguringContext(); connection = new SqlConnection(SqlServerNorthwindTestStoreFactory.NorthwindConnectionString); context.Database.SetDbConnection(connection, contextOwnsConnection); - Assert.True(context.Customers.Any()); + Assert.True(await context.Customers.AnyAsync()); } if (contextOwnsConnection) @@ -164,35 +164,35 @@ public void Can_specify_no_connection_in_OnConfiguring_with_default_service_prov } [ConditionalFact] - public void Can_specify_connection_in_OnConfiguring() + public async Task Can_specify_connection_in_OnConfiguring() { var serviceProvider = new ServiceCollection() .AddScoped(p => new SqlConnection(SqlServerNorthwindTestStoreFactory.NorthwindConnectionString)) .AddDbContext().BuildServiceProvider(validateScopes: true); - using (SqlServerTestStore.GetNorthwindStore()) + using (await SqlServerTestStore.GetNorthwindStoreAsync()) { using var scope = serviceProvider.CreateScope(); var context = scope.ServiceProvider.GetRequiredService(); - Assert.True(context.Customers.Any()); + Assert.True(await context.Customers.AnyAsync()); } } [ConditionalFact] - public void Can_specify_connection_in_OnConfiguring_with_default_service_provider() + public async Task Can_specify_connection_in_OnConfiguring_with_default_service_provider() { - using (SqlServerTestStore.GetNorthwindStore()) + using (await SqlServerTestStore.GetNorthwindStoreAsync()) { using var connection = new SqlConnection(SqlServerNorthwindTestStoreFactory.NorthwindConnectionString); using var context = new ConnectionInOnConfiguringContext(connection); - Assert.True(context.Customers.Any()); + Assert.True(await context.Customers.AnyAsync()); } } [ConditionalFact] - public void Can_specify_owned_connection_in_OnConfiguring() + public async Task Can_specify_owned_connection_in_OnConfiguring() { var serviceProvider = new ServiceCollection() @@ -201,36 +201,36 @@ var serviceProvider SqlConnection connection; - using (SqlServerTestStore.GetNorthwindStore()) + using (await SqlServerTestStore.GetNorthwindStoreAsync()) { connection = serviceProvider.GetRequiredService(); using var scope = serviceProvider.CreateScope(); var context = scope.ServiceProvider.GetRequiredService(); - Assert.True(context.Customers.Any()); + Assert.True(await context.Customers.AnyAsync()); } Assert.Throws(() => connection.Open()); // Disposed } [ConditionalFact] - public void Can_specify_owned_connection_in_OnConfiguring_with_default_service_provider() + public async Task Can_specify_owned_connection_in_OnConfiguring_with_default_service_provider() { SqlConnection connection; - using (SqlServerTestStore.GetNorthwindStore()) + using (await SqlServerTestStore.GetNorthwindStoreAsync()) { connection = new SqlConnection(SqlServerNorthwindTestStoreFactory.NorthwindConnectionString); using var context = new OwnedConnectionInOnConfiguringContext(connection); - Assert.True(context.Customers.Any()); + Assert.True(await context.Customers.AnyAsync()); } Assert.Throws(() => connection.Open()); // Disposed } [ConditionalFact] - public void Can_specify_then_change_connection() + public async Task Can_specify_then_change_connection() { var connection = new SqlConnection(SqlServerNorthwindTestStoreFactory.NorthwindConnectionString); @@ -239,24 +239,24 @@ var serviceProvider .AddScoped(p => connection) .AddDbContext().BuildServiceProvider(validateScopes: true); - using (SqlServerTestStore.GetNorthwindStore()) + using (await SqlServerTestStore.GetNorthwindStoreAsync()) { using var scope = serviceProvider.CreateScope(); var context = scope.ServiceProvider.GetRequiredService(); Assert.Same(connection, context.Database.GetDbConnection()); - Assert.True(context.Customers.Any()); + Assert.True(await context.Customers.AnyAsync()); using var newConnection = new SqlConnection(SqlServerNorthwindTestStoreFactory.NorthwindConnectionString); context.Database.SetDbConnection(newConnection); Assert.Same(newConnection, context.Database.GetDbConnection()); - Assert.True(context.Customers.Any()); + Assert.True(await context.Customers.AnyAsync()); } } [ConditionalFact] - public void Cannot_change_connection_when_open_and_owned() + public async Task Cannot_change_connection_when_open_and_owned() { var connection = new SqlConnection(SqlServerNorthwindTestStoreFactory.NorthwindConnectionString); @@ -265,14 +265,14 @@ var serviceProvider .AddScoped(p => connection) .AddDbContext().BuildServiceProvider(validateScopes: true); - using (SqlServerTestStore.GetNorthwindStore()) + using (await SqlServerTestStore.GetNorthwindStoreAsync()) { using var scope = serviceProvider.CreateScope(); var context = scope.ServiceProvider.GetRequiredService(); context.Database.OpenConnection(); Assert.Same(connection, context.Database.GetDbConnection()); - Assert.True(context.Customers.Any()); + Assert.True(await context.Customers.AnyAsync()); using var newConnection = new SqlConnection(SqlServerNorthwindTestStoreFactory.NorthwindConnectionString); @@ -283,7 +283,7 @@ var serviceProvider } [ConditionalFact] - public void Can_change_connection_when_open_and_not_owned() + public async Task Can_change_connection_when_open_and_not_owned() { var connection = new SqlConnection(SqlServerNorthwindTestStoreFactory.NorthwindConnectionString); @@ -292,20 +292,20 @@ var serviceProvider .AddScoped(p => connection) .AddDbContext().BuildServiceProvider(validateScopes: true); - using (SqlServerTestStore.GetNorthwindStore()) + using (await SqlServerTestStore.GetNorthwindStoreAsync()) { using var scope = serviceProvider.CreateScope(); var context = scope.ServiceProvider.GetRequiredService(); context.Database.OpenConnection(); Assert.Same(connection, context.Database.GetDbConnection()); - Assert.True(context.Customers.Any()); + Assert.True(await context.Customers.AnyAsync()); using var newConnection = new SqlConnection(SqlServerNorthwindTestStoreFactory.NorthwindConnectionString); context.Database.SetDbConnection(newConnection); Assert.Same(newConnection, context.Database.GetDbConnection()); - Assert.True(context.Customers.Any()); + Assert.True(await context.Customers.AnyAsync()); } } @@ -336,7 +336,7 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) } [ConditionalFact] - public void Throws_if_no_connection_found_in_config_without_UseSqlServer() + public async Task Throws_if_no_connection_found_in_config_without_UseSqlServer() { var serviceProvider = new ServiceCollection() @@ -346,11 +346,11 @@ var serviceProvider var context = scope.ServiceProvider.GetRequiredService(); Assert.Equal( CoreStrings.NoProviderConfigured, - Assert.Throws(() => context.Customers.Any()).Message); + (await Assert.ThrowsAsync(() => context.Customers.AnyAsync())).Message); } [ConditionalFact] - public void Throws_if_no_config_without_UseSqlServer() + public async Task Throws_if_no_config_without_UseSqlServer() { var serviceProvider = new ServiceCollection() @@ -360,7 +360,7 @@ var serviceProvider var context = scope.ServiceProvider.GetRequiredService(); Assert.Equal( CoreStrings.NoProviderConfigured, - Assert.Throws(() => context.Customers.Any()).Message); + (await Assert.ThrowsAsync(() => context.Customers.AnyAsync())).Message); } private class NoUseSqlServerContext : NorthwindContextBase @@ -370,7 +370,7 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) } [ConditionalFact] - public void Can_depend_on_DbContextOptions() + public async Task Can_depend_on_DbContextOptions() { var serviceProvider = new ServiceCollection() @@ -378,18 +378,18 @@ var serviceProvider .AddDbContext() .BuildServiceProvider(validateScopes: true); - using (SqlServerTestStore.GetNorthwindStore()) + using (await SqlServerTestStore.GetNorthwindStoreAsync()) { using var scope = serviceProvider.CreateScope(); var context = scope.ServiceProvider.GetRequiredService(); - Assert.True(context.Customers.Any()); + Assert.True(await context.Customers.AnyAsync()); } } [ConditionalFact] - public void Can_depend_on_DbContextOptions_with_default_service_provider() + public async Task Can_depend_on_DbContextOptions_with_default_service_provider() { - using (SqlServerTestStore.GetNorthwindStore()) + using (await SqlServerTestStore.GetNorthwindStoreAsync()) { using var connection = new SqlConnection(SqlServerNorthwindTestStoreFactory.NorthwindConnectionString); @@ -397,7 +397,7 @@ public void Can_depend_on_DbContextOptions_with_default_service_provider() new DbContextOptions(), connection); - Assert.True(context.Customers.Any()); + Assert.True(await context.Customers.AnyAsync()); } } @@ -425,28 +425,28 @@ public override void Dispose() } [ConditionalFact] - public void Can_depend_on_non_generic_options_when_only_one_context() + public async Task Can_depend_on_non_generic_options_when_only_one_context() { var serviceProvider = new ServiceCollection() .AddDbContext() .BuildServiceProvider(validateScopes: true); - using (SqlServerTestStore.GetNorthwindStore()) + using (await SqlServerTestStore.GetNorthwindStoreAsync()) { using var scope = serviceProvider.CreateScope(); var context = scope.ServiceProvider.GetRequiredService(); - Assert.True(context.Customers.Any()); + Assert.True(await context.Customers.AnyAsync()); } } [ConditionalFact] - public void Can_depend_on_non_generic_options_when_only_one_context_with_default_service_provider() + public async Task Can_depend_on_non_generic_options_when_only_one_context_with_default_service_provider() { - using (SqlServerTestStore.GetNorthwindStore()) + using (await SqlServerTestStore.GetNorthwindStoreAsync()) { using var context = new NonGenericOptionsContext(new DbContextOptions()); - Assert.True(context.Customers.Any()); + Assert.True(await context.Customers.AnyAsync()); } } @@ -470,7 +470,7 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) [InlineData("MyConnectionString", "name=MyConnectionString")] [InlineData("ConnectionStrings:DefaultConnection", "name=ConnectionStrings:DefaultConnection")] [InlineData("ConnectionStrings:DefaultConnection", " NamE = ConnectionStrings:DefaultConnection ")] - public void Can_use_AddDbContext_and_get_connection_string_from_config(string key, string connectionString) + public async Task Can_use_AddDbContext_and_get_connection_string_from_config(string key, string connectionString) { var configBuilder = new ConfigurationBuilder() .AddInMemoryCollection( @@ -483,11 +483,11 @@ var serviceProvider b => b.UseSqlServer(connectionString).EnableServiceProviderCaching(false)) .BuildServiceProvider(validateScopes: true); - using (SqlServerTestStore.GetNorthwindStore()) + using (await SqlServerTestStore.GetNorthwindStoreAsync()) { using var serviceScope = serviceProvider.GetRequiredService().CreateScope(); using var context = serviceScope.ServiceProvider.GetRequiredService(); - Assert.True(context.Customers.Any()); + Assert.True(await context.Customers.AnyAsync()); } } @@ -535,7 +535,7 @@ public async Task Can_use_an_existing_closed_connection_test(bool openConnection .AddEntityFrameworkSqlServer() .BuildServiceProvider(validateScopes: true); - using var store = SqlServerTestStore.GetNorthwindStore(); + using var store = await SqlServerTestStore.GetNorthwindStoreAsync(); store.CloseConnection(); var openCount = 0; diff --git a/test/EFCore.SqlServer.FunctionalTests/ConvertToProviderTypesSqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/ConvertToProviderTypesSqlServerTest.cs index 475851b5ed0..1bca0ae908e 100644 --- a/test/EFCore.SqlServer.FunctionalTests/ConvertToProviderTypesSqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/ConvertToProviderTypesSqlServerTest.cs @@ -6,8 +6,9 @@ namespace Microsoft.EntityFrameworkCore; #nullable disable [SqlServerCondition(SqlServerCondition.IsNotSqlAzure)] -public class ConvertToProviderTypesSqlServerTest(ConvertToProviderTypesSqlServerTest.ConvertToProviderTypesSqlServerFixture fixture) : ConvertToProviderTypesTestBase< - ConvertToProviderTypesSqlServerTest.ConvertToProviderTypesSqlServerFixture>(fixture) +public class ConvertToProviderTypesSqlServerTest(ConvertToProviderTypesSqlServerTest.ConvertToProviderTypesSqlServerFixture fixture) + : ConvertToProviderTypesTestBase< + ConvertToProviderTypesSqlServerTest.ConvertToProviderTypesSqlServerFixture>(fixture) { [ConditionalFact] public virtual void Columns_have_expected_data_types() @@ -172,10 +173,9 @@ public virtual void Columns_have_expected_data_types() Assert.Equal(expected, actual, ignoreLineEndingDifferences: true); } - public override void Object_to_string_conversion() - { + public override Task Object_to_string_conversion() // Return values are not string - } + => Task.CompletedTask; public class ConvertToProviderTypesSqlServerFixture : ConvertToProviderTypesFixtureBase { diff --git a/test/EFCore.SqlServer.FunctionalTests/CustomConvertersSqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/CustomConvertersSqlServerTest.cs index b95f928323b..5b947a6643a 100644 --- a/test/EFCore.SqlServer.FunctionalTests/CustomConvertersSqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/CustomConvertersSqlServerTest.cs @@ -225,9 +225,9 @@ public virtual void Columns_have_expected_data_types() } [ConditionalFact] - public override void Value_conversion_is_appropriately_used_for_join_condition() + public override async Task Value_conversion_is_appropriately_used_for_join_condition() { - base.Value_conversion_is_appropriately_used_for_join_condition(); + await base.Value_conversion_is_appropriately_used_for_join_condition(); AssertSql( """ @@ -241,9 +241,9 @@ FROM [Blog] AS [b] } [ConditionalFact] - public override void Value_conversion_is_appropriately_used_for_left_join_condition() + public override async Task Value_conversion_is_appropriately_used_for_left_join_condition() { - base.Value_conversion_is_appropriately_used_for_left_join_condition(); + await base.Value_conversion_is_appropriately_used_for_left_join_condition(); AssertSql( """ @@ -257,9 +257,9 @@ FROM [Blog] AS [b] } [ConditionalFact] - public override void Where_bool_gets_converted_to_equality_when_value_conversion_is_used() + public override async Task Where_bool_gets_converted_to_equality_when_value_conversion_is_used() { - base.Where_bool_gets_converted_to_equality_when_value_conversion_is_used(); + await base.Where_bool_gets_converted_to_equality_when_value_conversion_is_used(); AssertSql( """ @@ -270,9 +270,9 @@ FROM [Blog] AS [b] } [ConditionalFact] - public override void Where_negated_bool_gets_converted_to_equality_when_value_conversion_is_used() + public override async Task Where_negated_bool_gets_converted_to_equality_when_value_conversion_is_used() { - base.Where_negated_bool_gets_converted_to_equality_when_value_conversion_is_used(); + await base.Where_negated_bool_gets_converted_to_equality_when_value_conversion_is_used(); AssertSql( """ @@ -282,9 +282,9 @@ FROM [Blog] AS [b] """); } - public override void Where_bool_gets_converted_to_equality_when_value_conversion_is_used_using_EFProperty() + public async override Task Where_bool_gets_converted_to_equality_when_value_conversion_is_used_using_EFProperty() { - base.Where_bool_gets_converted_to_equality_when_value_conversion_is_used_using_EFProperty(); + await base.Where_bool_gets_converted_to_equality_when_value_conversion_is_used_using_EFProperty(); AssertSql( """ @@ -294,9 +294,9 @@ FROM [Blog] AS [b] """); } - public override void Where_bool_gets_converted_to_equality_when_value_conversion_is_used_using_indexer() + public async override Task Where_bool_gets_converted_to_equality_when_value_conversion_is_used_using_indexer() { - base.Where_bool_gets_converted_to_equality_when_value_conversion_is_used_using_indexer(); + await base.Where_bool_gets_converted_to_equality_when_value_conversion_is_used_using_indexer(); AssertSql( """ @@ -306,14 +306,13 @@ FROM [Blog] AS [b] """); } - public override void Object_to_string_conversion() - { + public override Task Object_to_string_conversion() // Return values are not string - } + => Task.CompletedTask; - public override void Id_object_as_entity_key() + public async override Task Id_object_as_entity_key() { - base.Id_object_as_entity_key(); + await base.Id_object_as_entity_key(); AssertSql( """ diff --git a/test/EFCore.SqlServer.FunctionalTests/DataAnnotationSqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/DataAnnotationSqlServerTest.cs index 15aa4dbcb2b..9a174055591 100644 --- a/test/EFCore.SqlServer.FunctionalTests/DataAnnotationSqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/DataAnnotationSqlServerTest.cs @@ -203,9 +203,9 @@ public override IModel DatabaseGeneratedOption_Identity_does_not_throw_on_nonint return model; } - public override void ConcurrencyCheckAttribute_throws_if_value_in_database_changed() + public override async Task ConcurrencyCheckAttribute_throws_if_value_in_database_changed() { - base.ConcurrencyCheckAttribute_throws_if_value_in_database_changed(); + await base.ConcurrencyCheckAttribute_throws_if_value_in_database_changed(); AssertSql( """ @@ -247,9 +247,9 @@ OUTPUT 1 """); } - public override void DatabaseGeneratedAttribute_autogenerates_values_when_set_to_identity() + public override async Task DatabaseGeneratedAttribute_autogenerates_values_when_set_to_identity() { - base.DatabaseGeneratedAttribute_autogenerates_values_when_set_to_identity(); + await base.DatabaseGeneratedAttribute_autogenerates_values_when_set_to_identity(); AssertSql( """ @@ -269,9 +269,9 @@ OUTPUT INSERTED.[Unique_No] """); } - public override void MaxLengthAttribute_throws_while_inserting_value_longer_than_max_length() + public override async Task MaxLengthAttribute_throws_while_inserting_value_longer_than_max_length() { - base.MaxLengthAttribute_throws_while_inserting_value_longer_than_max_length(); + await base.MaxLengthAttribute_throws_while_inserting_value_longer_than_max_length(); AssertSql( """ @@ -307,9 +307,9 @@ OUTPUT INSERTED.[Unique_No] """); } - public override void StringLengthAttribute_throws_while_inserting_value_longer_than_max_length() + public override async Task StringLengthAttribute_throws_while_inserting_value_longer_than_max_length() { - base.StringLengthAttribute_throws_while_inserting_value_longer_than_max_length(); + await base.StringLengthAttribute_throws_while_inserting_value_longer_than_max_length(); AssertSql( """ @@ -333,13 +333,6 @@ INSERT INTO [Two] ([Data]) """); } - public override void TimestampAttribute_throws_if_value_in_database_changed() - => base.TimestampAttribute_throws_if_value_in_database_changed(); - - // Not validating SQL because not significantly different from other tests and - // row version value is not stable. - private static readonly string _eol = Environment.NewLine; - private void AssertSql(params string[] expected) => Fixture.TestSqlLoggerFactory.AssertBaseline(expected); diff --git a/test/EFCore.SqlServer.FunctionalTests/DefaultValuesTest.cs b/test/EFCore.SqlServer.FunctionalTests/DefaultValuesTest.cs index f6dd1789e21..ef03987f5b1 100644 --- a/test/EFCore.SqlServer.FunctionalTests/DefaultValuesTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/DefaultValuesTest.cs @@ -5,7 +5,7 @@ namespace Microsoft.EntityFrameworkCore; #nullable disable -public class DefaultValuesTest : IDisposable +public class DefaultValuesTest : IAsyncLifetime { private readonly IServiceProvider _serviceProvider = new ServiceCollection() .AddEntityFrameworkSqlServer() @@ -48,6 +48,7 @@ private class ChipsContext(IServiceProvider serviceProvider, string databaseName // ReSharper disable once UnusedAutoPropertyAccessor.Local public DbSet Chips { get; set; } + // ReSharper disable once UnusedAutoPropertyAccessor.Local public DbSet Chippers { get; set; } @@ -85,13 +86,14 @@ private class Chipper public string Id { get; set; } } - public DefaultValuesTest() - { - TestStore = SqlServerTestStore.CreateInitialized("DefaultValuesTest"); - } + protected SqlServerTestStore TestStore { get; private set; } - protected SqlServerTestStore TestStore { get; } + public async Task InitializeAsync() + => TestStore = await SqlServerTestStore.CreateInitializedAsync("DefaultValuesTest"); - public virtual void Dispose() - => TestStore.Dispose(); + public Task DisposeAsync() + { + TestStore.Dispose(); + return Task.CompletedTask; + } } diff --git a/test/EFCore.SqlServer.FunctionalTests/EntitySplittingSqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/EntitySplittingSqlServerTest.cs index dbe35c4ce22..f6b9d330c74 100644 --- a/test/EFCore.SqlServer.FunctionalTests/EntitySplittingSqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/EntitySplittingSqlServerTest.cs @@ -26,18 +26,15 @@ await InitializeAsync( }); }, sensitiveLogEnabled: false, - seed: c => - { - c.Database.ExecuteSqlRaw( - @" + seed: c => c.Database.ExecuteSqlRawAsync( + @" CREATE OR ALTER TRIGGER [MeterReadingsDetails_Trigger] ON [MeterReadingDetails] FOR INSERT, UPDATE, DELETE AS BEGIN IF @@ROWCOUNT = 0 return -END"); - }); +END")); await using (var context = CreateContext()) { diff --git a/test/EFCore.SqlServer.FunctionalTests/EverythingIsBytesSqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/EverythingIsBytesSqlServerTest.cs index 4cc12a0c240..4cdfbd4027e 100644 --- a/test/EFCore.SqlServer.FunctionalTests/EverythingIsBytesSqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/EverythingIsBytesSqlServerTest.cs @@ -9,7 +9,8 @@ namespace Microsoft.EntityFrameworkCore; #nullable disable [SqlServerCondition(SqlServerCondition.IsNotSqlAzure)] -public class EverythingIsBytesSqlServerTest(EverythingIsBytesSqlServerTest.EverythingIsBytesSqlServerFixture fixture) : BuiltInDataTypesTestBase(fixture) +public class EverythingIsBytesSqlServerTest(EverythingIsBytesSqlServerTest.EverythingIsBytesSqlServerFixture fixture) + : BuiltInDataTypesTestBase(fixture) { [ConditionalFact] public virtual void Columns_have_expected_data_types() @@ -172,30 +173,25 @@ public virtual void Columns_have_expected_data_types() Assert.Equal(expected, actual, ignoreLineEndingDifferences: true); } - public override void Can_read_back_mapped_enum_from_collection_first_or_default() - { + public override Task Can_read_back_mapped_enum_from_collection_first_or_default() // The query needs to generate TOP(1) - } + => Task.CompletedTask; - public override void Can_read_back_bool_mapped_as_int_through_navigation() - { + public override Task Can_read_back_bool_mapped_as_int_through_navigation() // Column is mapped as int rather than byte[] - } + => Task.CompletedTask; - public override void Object_to_string_conversion() - { + public override Task Object_to_string_conversion() // Return values are string which byte[] cannot read - } + => Task.CompletedTask; - public override void Can_compare_enum_to_constant() - { + public override Task Can_compare_enum_to_constant() // Column is mapped as int rather than byte[] - } + => Task.CompletedTask; - public override void Can_compare_enum_to_parameter() - { + public override Task Can_compare_enum_to_parameter() // Column is mapped as int rather than byte[] - } + => Task.CompletedTask; public class EverythingIsBytesSqlServerFixture : BuiltInDataTypesFixtureBase { diff --git a/test/EFCore.SqlServer.FunctionalTests/EverythingIsStringsSqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/EverythingIsStringsSqlServerTest.cs index 62ae891ab31..3edade4ed1b 100644 --- a/test/EFCore.SqlServer.FunctionalTests/EverythingIsStringsSqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/EverythingIsStringsSqlServerTest.cs @@ -9,8 +9,9 @@ namespace Microsoft.EntityFrameworkCore; #nullable disable [SqlServerCondition(SqlServerCondition.IsNotSqlAzure)] -public class EverythingIsStringsSqlServerTest(EverythingIsStringsSqlServerTest.EverythingIsStringsSqlServerFixture fixture) : BuiltInDataTypesTestBase< - EverythingIsStringsSqlServerTest.EverythingIsStringsSqlServerFixture>(fixture) +public class EverythingIsStringsSqlServerTest(EverythingIsStringsSqlServerTest.EverythingIsStringsSqlServerFixture fixture) + : BuiltInDataTypesTestBase< + EverythingIsStringsSqlServerTest.EverythingIsStringsSqlServerFixture>(fixture) { [ConditionalFact] public virtual void Columns_have_expected_data_types() @@ -173,25 +174,21 @@ public virtual void Columns_have_expected_data_types() Assert.Equal(expected, actual, ignoreLineEndingDifferences: true); } - public override void Can_read_back_mapped_enum_from_collection_first_or_default() - { + public override Task Can_read_back_mapped_enum_from_collection_first_or_default() // The query needs to generate TOP(1) - } + => Task.CompletedTask; - public override void Can_read_back_bool_mapped_as_int_through_navigation() - { + public override Task Can_read_back_bool_mapped_as_int_through_navigation() // Column is mapped as int rather than string - } + => Task.CompletedTask; - public override void Can_compare_enum_to_constant() - { + public override Task Can_compare_enum_to_constant() // Column is mapped as int rather than string - } + => Task.CompletedTask; - public override void Can_compare_enum_to_parameter() - { + public override Task Can_compare_enum_to_parameter() // Column is mapped as int rather than string - } + => Task.CompletedTask; public class EverythingIsStringsSqlServerFixture : BuiltInDataTypesFixtureBase { diff --git a/test/EFCore.SqlServer.FunctionalTests/GraphUpdates/GraphUpdatesSqlServerOwnedTest.cs b/test/EFCore.SqlServer.FunctionalTests/GraphUpdates/GraphUpdatesSqlServerOwnedTest.cs index 6c9039b3fd8..7ff86759731 100644 --- a/test/EFCore.SqlServer.FunctionalTests/GraphUpdates/GraphUpdatesSqlServerOwnedTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/GraphUpdates/GraphUpdatesSqlServerOwnedTest.cs @@ -5,7 +5,8 @@ namespace Microsoft.EntityFrameworkCore; #nullable disable -public class GraphUpdatesSqlServerOwnedTest(GraphUpdatesSqlServerOwnedTest.SqlServerFixture fixture) : GraphUpdatesSqlServerTestBase(fixture) +public class GraphUpdatesSqlServerOwnedTest(GraphUpdatesSqlServerOwnedTest.SqlServerFixture fixture) + : GraphUpdatesSqlServerTestBase(fixture) { // No owned types public override Task Update_root_by_collection_replacement_of_inserted_first_level(bool async) @@ -56,29 +57,25 @@ public override Task Shadow_skip_navigation_in_base_class_is_handled(bool async) => Task.CompletedTask; // Owned dependents are always loaded - public override void Required_one_to_one_are_cascade_deleted_in_store( + public override Task Required_one_to_one_are_cascade_deleted_in_store( CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) - { - } + => Task.CompletedTask; - public override void Required_one_to_one_with_alternate_key_are_cascade_deleted_in_store( + public override Task Required_one_to_one_with_alternate_key_are_cascade_deleted_in_store( CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) - { - } + => Task.CompletedTask; // No owned types public override Task Can_insert_when_composite_FK_has_default_value_for_one_part(bool async) => Task.CompletedTask; - public override void Required_one_to_one_relationships_are_one_to_one(CascadeTiming? deleteOrphansTiming) - { - } + public override Task Required_one_to_one_relationships_are_one_to_one(CascadeTiming? deleteOrphansTiming) + => Task.CompletedTask; - public override void Required_one_to_one_with_AK_relationships_are_one_to_one(CascadeTiming? deleteOrphansTiming) - { - } + public override Task Required_one_to_one_with_AK_relationships_are_one_to_one(CascadeTiming? deleteOrphansTiming) + => Task.CompletedTask; // No owned types public override Task Can_insert_when_bool_PK_in_composite_key_has_sentinel_value(bool async, bool initialValue) diff --git a/test/EFCore.SqlServer.FunctionalTests/GraphUpdates/ProxyGraphUpdatesSqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/GraphUpdates/ProxyGraphUpdatesSqlServerTest.cs index 3648601eed3..32749b0d4f4 100644 --- a/test/EFCore.SqlServer.FunctionalTests/GraphUpdates/ProxyGraphUpdatesSqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/GraphUpdates/ProxyGraphUpdatesSqlServerTest.cs @@ -28,7 +28,8 @@ protected override ITestStoreFactory TestStoreFactory } } - public class LazyLoading(LazyLoading.ProxyGraphUpdatesWithLazyLoadingSqlServerFixture fixture) : ProxyGraphUpdatesSqlServerTestBase(fixture) + public class LazyLoading(LazyLoading.ProxyGraphUpdatesWithLazyLoadingSqlServerFixture fixture) + : ProxyGraphUpdatesSqlServerTestBase(fixture) { protected override bool DoesLazyLoading => true; @@ -56,13 +57,12 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con } } - public class ChangeTracking(ChangeTracking.ProxyGraphUpdatesWithChangeTrackingSqlServerFixture fixture) : ProxyGraphUpdatesSqlServerTestBase(fixture) + public class ChangeTracking(ChangeTracking.ProxyGraphUpdatesWithChangeTrackingSqlServerFixture fixture) + : ProxyGraphUpdatesSqlServerTestBase(fixture) { - // Needs lazy loading - public override void Save_two_entity_cycle_with_lazy_loading() - { - } + public override Task Save_two_entity_cycle_with_lazy_loading() + => Task.CompletedTask; protected override bool DoesLazyLoading => false; @@ -90,8 +90,10 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con } } - public class ChangeTrackingAndLazyLoading(ChangeTrackingAndLazyLoading.ProxyGraphUpdatesWithChangeTrackingAndLazyLoadingSqlServerFixture fixture) : ProxyGraphUpdatesSqlServerTestBase< - ChangeTrackingAndLazyLoading.ProxyGraphUpdatesWithChangeTrackingAndLazyLoadingSqlServerFixture>(fixture) + public class ChangeTrackingAndLazyLoading( + ChangeTrackingAndLazyLoading.ProxyGraphUpdatesWithChangeTrackingAndLazyLoadingSqlServerFixture fixture) + : ProxyGraphUpdatesSqlServerTestBase< + ChangeTrackingAndLazyLoading.ProxyGraphUpdatesWithChangeTrackingAndLazyLoadingSqlServerFixture>(fixture) { protected override bool DoesLazyLoading => true; diff --git a/test/EFCore.SqlServer.FunctionalTests/JsonTypesSqlServerTestBase.cs b/test/EFCore.SqlServer.FunctionalTests/JsonTypesSqlServerTestBase.cs index 0ad439a391c..ec53cb56dc0 100644 --- a/test/EFCore.SqlServer.FunctionalTests/JsonTypesSqlServerTestBase.cs +++ b/test/EFCore.SqlServer.FunctionalTests/JsonTypesSqlServerTestBase.cs @@ -5,27 +5,27 @@ namespace Microsoft.EntityFrameworkCore; public abstract class JsonTypesSqlServerTestBase : JsonTypesRelationalTestBase { - public override void Can_read_write_ulong_enum_JSON_values(EnumU64 value, string json) + public override Task Can_read_write_ulong_enum_JSON_values(EnumU64 value, string json) { if (value == EnumU64.Max) { json = """{"Prop":-1}"""; // Because ulong is converted to long on SQL Server } - base.Can_read_write_ulong_enum_JSON_values(value, json); + return base.Can_read_write_ulong_enum_JSON_values(value, json); } - public override void Can_read_write_nullable_ulong_enum_JSON_values(object? value, string json) + public override Task Can_read_write_nullable_ulong_enum_JSON_values(object? value, string json) { if (Equals(value, ulong.MaxValue)) { json = """{"Prop":-1}"""; // Because ulong is converted to long on SQL Server } - base.Can_read_write_nullable_ulong_enum_JSON_values(value, json); + return base.Can_read_write_nullable_ulong_enum_JSON_values(value, json); } - public override void Can_read_write_collection_of_ulong_enum_JSON_values() + public override Task Can_read_write_collection_of_ulong_enum_JSON_values() => Can_read_and_write_JSON_value>( nameof(EnumU64CollectionType.EnumU64), [ @@ -38,7 +38,7 @@ public override void Can_read_write_collection_of_ulong_enum_JSON_values() """{"Prop":[0,-1,0,1,8]}""", // Because ulong is converted to long on SQL Server mappedCollection: true); - public override void Can_read_write_collection_of_nullable_ulong_enum_JSON_values() + public override Task Can_read_write_collection_of_nullable_ulong_enum_JSON_values() => Can_read_and_write_JSON_value>( nameof(NullableEnumU64CollectionType.EnumU64), [ @@ -52,14 +52,15 @@ public override void Can_read_write_collection_of_nullable_ulong_enum_JSON_value """{"Prop":[0,null,-1,0,1,8]}""", // Because ulong is converted to long on SQL Server mappedCollection: true); - public override void Can_read_write_collection_of_fixed_length_string_JSON_values(object? storeType) + public override Task Can_read_write_collection_of_fixed_length_string_JSON_values(object? storeType) => base.Can_read_write_collection_of_fixed_length_string_JSON_values("nchar(32)"); - public override void Can_read_write_collection_of_ASCII_string_JSON_values(object? storeType) + public override Task Can_read_write_collection_of_ASCII_string_JSON_values(object? storeType) => base.Can_read_write_collection_of_ASCII_string_JSON_values("varchar(max)"); - protected override ITestStoreFactory TestStoreFactory => SqlServerTestStoreFactory.Instance; + protected override ITestStoreFactory TestStoreFactory + => SqlServerTestStoreFactory.Instance; protected override DbContextOptionsBuilder AddOptions(DbContextOptionsBuilder builder) { diff --git a/test/EFCore.SqlServer.FunctionalTests/ManyToManyTrackingProxyGeneratedKeysSqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/ManyToManyTrackingProxyGeneratedKeysSqlServerTest.cs index 6faf1839344..b62e479db49 100644 --- a/test/EFCore.SqlServer.FunctionalTests/ManyToManyTrackingProxyGeneratedKeysSqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/ManyToManyTrackingProxyGeneratedKeysSqlServerTest.cs @@ -7,7 +7,8 @@ namespace Microsoft.EntityFrameworkCore; #nullable disable -public class ManyToManyTrackingProxyGeneratedKeysSqlServerTest(ManyToManyTrackingProxyGeneratedKeysSqlServerTest.ManyToManyTrackingProxyGeneratedKeysSqlServerFixture fixture) +public class ManyToManyTrackingProxyGeneratedKeysSqlServerTest( + ManyToManyTrackingProxyGeneratedKeysSqlServerTest.ManyToManyTrackingProxyGeneratedKeysSqlServerFixture fixture) : ManyToManyTrackingSqlServerTestBase< ManyToManyTrackingProxyGeneratedKeysSqlServerTest.ManyToManyTrackingProxyGeneratedKeysSqlServerFixture>(fixture) { @@ -15,24 +16,21 @@ public override Task Can_insert_many_to_many_shared_with_payload(bool async) // Mutable properties aren't proxyable on Dictionary => Task.CompletedTask; - public override void Can_update_many_to_many_shared_with_payload() - { + public override Task Can_update_many_to_many_shared_with_payload() // Mutable properties aren't proxyable on Dictionary - } + => Task.CompletedTask; - public override void Can_insert_update_delete_shared_type_entity_type() - { + public override Task Can_insert_update_delete_shared_type_entity_type() // Mutable properties aren't proxyable on Dictionary - } + => Task.CompletedTask; public override Task Can_insert_many_to_many_shared_with_payload_unidirectional(bool async) // Mutable properties aren't proxyable on Dictionary => Task.CompletedTask; - public override void Can_update_many_to_many_shared_with_payload_unidirectional() - { + public override Task Can_update_many_to_many_shared_with_payload_unidirectional() // Mutable properties aren't proxyable on Dictionary - } + => Task.CompletedTask; protected override bool RequiresDetectChanges => false; diff --git a/test/EFCore.SqlServer.FunctionalTests/ManyToManyTrackingProxySqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/ManyToManyTrackingProxySqlServerTest.cs index bd369c8d56c..fc6ed6a3681 100644 --- a/test/EFCore.SqlServer.FunctionalTests/ManyToManyTrackingProxySqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/ManyToManyTrackingProxySqlServerTest.cs @@ -28,24 +28,21 @@ public override Task Can_insert_many_to_many_shared_with_payload(bool async) // Mutable properties aren't proxyable on Dictionary => Task.CompletedTask; - public override void Can_update_many_to_many_shared_with_payload() - { + public override Task Can_update_many_to_many_shared_with_payload() // Mutable properties aren't proxyable on Dictionary - } + => Task.CompletedTask; - public override void Can_insert_update_delete_shared_type_entity_type() - { + public override Task Can_insert_update_delete_shared_type_entity_type() // Mutable properties aren't proxyable on Dictionary - } + => Task.CompletedTask; public override Task Can_insert_many_to_many_shared_with_payload_unidirectional(bool async) // Mutable properties aren't proxyable on Dictionary => Task.CompletedTask; - public override void Can_update_many_to_many_shared_with_payload_unidirectional() - { + public override Task Can_update_many_to_many_shared_with_payload_unidirectional() // Mutable properties aren't proxyable on Dictionary - } + => Task.CompletedTask; protected override bool RequiresDetectChanges => false; diff --git a/test/EFCore.SqlServer.FunctionalTests/MemoryOptimizedTablesTest.cs b/test/EFCore.SqlServer.FunctionalTests/MemoryOptimizedTablesTest.cs index 69942c63cc8..e834f928fba 100644 --- a/test/EFCore.SqlServer.FunctionalTests/MemoryOptimizedTablesTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/MemoryOptimizedTablesTest.cs @@ -11,41 +11,41 @@ namespace Microsoft.EntityFrameworkCore; #nullable disable [SqlServerCondition(SqlServerCondition.SupportsMemoryOptimized)] -public class MemoryOptimizedTablesTest(MemoryOptimizedTablesTest.MemoryOptimizedTablesFixture fixture) : IClassFixture +public class MemoryOptimizedTablesTest(MemoryOptimizedTablesTest.MemoryOptimizedTablesFixture fixture) + : IClassFixture { protected MemoryOptimizedTablesFixture Fixture { get; } = fixture; [ConditionalFact] - public void Can_create_memoryOptimized_table() + public async Task Can_create_memoryOptimized_table() { - using (CreateTestStore()) + using (await CreateTestStoreAsync()) { var bigUn = new BigUn(); var fastUns = new[] { new FastUn { Name = "First 'un", BigUn = bigUn }, new FastUn { Name = "Second 'un", BigUn = bigUn } }; using (var context = CreateContext()) { - context.Database.EnsureCreatedResiliently(); + await context.Database.EnsureCreatedResilientlyAsync(); // ReSharper disable once CoVariantArrayConversion context.AddRange(fastUns); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = CreateContext()) { - Assert.Equal(fastUns.Select(f => f.Name), context.FastUns.OrderBy(f => f.Name).Select(f => f.Name).ToList()); + Assert.Equal(fastUns.Select(f => f.Name), await context.FastUns.OrderBy(f => f.Name).Select(f => f.Name).ToListAsync()); } } } protected TestStore TestStore { get; set; } - protected TestStore CreateTestStore() + protected Task CreateTestStoreAsync() { TestStore = SqlServerTestStore.Create(nameof(MemoryOptimizedTablesTest)); - TestStore.Initialize(null, CreateContext, c => { }); - return TestStore; + return TestStore.InitializeAsync(null, CreateContext, _ => Task.CompletedTask); } private MemoryOptimizedContext CreateContext() diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/AdHocJsonQuerySqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/Query/AdHocJsonQuerySqlServerTest.cs index f0638ee931c..3f42c52b152 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/AdHocJsonQuerySqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/AdHocJsonQuerySqlServerTest.cs @@ -14,7 +14,7 @@ public class AdHocJsonQuerySqlServerTest : AdHocJsonQueryTestBase protected override ITestStoreFactory TestStoreFactory => SqlServerTestStoreFactory.Instance; - protected override void Seed29219(MyContext29219 ctx) + protected override async Task Seed29219(MyContext29219 ctx) { var entity1 = new MyEntity29219 { @@ -36,19 +36,19 @@ protected override void Seed29219(MyContext29219 ctx) }; ctx.Entities.AddRange(entity1, entity2); - ctx.SaveChanges(); + await ctx.SaveChangesAsync(); - ctx.Database.ExecuteSql( + await ctx.Database.ExecuteSqlAsync( $$""" INSERT INTO [Entities] ([Id], [Reference], [Collection]) VALUES(3, N'{ "NonNullableScalar" : 30 }', N'[{ "NonNullableScalar" : 10001 }]') """); } - protected override void Seed30028(MyContext30028 ctx) + protected override async Task Seed30028(MyContext30028 ctx) { // complete - ctx.Database.ExecuteSql( + await ctx.Database.ExecuteSqlAsync( $$$$""" INSERT INTO [Entities] ([Id], [Json]) VALUES( @@ -57,7 +57,7 @@ INSERT INTO [Entities] ([Id], [Json]) """); // missing collection - ctx.Database.ExecuteSql( + await ctx.Database.ExecuteSqlAsync( $$$$""" INSERT INTO [Entities] ([Id], [Json]) VALUES( @@ -66,7 +66,7 @@ INSERT INTO [Entities] ([Id], [Json]) """); // missing optional reference - ctx.Database.ExecuteSql( + await ctx.Database.ExecuteSqlAsync( $$$$""" INSERT INTO [Entities] ([Id], [Json]) VALUES( @@ -75,7 +75,7 @@ INSERT INTO [Entities] ([Id], [Json]) """); // missing required reference - ctx.Database.ExecuteSql( + await ctx.Database.ExecuteSqlAsync( $$$$""" INSERT INTO [Entities] ([Id], [Json]) VALUES( @@ -84,14 +84,14 @@ INSERT INTO [Entities] ([Id], [Json]) """); } - protected override void Seed33046(Context33046 ctx) - => ctx.Database.ExecuteSql( + protected override Task Seed33046(Context33046 ctx) + => ctx.Database.ExecuteSqlAsync( $$""" INSERT INTO [Reviews] ([Rounds], [Id]) VALUES(N'[{"RoundNumber":11,"SubRounds":[{"SubRoundNumber":111},{"SubRoundNumber":112}]}]', 1) """); - protected override void SeedArrayOfPrimitives(MyContextArrayOfPrimitives ctx) + protected override Task SeedArrayOfPrimitives(MyContextArrayOfPrimitives ctx) { var entity1 = new MyEntityArrayOfPrimitives { @@ -134,11 +134,11 @@ protected override void SeedArrayOfPrimitives(MyContextArrayOfPrimitives ctx) }; ctx.Entities.AddRange(entity1, entity2); - ctx.SaveChanges(); + return ctx.SaveChangesAsync(); } - protected override void SeedJunkInJson(MyContextJunkInJson ctx) - => ctx.Database.ExecuteSql( + protected override Task SeedJunkInJson(MyContextJunkInJson ctx) + => ctx.Database.ExecuteSqlAsync( $$$$""" INSERT INTO [Entities] ([Collection], [CollectionWithCtor], [Reference], [ReferenceWithCtor], [Id]) VALUES( @@ -149,16 +149,16 @@ INSERT INTO [Entities] ([Collection], [CollectionWithCtor], [Reference], [Refere 1) """); - protected override void SeedTrickyBuffering(MyContextTrickyBuffering ctx) - => ctx.Database.ExecuteSql( + protected override Task SeedTrickyBuffering(MyContextTrickyBuffering ctx) + => ctx.Database.ExecuteSqlAsync( $$$""" INSERT INTO [Entities] ([Reference], [Id]) VALUES( N'{"Name": "r1", "Number": 7, "JunkReference":{"Something": "SomeValue" }, "JunkCollection": [{"Foo": "junk value"}], "NestedReference": {"DoB": "2000-01-01T00:00:00"}, "NestedCollection": [{"DoB": "2000-02-01T00:00:00", "JunkReference": {"Something": "SomeValue"}}, {"DoB": "2000-02-02T00:00:00"}]}',1) """); - protected override void SeedShadowProperties(MyContextShadowProperties ctx) - => ctx.Database.ExecuteSql( + protected override Task SeedShadowProperties(MyContextShadowProperties ctx) + => ctx.Database.ExecuteSqlAsync( $$""" INSERT INTO [Entities] ([Collection], [CollectionWithCtor], [Reference], [ReferenceWithCtor], [Id], [Name]) VALUES( @@ -170,9 +170,9 @@ INSERT INTO [Entities] ([Collection], [CollectionWithCtor], [Reference], [Refere N'e1') """); - protected override void SeedNotICollection(MyContextNotICollection ctx) + protected override async Task SeedNotICollection(MyContextNotICollection ctx) { - ctx.Database.ExecuteSql( + await ctx.Database.ExecuteSqlAsync( $$""" INSERT INTO [Entities] ([Json], [Id]) VALUES( @@ -180,7 +180,7 @@ INSERT INTO [Entities] ([Json], [Id]) 1) """); - ctx.Database.ExecuteSql( + await ctx.Database.ExecuteSqlAsync( $$$""" INSERT INTO [Entities] ([Json], [Id]) VALUES( @@ -302,8 +302,8 @@ public virtual async Task Read_json_entity_collection_with_enum_properties_with_ l => l.Message == CoreResources.LogStringEnumValueInJson(testLogger).GenerateMessage(nameof(ULongEnumLegacyValues)))); } - private void SeedEnumLegacyValues(MyContextEnumLegacyValues ctx) - => ctx.Database.ExecuteSql( + private Task SeedEnumLegacyValues(MyContextEnumLegacyValues ctx) + => ctx.Database.ExecuteSqlAsync( $$""" INSERT INTO [Entities] ([Collection], [Reference], [Id], [Name]) VALUES( diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/AdHocMiscellaneousQuerySqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/Query/AdHocMiscellaneousQuerySqlServerTest.cs index dba0dad08ab..7dbdedb982d 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/AdHocMiscellaneousQuerySqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/AdHocMiscellaneousQuerySqlServerTest.cs @@ -19,14 +19,12 @@ public class AdHocMiscellaneousQuerySqlServerTest : AdHocMiscellaneousQueryRelat protected override ITestStoreFactory TestStoreFactory => SqlServerTestStoreFactory.Instance; - protected override void Seed2951(Context2951 context) - { - context.Database.ExecuteSqlRaw( -""" + protected override Task Seed2951(Context2951 context) + => context.Database.ExecuteSqlRawAsync( + """ CREATE TABLE ZeroKey (Id int); INSERT ZeroKey VALUES (NULL) """); - } #region 5456 @@ -34,8 +32,8 @@ INSERT ZeroKey VALUES (NULL) public virtual async Task Include_group_join_is_per_query_context() { var contextFactory = await InitializeAsync( - seed: c => c.Seed(), - createTestStore: () => SqlServerTestStore.CreateInitialized(StoreName, multipleActiveResultSets: true)); + seed: c => c.SeedAsync(), + createTestStore: async () => await SqlServerTestStore.CreateInitializedAsync(StoreName, multipleActiveResultSets: true)); Parallel.For( 0, 10, i => @@ -69,8 +67,8 @@ public virtual async Task Include_group_join_is_per_query_context() public virtual async Task Include_group_join_is_per_query_context_async() { var contextFactory = await InitializeAsync( - seed: c => c.Seed(), - createTestStore: () => SqlServerTestStore.CreateInitialized(StoreName, multipleActiveResultSets: true)); + seed: c => c.SeedAsync(), + createTestStore: async () => await SqlServerTestStore.CreateInitializedAsync(StoreName, multipleActiveResultSets: true)); await Parallel.ForAsync( 0, 10, async (i, ct) => @@ -109,19 +107,15 @@ private class Context5456(DbContextOptions options) : DbContext(options) public DbSet Comments { get; set; } public DbSet Authors { get; set; } - public void Seed() + public Task SeedAsync() { for (var i = 0; i < 100; i++) { Add( - new Blog - { - Posts = [new() { Comments = [new(), new()] }, new()], - Author = new Author() - }); + new Blog { Posts = [new() { Comments = [new(), new()] }, new()], Author = new Author() }); } - SaveChanges(); + return SaveChangesAsync(); } public class Blog @@ -158,7 +152,7 @@ public class Comment [ConditionalFact] public virtual async Task Select_nested_projection() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using (var context = contextFactory.CreateContext()) { @@ -175,20 +169,20 @@ public virtual async Task Select_nested_projection() } AssertSql( -""" + """ SELECT [c].[Id], [c].[Name] FROM [Customers] AS [c] """, - // - """ + // + """ @__id_0='1' SELECT TOP(2) [c].[Id], [c].[Name] FROM [Customers] AS [c] WHERE [c].[Id] = @__id_0 """, - // - """ + // + """ @__id_0='2' SELECT TOP(2) [c].[Id], [c].[Name] @@ -201,13 +195,13 @@ private class Context8864(DbContextOptions options) : DbContext(options) { public DbSet Customers { get; set; } - public void Seed() + public Task SeedAsync() { AddRange( new Customer { Name = "Alan" }, new Customer { Name = "Elon" }); - SaveChanges(); + return SaveChangesAsync(); } public static Customer Get(Context8864 context, int id) @@ -227,7 +221,7 @@ public class Customer [ConditionalFact] public async Task Default_schema_applied_when_no_function_schema() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using (var context = contextFactory.CreateContext()) { @@ -283,16 +277,16 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) modelBuilder.HasDbFunction(typeof(Context9214).GetMethod(nameof(AddTwo))).HasSchema("dbo"); } - public void Seed() + public async Task SeedAsync() { var w1 = new Widget9214 { Val = 1 }; var w2 = new Widget9214 { Val = 2 }; var w3 = new Widget9214 { Val = 3 }; Widgets.AddRange(w1, w2, w3); - SaveChanges(); + await SaveChangesAsync(); - Database.ExecuteSqlRaw( -""" + await Database.ExecuteSqlRawAsync( + """ CREATE FUNCTION foo.AddOne (@num int) RETURNS int AS @@ -302,8 +296,8 @@ RETURNS int """); - Database.ExecuteSqlRaw( -""" + await Database.ExecuteSqlRawAsync( + """ CREATE FUNCTION dbo.AddTwo (@num int) RETURNS int AS @@ -327,7 +321,7 @@ public class Widget9214 [ConditionalFact] public virtual async Task From_sql_gets_value_of_out_parameter_in_stored_procedure() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using (var context = contextFactory.CreateContext()) { @@ -356,10 +350,10 @@ protected class Context9277(DbContextOptions options) : DbContext(options) { public DbSet Blogs { get; set; } - public void Seed() + public async Task SeedAsync() { - Database.ExecuteSqlRaw( -""" + await Database.ExecuteSqlRawAsync( + """ CREATE PROCEDURE [dbo].[GetPersonAndVoteCount] ( @id int, @@ -382,7 +376,7 @@ FROM dbo.Blogs new Blog9277 { SomeValue = 3 } ); - SaveChanges(); + await SaveChangesAsync(); } public class Blog9277 @@ -456,12 +450,12 @@ public class BaseEntity [ConditionalFact] public virtual async Task Projecting_entity_with_value_converter_and_include_works() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var result = context.Parents.Include(p => p.Child).OrderBy(e => e.Id).FirstOrDefault(); AssertSql( -""" + """ SELECT TOP(1) [p].[Id], [p].[ChildId], [c].[Id], [c].[ParentId], [c].[ULongRowVersion] FROM [Parents] AS [p] LEFT JOIN [Children] AS [c] ON [p].[ChildId] = [c].[Id] @@ -472,12 +466,12 @@ ORDER BY [p].[Id] [ConditionalFact] public virtual async Task Projecting_column_with_value_converter_of_ulong_byte_array() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var result = context.Parents.OrderBy(e => e.Id).Select(p => (ulong?)p.Child.ULongRowVersion).FirstOrDefault(); AssertSql( -""" + """ SELECT TOP(1) [c].[ULongRowVersion] FROM [Parents] AS [p] LEFT JOIN [Children] AS [c] ON [p].[ChildId] = [c].[Id] @@ -505,10 +499,10 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) modelBuilder.Entity(); } - public void Seed() + public Task SeedAsync() { Parents.Add(new Parent12518()); - SaveChanges(); + return SaveChangesAsync(); } public class Parent12518 @@ -534,7 +528,7 @@ public class Child12518 [ConditionalFact] public virtual async Task DateTime_Contains_with_smalldatetime_generates_correct_literal() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var testDateList = new List { new(2018, 10, 07) }; var findRecordsWithDateInList = context.ReproEntity @@ -544,7 +538,7 @@ public virtual async Task DateTime_Contains_with_smalldatetime_generates_correct Assert.Single(findRecordsWithDateInList); AssertSql( -""" + """ @__testDateList_0='["2018-10-07T00:00:00"]' (Size = 4000) SELECT [r].[Id], [r].[MyTime] @@ -563,13 +557,13 @@ private class Context13118(DbContextOptions options) : DbContext(options) protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity(e => e.Property("MyTime").HasColumnType("smalldatetime")); - public void Seed() + public Task SeedAsync() { AddRange( new ReproEntity13118 { MyTime = new DateTime(2018, 10, 07) }, new ReproEntity13118 { MyTime = new DateTime(2018, 10, 08) }); - SaveChanges(); + return SaveChangesAsync(); } } @@ -588,7 +582,7 @@ private class ReproEntity13118 [InlineData(true)] public async Task Where_equals_DateTime_Now(bool async) { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var query = context.Dates.Where( @@ -616,7 +610,7 @@ FROM [Dates] AS [d] [InlineData(true)] public async Task Where_not_equals_DateTime_Now(bool async) { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var query = context.Dates.Where( @@ -644,7 +638,7 @@ FROM [Dates] AS [d] [InlineData(true)] public async Task Where_equals_new_DateTime(bool async) { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var query = context.Dates.Where( @@ -694,7 +688,7 @@ public async Task Where_contains_DateTime_literals(bool async) new DateTime(1980, 9, 3, 12, 0, 10, 222) }; - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var query = context.Dates.Where( @@ -773,7 +767,7 @@ protected class Context14095(DbContextOptions options) : DbContext(options) { public DbSet Dates { get; set; } - public void Seed() + public Task SeedAsync() { Add( new DatesAndPrunes14095 @@ -790,7 +784,7 @@ public void Seed() DateTime2_6 = new DateTime(1979, 9, 3, 12, 0, 10, 111), DateTime2_7 = new DateTime(1980, 9, 3, 12, 0, 10, 222) }); - SaveChanges(); + return SaveChangesAsync(); } public class DatesAndPrunes14095 @@ -841,7 +835,7 @@ public class DatesAndPrunes14095 [InlineData(true)] public virtual async Task Nested_queries_does_not_cause_concurrency_exception_sync(bool tracking) { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using (var context = contextFactory.CreateContext()) { @@ -870,42 +864,42 @@ public virtual async Task Nested_queries_does_not_cause_concurrency_exception_sy } AssertSql( -""" + """ SELECT [r].[Id], [r].[Name] FROM [Repos] AS [r] WHERE [r].[Id] > 0 ORDER BY [r].[Id] """, - // - """ + // + """ SELECT [r].[Id], [r].[Name] FROM [Repos] AS [r] WHERE [r].[Id] > 0 ORDER BY [r].[Id] """, - // - """ + // + """ SELECT [r].[Id], [r].[Name] FROM [Repos] AS [r] WHERE [r].[Id] > 0 ORDER BY [r].[Id] """, - // - """ + // + """ SELECT [r].[Id], [r].[Name] FROM [Repos] AS [r] WHERE [r].[Id] > 0 ORDER BY [r].[Id] """, - // - """ + // + """ SELECT [r].[Id], [r].[Name] FROM [Repos] AS [r] WHERE [r].[Id] > 0 ORDER BY [r].[Id] """, - // - """ + // + """ SELECT [r].[Id], [r].[Name] FROM [Repos] AS [r] WHERE [r].[Id] > 0 @@ -917,13 +911,13 @@ private class Context15518(DbContextOptions options) : DbContext(options) { public DbSet Repos { get; set; } - public void Seed() + public Task SeedAsync() { AddRange( new Repo { Name = "London" }, new Repo { Name = "New York" }); - SaveChanges(); + return SaveChangesAsync(); } public class Repo @@ -940,7 +934,7 @@ public class Repo [ConditionalFact] public virtual async Task From_sql_expression_compares_correctly() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using (var context = contextFactory.CreateContext()) { @@ -957,7 +951,7 @@ from t2 in context.Tests.FromSqlInterpolated( Assert.Equal(Context19206.TestType19206.Integration, item.t2.Type); AssertSql( -""" + """ p0='0' p1='1' @@ -980,11 +974,11 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) { } - public void Seed() + public Task SeedAsync() { Add(new Test { Type = TestType19206.Unit }); Add(new Test { Type = TestType19206.Integration }); - SaveChanges(); + return SaveChangesAsync(); } public class Test @@ -1048,7 +1042,7 @@ public class List public virtual async Task Can_query_point_with_buffered_data_reader() { var contextFactory = await InitializeAsync( - seed: c => c.Seed(), + seed: c => c.SeedAsync(), onConfiguring: o => new SqlServerDbContextOptionsBuilder(o).UseNetTopologySuite(), addServices: c => c.AddEntityFrameworkSqlServerNetTopologySuite()); @@ -1058,7 +1052,7 @@ public virtual async Task Can_query_point_with_buffered_data_reader() Assert.NotNull(testUser); AssertSql( -""" + """ SELECT TOP(1) [l].[Id], [l].[Name], [l].[Address_County], [l].[Address_Line1], [l].[Address_Line2], [l].[Address_Point], [l].[Address_Postcode], [l].[Address_Town], [l].[Address_Value] FROM [Locations] AS [l] WHERE [l].[Name] = N'My Location' @@ -1069,7 +1063,7 @@ private class Context23282(DbContextOptions options) : DbContext(options) { public DbSet Locations { get; set; } - public void Seed() + public Task SeedAsync() { Locations.Add( new Location @@ -1084,7 +1078,7 @@ public void Seed() Point = new Point(115.7930, 37.2431) { SRID = 4326 } } }); - SaveChanges(); + return SaveChangesAsync(); } [Owned] @@ -1122,7 +1116,7 @@ public virtual async Task Subquery_take_SelectMany_with_TVF() using var context = contextFactory.CreateContext(); context.Database.ExecuteSqlRaw( -""" + """ create function [dbo].[GetPersonStatusAsOf] (@personId bigint, @timestamp datetime2) returns @personStatus table ( @@ -1281,7 +1275,7 @@ protected class DemoEntity [MemberData(nameof(IsAsyncData))] public virtual async Task TemporalAsOf_with_json_basic_query(bool async) { - var contextFactory = await InitializeAsync(seed: x => x.Seed()); + var contextFactory = await InitializeAsync(seed: x => x.SeedAsync()); using var context = contextFactory.CreateContext(); var query = context.Entities.TemporalAsOf(new DateTime(2010, 1, 1)); @@ -1304,7 +1298,7 @@ public virtual async Task TemporalAsOf_with_json_basic_query(bool async) [MemberData(nameof(IsAsyncData))] public virtual async Task TemporalAll_with_json_basic_query(bool async) { - var contextFactory = await InitializeAsync(seed: x => x.Seed()); + var contextFactory = await InitializeAsync(seed: x => x.SeedAsync()); using var context = contextFactory.CreateContext(); var query = context.Entities.TemporalAll(); @@ -1327,7 +1321,7 @@ FROM [Entities] FOR SYSTEM_TIME ALL AS [e] [MemberData(nameof(IsAsyncData))] public virtual async Task TemporalAsOf_project_json_entity_reference(bool async) { - var contextFactory = await InitializeAsync(seed: x => x.Seed()); + var contextFactory = await InitializeAsync(seed: x => x.SeedAsync()); using var context = contextFactory.CreateContext(); var query = context.Entities.TemporalAsOf(new DateTime(2010, 1, 1)).Select(x => x.Reference); @@ -1349,7 +1343,7 @@ public virtual async Task TemporalAsOf_project_json_entity_reference(bool async) [MemberData(nameof(IsAsyncData))] public virtual async Task TemporalAsOf_project_json_entity_collection(bool async) { - var contextFactory = await InitializeAsync(seed: x => x.Seed()); + var contextFactory = await InitializeAsync(seed: x => x.SeedAsync()); using var context = contextFactory.CreateContext(); var query = context.Entities.TemporalAsOf(new DateTime(2010, 1, 1)).Select(x => x.Collection); @@ -1375,30 +1369,28 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity().Property(x => x.Id).ValueGeneratedNever(); modelBuilder.Entity().ToTable("Entities", tb => tb.IsTemporal()); - modelBuilder.Entity().OwnsOne(x => x.Reference, nb => - { - nb.ToJson(); - nb.OwnsOne(x => x.Nested); - }); + modelBuilder.Entity().OwnsOne( + x => x.Reference, nb => + { + nb.ToJson(); + nb.OwnsOne(x => x.Nested); + }); - modelBuilder.Entity().OwnsMany(x => x.Collection, nb => - { - nb.ToJson(); - nb.OwnsOne(x => x.Nested); - }); + modelBuilder.Entity().OwnsMany( + x => x.Collection, nb => + { + nb.ToJson(); + nb.OwnsOne(x => x.Nested); + }); } - public void Seed() + public async Task SeedAsync() { var e1 = new Entity30478 { Id = 1, Name = "e1", - Reference = new Json30478 - { - Name = "r1", - Nested = new JsonNested30478 { Number = 1 } - }, + Reference = new Json30478 { Name = "r1", Nested = new JsonNested30478 { Number = 1 } }, Collection = [ new Json30478 { Name = "c11", Nested = new JsonNested30478 { Number = 11 } }, @@ -1413,11 +1405,7 @@ public void Seed() { Id = 2, Name = "e2", - Reference = new Json30478 - { - Name = "r2", - Nested = new JsonNested30478 { Number = 2 } - }, + Reference = new Json30478 { Name = "r2", Nested = new JsonNested30478 { Number = 2 } }, Collection = [ new Json30478 { Name = "c21", Nested = new JsonNested30478 { Number = 21 } }, @@ -1428,20 +1416,21 @@ public void Seed() }; AddRange(e1, e2); - SaveChanges(); + await SaveChangesAsync(); RemoveRange(e1, e2); - SaveChanges(); + await SaveChangesAsync(); - Database.ExecuteSqlRaw($"ALTER TABLE [Entities] SET (SYSTEM_VERSIONING = OFF)"); - Database.ExecuteSqlRaw($"ALTER TABLE [Entities] DROP PERIOD FOR SYSTEM_TIME"); + await Database.ExecuteSqlRawAsync("ALTER TABLE [Entities] SET (SYSTEM_VERSIONING = OFF)"); + await Database.ExecuteSqlRawAsync("ALTER TABLE [Entities] DROP PERIOD FOR SYSTEM_TIME"); - Database.ExecuteSqlRaw($"UPDATE [EntitiesHistory] SET PeriodStart = '2000-01-01T01:00:00.0000000Z'"); - Database.ExecuteSqlRaw($"UPDATE [EntitiesHistory] SET PeriodEnd = '2020-07-01T07:00:00.0000000Z'"); + await Database.ExecuteSqlRawAsync("UPDATE [EntitiesHistory] SET PeriodStart = '2000-01-01T01:00:00.0000000Z'"); + await Database.ExecuteSqlRawAsync("UPDATE [EntitiesHistory] SET PeriodEnd = '2020-07-01T07:00:00.0000000Z'"); - Database.ExecuteSqlRaw($"ALTER TABLE [Entities] ADD PERIOD FOR SYSTEM_TIME ([PeriodStart], [PeriodEnd])"); - Database.ExecuteSqlRaw($"ALTER TABLE [Entities] SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = [dbo].[EntitiesHistory]))"); + await Database.ExecuteSqlRawAsync("ALTER TABLE [Entities] ADD PERIOD FOR SYSTEM_TIME ([PeriodStart], [PeriodEnd])"); + await Database.ExecuteSqlRawAsync( + "ALTER TABLE [Entities] SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = [dbo].[EntitiesHistory]))"); } } @@ -1471,13 +1460,13 @@ public override async Task First_FirstOrDefault_ix_async() await base.First_FirstOrDefault_ix_async(); AssertSql( -""" + """ SELECT TOP(1) [p].[Id], [p].[Name] FROM [Products] AS [p] ORDER BY [p].[Id] """, - // - """ + // + """ @p0='1' SET IMPLICIT_TRANSACTIONS OFF; @@ -1486,8 +1475,8 @@ DELETE FROM [Products] OUTPUT 1 WHERE [Id] = @p0; """, - // - """ + // + """ @p0='Product 1' (Size = 4000) SET IMPLICIT_TRANSACTIONS OFF; @@ -1496,14 +1485,14 @@ INSERT INTO [Products] ([Name]) OUTPUT INSERTED.[Id] VALUES (@p0); """, - // - """ + // + """ SELECT TOP(1) [p].[Id], [p].[Name] FROM [Products] AS [p] ORDER BY [p].[Id] """, - // - """ + // + """ @p0='2' SET IMPLICIT_TRANSACTIONS OFF; @@ -1519,13 +1508,13 @@ public override async Task Discriminator_type_is_handled_correctly() await base.Discriminator_type_is_handled_correctly(); AssertSql( -""" + """ SELECT [p].[Id], [p].[Discriminator], [p].[Name] FROM [Products] AS [p] WHERE [p].[Discriminator] = 1 """, - // - """ + // + """ SELECT [p].[Id], [p].[Discriminator], [p].[Name] FROM [Products] AS [p] WHERE [p].[Discriminator] = 1 @@ -1548,13 +1537,13 @@ public override async Task Enum_has_flag_applies_explicit_cast_for_constant() await base.Enum_has_flag_applies_explicit_cast_for_constant(); AssertSql( -""" + """ SELECT [e].[Id], [e].[Permission], [e].[PermissionByte], [e].[PermissionShort] FROM [Entities] AS [e] WHERE [e].[Permission] & CAST(17179869184 AS bigint) = CAST(17179869184 AS bigint) """, - // - """ + // + """ SELECT [e].[Id], [e].[Permission], [e].[PermissionByte], [e].[PermissionShort] FROM [Entities] AS [e] WHERE [e].[PermissionShort] & CAST(4 AS smallint) = CAST(4 AS smallint) @@ -1566,13 +1555,13 @@ public override async Task Enum_has_flag_does_not_apply_explicit_cast_for_non_co await base.Enum_has_flag_does_not_apply_explicit_cast_for_non_constant(); AssertSql( -""" + """ SELECT [e].[Id], [e].[Permission], [e].[PermissionByte], [e].[PermissionShort] FROM [Entities] AS [e] WHERE [e].[Permission] & [e].[Permission] = [e].[Permission] """, - // - """ + // + """ SELECT [e].[Id], [e].[Permission], [e].[PermissionByte], [e].[PermissionShort] FROM [Entities] AS [e] WHERE [e].[PermissionByte] & [e].[PermissionByte] = [e].[PermissionByte] @@ -1584,39 +1573,39 @@ public override async Task Variable_from_closure_is_parametrized() await base.Variable_from_closure_is_parametrized(); AssertSql( -""" + """ @__id_0='1' SELECT [e].[Id], [e].[Name] FROM [Entities] AS [e] WHERE [e].[Id] = @__id_0 """, - // - """ + // + """ @__id_0='2' SELECT [e].[Id], [e].[Name] FROM [Entities] AS [e] WHERE [e].[Id] = @__id_0 """, - // - """ + // + """ @__id_0='1' SELECT [e].[Id], [e].[Name] FROM [Entities] AS [e] WHERE [e].[Id] = @__id_0 """, - // - """ + // + """ @__id_0='2' SELECT [e].[Id], [e].[Name] FROM [Entities] AS [e] WHERE [e].[Id] = @__id_0 """, - // - """ + // + """ @__id_0='1' SELECT [e].[Id], [e].[Name] @@ -1627,8 +1616,8 @@ FROM [Entities] AS [e0] WHERE [e0].[Id] = @__id_0 ) """, - // - """ + // + """ @__id_0='2' SELECT [e].[Id], [e].[Name] @@ -1646,15 +1635,15 @@ public override async Task Relational_command_cache_creates_new_entry_when_param await base.Relational_command_cache_creates_new_entry_when_parameter_nullability_changes(); AssertSql( -""" + """ @__name_0='A' (Size = 4000) SELECT [e].[Id], [e].[Name] FROM [Entities] AS [e] WHERE [e].[Name] = @__name_0 """, - // - """ + // + """ SELECT [e].[Id], [e].[Name] FROM [Entities] AS [e] WHERE [e].[Name] IS NULL @@ -1673,7 +1662,7 @@ public override async Task Explicitly_compiled_query_does_not_add_cache_entry() await base.Explicitly_compiled_query_does_not_add_cache_entry(); AssertSql( -""" + """ SELECT TOP(2) [e].[Id], [e].[Name] FROM [Entities] AS [e] WHERE [e].[Id] = 1 @@ -1685,7 +1674,7 @@ public override async Task Conditional_expression_with_conditions_does_not_colla await base.Conditional_expression_with_conditions_does_not_collapse_if_nullable_bool(); AssertSql( -""" + """ SELECT CASE WHEN [c0].[Id] IS NOT NULL THEN CASE WHEN [c0].[Processed] = CAST(0 AS bit) THEN CAST(1 AS bit) @@ -1714,62 +1703,62 @@ public override async Task Average_with_cast() await base.Average_with_cast(); AssertSql( -""" + """ SELECT [p].[Id], [p].[DecimalColumn], [p].[DoubleColumn], [p].[FloatColumn], [p].[IntColumn], [p].[LongColumn], [p].[NullableDecimalColumn], [p].[NullableDoubleColumn], [p].[NullableFloatColumn], [p].[NullableIntColumn], [p].[NullableLongColumn], [p].[Price] FROM [Prices] AS [p] """, - // - """ + // + """ SELECT AVG([p].[Price]) FROM [Prices] AS [p] """, - // - """ + // + """ SELECT AVG(CAST([p].[IntColumn] AS float)) FROM [Prices] AS [p] """, - // - """ + // + """ SELECT AVG(CAST([p].[NullableIntColumn] AS float)) FROM [Prices] AS [p] """, - // - """ + // + """ SELECT AVG(CAST([p].[LongColumn] AS float)) FROM [Prices] AS [p] """, - // - """ + // + """ SELECT AVG(CAST([p].[NullableLongColumn] AS float)) FROM [Prices] AS [p] """, - // - """ + // + """ SELECT CAST(AVG([p].[FloatColumn]) AS real) FROM [Prices] AS [p] """, - // - """ + // + """ SELECT CAST(AVG([p].[NullableFloatColumn]) AS real) FROM [Prices] AS [p] """, - // - """ + // + """ SELECT AVG([p].[DoubleColumn]) FROM [Prices] AS [p] """, - // - """ + // + """ SELECT AVG([p].[NullableDoubleColumn]) FROM [Prices] AS [p] """, - // - """ + // + """ SELECT AVG([p].[DecimalColumn]) FROM [Prices] AS [p] """, - // - """ + // + """ SELECT AVG([p].[NullableDecimalColumn]) FROM [Prices] AS [p] """); @@ -1780,7 +1769,7 @@ public override async Task Parameterless_ctor_on_inner_DTO_gets_called_for_every await base.Parameterless_ctor_on_inner_DTO_gets_called_for_every_row(); AssertSql( -""" + """ SELECT [e].[Id], [e].[Name] FROM [Entities] AS [e] """); @@ -1826,7 +1815,7 @@ public override async Task Repeated_parameters_in_generated_query_sql() await base.Repeated_parameters_in_generated_query_sql(); AssertSql( -""" + """ @__k_0='1' SELECT TOP(1) [a].[Id], [a].[Name] @@ -1859,7 +1848,7 @@ public override async Task Operators_combine_nullability_of_entity_shapers() await base.Operators_combine_nullability_of_entity_shapers(); AssertSql( -""" + """ SELECT [a].[Id], [a].[a], [a].[a1], [a].[forkey], [b].[Id] AS [Id0], [b].[b], [b].[b1], [b].[forkey] AS [forkey0] FROM [As] AS [a] LEFT JOIN [Bs] AS [b] ON [a].[forkey] = [b].[forkey] @@ -1869,8 +1858,8 @@ FROM [Bs] AS [b0] LEFT JOIN [As] AS [a0] ON [b0].[forkey] = [a0].[forkey] WHERE [a0].[Id] IS NULL """, - // - """ + // + """ SELECT [a].[Id], [a].[a], [a].[a1], [a].[forkey], [b].[Id] AS [Id0], [b].[b], [b].[b1], [b].[forkey] AS [forkey0] FROM [As] AS [a] LEFT JOIN [Bs] AS [b] ON [a].[forkey] = [b].[forkey] @@ -1880,8 +1869,8 @@ FROM [Bs] AS [b0] LEFT JOIN [As] AS [a0] ON [b0].[forkey] = [a0].[forkey] WHERE [a0].[Id] IS NULL """, - // - """ + // + """ SELECT [a].[Id], [a].[a], [a].[a1], [a].[forkey], [b].[Id] AS [Id0], [b].[b], [b].[b1], [b].[forkey] AS [forkey0] FROM [As] AS [a] LEFT JOIN [Bs] AS [b] ON [a].[forkey] = [b].[forkey] @@ -1890,8 +1879,8 @@ FROM [As] AS [a] FROM [Bs] AS [b0] LEFT JOIN [As] AS [a0] ON [b0].[forkey] = [a0].[forkey] """, - // - """ + // + """ SELECT [a].[Id], [a].[a], [a].[a1], [a].[forkey], [b].[Id] AS [Id0], [b].[b], [b].[b1], [b].[forkey] AS [forkey0] FROM [As] AS [a] LEFT JOIN [Bs] AS [b] ON [a].[forkey] = [b].[forkey] @@ -1907,19 +1896,19 @@ public override async Task Shadow_property_with_inheritance() await base.Shadow_property_with_inheritance(); AssertSql( -""" + """ SELECT [c].[Id], [c].[Discriminator], [c].[IsPrimary], [c].[UserName], [c].[EmployerId], [c].[ServiceOperatorId] FROM [Contacts] AS [c] """, - // - """ + // + """ SELECT [c].[Id], [c].[Discriminator], [c].[IsPrimary], [c].[UserName], [c].[ServiceOperatorId], [s].[Id] FROM [Contacts] AS [c] INNER JOIN [ServiceOperators] AS [s] ON [c].[ServiceOperatorId] = [s].[Id] WHERE [c].[Discriminator] = N'ServiceOperatorContact' """, - // - """ + // + """ SELECT [c].[Id], [c].[Discriminator], [c].[IsPrimary], [c].[UserName], [c].[ServiceOperatorId] FROM [Contacts] AS [c] WHERE [c].[Discriminator] = N'ServiceOperatorContact' @@ -1931,7 +1920,7 @@ public override async Task Inlined_dbcontext_is_not_leaking() await base.Inlined_dbcontext_is_not_leaking(); AssertSql( -""" + """ SELECT [b].[Id] FROM [Blogs] AS [b] """); @@ -2001,7 +1990,7 @@ public override async Task Left_join_with_missing_key_values_on_both_sides(bool await base.Left_join_with_missing_key_values_on_both_sides(async); AssertSql( -""" + """ SELECT [c].[CustomerID], [c].[CustomerName], CASE WHEN [p].[PostcodeID] IS NULL THEN '' ELSE [p].[TownName] @@ -2045,7 +2034,7 @@ public override async Task Comparing_byte_column_to_enum_in_vb_creating_double_c await base.Comparing_byte_column_to_enum_in_vb_creating_double_cast(async); AssertSql( -""" + """ SELECT [f].[Id], [f].[Taste] FROM [Foods] AS [f] WHERE [f].[Taste] = CAST(1 AS tinyint) @@ -2057,7 +2046,7 @@ public override async Task Null_check_removal_in_ternary_maintain_appropriate_ca await base.Null_check_removal_in_ternary_maintain_appropriate_cast(async); AssertSql( -""" + """ SELECT CAST([f].[Taste] AS tinyint) AS [Bar] FROM [Foods] AS [f] """); @@ -2068,7 +2057,7 @@ public override async Task SaveChangesAsync_accepts_changes_with_ConfigureAwait_ await base.SaveChangesAsync_accepts_changes_with_ConfigureAwait_true(); AssertSql( -""" + """ SET IMPLICIT_TRANSACTIONS OFF; SET NOCOUNT ON; INSERT INTO [ObservableThings] @@ -2271,7 +2260,7 @@ public override async Task Aggregate_over_subquery_in_group_by_projection_2(bool await base.Aggregate_over_subquery_in_group_by_projection_2(async); AssertSql( -""" + """ SELECT [t].[Value] AS [A], ( SELECT MAX([t0].[Id]) FROM [Tables] AS [t0] @@ -2286,7 +2275,7 @@ public override async Task Group_by_aggregate_in_subquery_projection_after_group await base.Group_by_aggregate_in_subquery_projection_after_group_by(async); AssertSql( -""" + """ SELECT [t].[Value] AS [A], COALESCE(SUM([t].[Id]), 0) AS [B], COALESCE(( SELECT TOP(1) COALESCE(SUM([t].[Id]), 0) + COALESCE(SUM([t0].[Id]), 0) FROM [Tables] AS [t0] @@ -2302,7 +2291,7 @@ public override async Task Subquery_first_member_compared_to_null(bool async) await base.Subquery_first_member_compared_to_null(async); AssertSql( -""" + """ SELECT ( SELECT TOP(1) [c1].[SomeOtherNullableDateTime] FROM [Child] AS [c1] @@ -2346,7 +2335,7 @@ public override async Task Flattened_GroupJoin_on_interface_generic(bool async) await base.Flattened_GroupJoin_on_interface_generic(async); AssertSql( -""" + """ SELECT [c].[Id], [c].[ParentId], [c].[SomeInteger], [c].[SomeNullableDateTime], [c].[SomeOtherNullableDateTime] FROM [Parents] AS [p] LEFT JOIN [Child] AS [c] ON [p].[Id] = [c].[Id] diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/AdHocNavigationsQuerySqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/Query/AdHocNavigationsQuerySqlServerTest.cs index 41a474db0fd..b265e957cf7 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/AdHocNavigationsQuerySqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/AdHocNavigationsQuerySqlServerTest.cs @@ -15,7 +15,7 @@ protected override ITestStoreFactory TestStoreFactory [ConditionalFact] public virtual async Task Nested_include_queries_do_not_populate_navigation_twice() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var query = context.Blogs.Include(b => b.Posts); @@ -31,35 +31,35 @@ public virtual async Task Nested_include_queries_do_not_populate_navigation_twic b => Assert.Single(b.Posts)); AssertSql( -""" + """ SELECT [b].[Id], [p].[Id], [p].[BlogId] FROM [Blogs] AS [b] LEFT JOIN [Post] AS [p] ON [b].[Id] = [p].[BlogId] ORDER BY [b].[Id] """, - // - """ + // + """ SELECT [b].[Id], [p].[Id], [p].[BlogId] FROM [Blogs] AS [b] LEFT JOIN [Post] AS [p] ON [b].[Id] = [p].[BlogId] ORDER BY [b].[Id] """, - // - """ + // + """ SELECT [b].[Id], [p].[Id], [p].[BlogId] FROM [Blogs] AS [b] LEFT JOIN [Post] AS [p] ON [b].[Id] = [p].[BlogId] ORDER BY [b].[Id] """, - // - """ + // + """ SELECT [b].[Id], [p].[Id], [p].[BlogId] FROM [Blogs] AS [b] LEFT JOIN [Post] AS [p] ON [b].[Id] = [p].[BlogId] ORDER BY [b].[Id] """, - // - """ + // + """ SELECT [b].[Id], [p].[Id], [p].[BlogId] FROM [Blogs] AS [b] LEFT JOIN [Post] AS [p] ON [b].[Id] = [p].[BlogId] @@ -75,7 +75,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) { } - public void Seed() + public Task SeedAsync() { AddRange( new Blog @@ -90,7 +90,7 @@ public void Seed() new Blog { Posts = [new(), new()] }, new Blog { Posts = [new()] }); - SaveChanges(); + return SaveChangesAsync(); } public class Blog @@ -152,28 +152,28 @@ public override async Task Customer_collections_materialize_properly() await base.Customer_collections_materialize_properly(); AssertSql( -""" + """ SELECT [c].[Id], [o].[Id], [o].[CustomerId1], [o].[CustomerId2], [o].[CustomerId3], [o].[CustomerId4], [o].[Name] FROM [Customers] AS [c] LEFT JOIN [Orders] AS [o] ON [c].[Id] = [o].[CustomerId1] ORDER BY [c].[Id] """, - // - """ + // + """ SELECT [c].[Id], [o].[Id], [o].[CustomerId1], [o].[CustomerId2], [o].[CustomerId3], [o].[CustomerId4], [o].[Name] FROM [Customers] AS [c] LEFT JOIN [Orders] AS [o] ON [c].[Id] = [o].[CustomerId2] ORDER BY [c].[Id] """, - // - """ + // + """ SELECT [c].[Id], [o].[Id], [o].[CustomerId1], [o].[CustomerId2], [o].[CustomerId3], [o].[CustomerId4], [o].[Name] FROM [Customers] AS [c] LEFT JOIN [Orders] AS [o] ON [c].[Id] = [o].[CustomerId3] ORDER BY [c].[Id] """, - // - """ + // + """ SELECT [c].[Id], [o].[Id], [o].[CustomerId1], [o].[CustomerId2], [o].[CustomerId3], [o].[CustomerId4], [o].[Name] FROM [Customers] AS [c] LEFT JOIN [Orders] AS [o] ON [c].[Id] = [o].[CustomerId4] @@ -186,7 +186,7 @@ public override async Task Reference_include_on_derived_type_with_sibling_works( await base.Reference_include_on_derived_type_with_sibling_works(); AssertSql( -""" + """ SELECT [p].[Id], [p].[Discriminator], [p].[LeaveStart], [p].[LeaveTypeId], [p0].[Id] FROM [Proposals] AS [p] LEFT JOIN [ProposalLeaveType] AS [p0] ON [p].[LeaveTypeId] = [p0].[Id] @@ -233,14 +233,14 @@ public override async Task Include_with_order_by_on_interface_key() await base.Include_with_order_by_on_interface_key(); AssertSql( -""" + """ SELECT [p].[Id], [p].[Name], [c].[Id], [c].[Name], [c].[Parent10635Id], [c].[ParentId] FROM [Parents] AS [p] LEFT JOIN [Children] AS [c] ON [p].[Id] = [c].[Parent10635Id] ORDER BY [p].[Id] """, - // - """ + // + """ SELECT [p].[Id], [c].[Id], [c].[Name], [c].[Parent10635Id], [c].[ParentId] FROM [Parents] AS [p] LEFT JOIN [Children] AS [c] ON [p].[Id] = [c].[Parent10635Id] @@ -253,7 +253,7 @@ public override async Task Collection_without_setter_materialized_correctly() await base.Collection_without_setter_materialized_correctly(); AssertSql( -""" + """ SELECT [b].[Id], [p].[Id], [p].[BlogId1], [p].[BlogId2], [p].[BlogId3], [p].[Name], [p0].[Id], [p0].[BlogId1], [p0].[BlogId2], [p0].[BlogId3], [p0].[Name], [p1].[Id], [p1].[BlogId1], [p1].[BlogId2], [p1].[BlogId3], [p1].[Name] FROM [Blogs] AS [b] LEFT JOIN [Posts] AS [p] ON [b].[Id] = [p].[BlogId1] @@ -261,8 +261,8 @@ FROM [Blogs] AS [b] LEFT JOIN [Posts] AS [p1] ON [b].[Id] = [p1].[BlogId3] ORDER BY [b].[Id], [p].[Id], [p0].[Id] """, - // - """ + // + """ SELECT ( SELECT TOP(1) ( SELECT COUNT(*) @@ -294,14 +294,14 @@ public override async Task Include_collection_works_when_defined_on_intermediate await base.Include_collection_works_when_defined_on_intermediate_type(); AssertSql( -""" + """ SELECT [s].[Id], [s].[Discriminator], [s0].[Id], [s0].[SchoolId] FROM [Schools] AS [s] LEFT JOIN [Students] AS [s0] ON [s].[Id] = [s0].[SchoolId] ORDER BY [s].[Id] """, - // - """ + // + """ SELECT [s].[Id], [s0].[Id], [s0].[SchoolId] FROM [Schools] AS [s] LEFT JOIN [Students] AS [s0] ON [s].[Id] = [s0].[SchoolId] @@ -379,7 +379,7 @@ public override async Task Correlated_collection_correctly_associates_entities_w await base.Correlated_collection_correctly_associates_entities_with_byte_array_keys(); AssertSql( -""" + """ SELECT [b].[Name], [c].[Id] FROM [Blogs] AS [b] LEFT JOIN [Comments] AS [c] ON [b].[Name] = [c].[BlogName] @@ -392,7 +392,7 @@ public override async Task Can_ignore_invalid_include_path_error() await base.Can_ignore_invalid_include_path_error(); AssertSql( -""" + """ SELECT [b].[Id], [b].[Discriminator], [b].[SubAId] FROM [BaseClasses] AS [b] WHERE [b].[Discriminator] = N'ClassA' @@ -434,7 +434,7 @@ public override async Task Using_explicit_interface_implementation_as_navigation await base.Using_explicit_interface_implementation_as_navigation_works(); AssertSql( -""" + """ SELECT TOP(2) CASE WHEN EXISTS ( SELECT 1 @@ -488,54 +488,54 @@ public override async Task Cycles_in_auto_include() await base.Cycles_in_auto_include(); AssertSql( -""" + """ SELECT [p].[Id], [d].[Id], [d].[PrincipalId] FROM [PrincipalOneToOne] AS [p] LEFT JOIN [DependentOneToOne] AS [d] ON [p].[Id] = [d].[PrincipalId] """, - // - """ + // + """ SELECT [d].[Id], [d].[PrincipalId], [p].[Id] FROM [DependentOneToOne] AS [d] INNER JOIN [PrincipalOneToOne] AS [p] ON [d].[PrincipalId] = [p].[Id] """, - // - """ + // + """ SELECT [p].[Id], [d].[Id], [d].[PrincipalId] FROM [PrincipalOneToMany] AS [p] LEFT JOIN [DependentOneToMany] AS [d] ON [p].[Id] = [d].[PrincipalId] ORDER BY [p].[Id] """, - // - """ + // + """ SELECT [d].[Id], [d].[PrincipalId], [p].[Id], [d0].[Id], [d0].[PrincipalId] FROM [DependentOneToMany] AS [d] INNER JOIN [PrincipalOneToMany] AS [p] ON [d].[PrincipalId] = [p].[Id] LEFT JOIN [DependentOneToMany] AS [d0] ON [p].[Id] = [d0].[PrincipalId] ORDER BY [d].[Id], [p].[Id] """, - // - """ + // + """ SELECT [p].[Id] FROM [PrincipalManyToMany] AS [p] """, - // - """ + // + """ SELECT [d].[Id] FROM [DependentManyToMany] AS [d] """, - // - """ + // + """ SELECT [c].[Id], [c].[CycleCId] FROM [CycleA] AS [c] """, - // - """ + // + """ SELECT [c].[Id], [c].[CId], [c].[CycleAId] FROM [CycleB] AS [c] """, - // - """ + // + """ SELECT [c].[Id], [c].[BId] FROM [CycleC] AS [c] """); @@ -617,7 +617,7 @@ public override async Task Count_member_over_IReadOnlyCollection_works(bool asyn await base.Count_member_over_IReadOnlyCollection_works(async); AssertSql( -""" + """ SELECT ( SELECT COUNT(*) FROM [Books] AS [b] diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/AdHocQueryFiltersQuerySqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/Query/AdHocQueryFiltersQuerySqlServerTest.cs index ecd4af24a11..53d5e14fbe9 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/AdHocQueryFiltersQuerySqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/AdHocQueryFiltersQuerySqlServerTest.cs @@ -15,14 +15,14 @@ protected override ITestStoreFactory TestStoreFactory [ConditionalFact] public virtual async Task Query_filter_with_db_set_should_not_block_other_filters() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var query = context.Factions.ToList(); Assert.Empty(query); AssertSql( -""" + """ SELECT [f].[Id], [f].[Name] FROM [Factions] AS [f] WHERE EXISTS ( @@ -35,14 +35,14 @@ FROM [Leaders] AS [l] [ConditionalFact] public virtual async Task Keyless_type_used_inside_defining_query() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var query = context.LeadersQuery.ToList(); Assert.Single(query); AssertSql( -""" + """ SELECT [t].[Name] FROM ( SELECT [l].[Name] @@ -68,7 +68,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .Entity() .HasNoKey() .ToSqlQuery( -""" + """ SELECT [t].[Name] FROM ( SELECT [l].[Name] @@ -79,7 +79,7 @@ FROM [Leaders] AS [l] """); } - public void Seed() + public Task SeedAsync() { var f1 = new Faction11803 { Name = "Skeliege" }; var f2 = new Faction11803 { Name = "Monsters" }; @@ -95,7 +95,7 @@ public void Seed() Factions.AddRange(f1, f2, f3, f4, f5); Leaders.AddRange(l11, l12, l13, l14); - SaveChanges(); + return SaveChangesAsync(); } public class Faction11803 @@ -126,7 +126,7 @@ public override async Task Query_filter_with_contains_evaluates_correctly() await base.Query_filter_with_contains_evaluates_correctly(); AssertSql( -""" + """ @__ef_filter___ids_0='[1,7]' (Size = 4000) SELECT [e].[Id], [e].[Name] @@ -143,7 +143,7 @@ public override async Task MultiContext_query_filter_test() await base.MultiContext_query_filter_test(); AssertSql( -""" + """ @__ef_filter__Tenant_0='0' SELECT [b].[Id], [b].[SomeValue] @@ -173,7 +173,7 @@ public override async Task Weak_entities_with_query_filter_subquery_flattening() await base.Weak_entities_with_query_filter_subquery_flattening(); AssertSql( -""" + """ SELECT CASE WHEN EXISTS ( SELECT 1 @@ -209,15 +209,15 @@ public override async Task Self_reference_in_query_filter_works() await base.Self_reference_in_query_filter_works(); AssertSql( -""" + """ SELECT [e].[Id], [e].[Name] FROM [EntitiesWithQueryFilterSelfReference] AS [e] WHERE EXISTS ( SELECT 1 FROM [EntitiesWithQueryFilterSelfReference] AS [e0]) AND ([e].[Name] <> N'Foo' OR [e].[Name] IS NULL) """, - // - """ + // + """ SELECT [e].[Id], [e].[Name] FROM [EntitiesReferencingEntityWithQueryFilterSelfReference] AS [e] WHERE EXISTS ( @@ -234,15 +234,15 @@ public override async Task Invoke_inside_query_filter_gets_correctly_evaluated_d await base.Invoke_inside_query_filter_gets_correctly_evaluated_during_translation(); AssertSql( -""" + """ @__ef_filter__p_0='1' SELECT [e].[Id], [e].[Name], [e].[TenantId] FROM [Entities] AS [e] WHERE ([e].[Name] <> N'Foo' OR [e].[Name] IS NULL) AND [e].[TenantId] = @__ef_filter__p_0 """, - // - """ + // + """ @__ef_filter__p_0='2' SELECT [e].[Id], [e].[Name], [e].[TenantId] @@ -256,7 +256,7 @@ public override async Task Query_filter_with_null_constant() await base.Query_filter_with_null_constant(); AssertSql( -""" + """ SELECT [p].[Id], [p].[UserDeleteId] FROM [People] AS [p] LEFT JOIN [User18759] AS [u] ON [p].[UserDeleteId] = [u].[Id] @@ -269,7 +269,7 @@ public override async Task GroupJoin_SelectMany_gets_flattened() await base.GroupJoin_SelectMany_gets_flattened(); AssertSql( -""" + """ SELECT [c].[CustomerId], [c].[CustomerMembershipId] FROM [CustomerFilters] AS [c] WHERE ( @@ -278,8 +278,8 @@ FROM [Customers] AS [c0] LEFT JOIN [CustomerMemberships] AS [c1] ON [c0].[Id] = [c1].[CustomerId] WHERE [c1].[Id] IS NOT NULL AND [c0].[Id] = [c].[CustomerId]) > 0 """, - // - """ + // + """ SELECT [c].[Id], [c].[Name], [c0].[Id] AS [CustomerMembershipId], CASE WHEN [c0].[Id] IS NOT NULL THEN [c0].[Name] ELSE N'' diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/AdHocQuerySplittingQuerySqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/Query/AdHocQuerySplittingQuerySqlServerTest.cs index 364827f323b..e715fa17405 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/AdHocQuerySplittingQuerySqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/AdHocQuerySplittingQuerySqlServerTest.cs @@ -15,7 +15,9 @@ protected override ITestStoreFactory TestStoreFactory private static readonly FieldInfo _querySplittingBehaviorFieldInfo = typeof(RelationalOptionsExtension).GetField("_querySplittingBehavior", BindingFlags.NonPublic | BindingFlags.Instance); - protected override DbContextOptionsBuilder SetQuerySplittingBehavior(DbContextOptionsBuilder optionsBuilder, QuerySplittingBehavior splittingBehavior) + protected override DbContextOptionsBuilder SetQuerySplittingBehavior( + DbContextOptionsBuilder optionsBuilder, + QuerySplittingBehavior splittingBehavior) { new SqlServerDbContextOptionsBuilder(optionsBuilder).UseQuerySplittingBehavior(splittingBehavior); @@ -39,8 +41,8 @@ protected override DbContextOptionsBuilder ClearQuerySplittingBehavior(DbContext return optionsBuilder; } - protected override TestStore CreateTestStore25225() - => SqlServerTestStore.CreateInitialized(StoreName, multipleActiveResultSets: true); + protected override async Task CreateTestStore25225() + => await SqlServerTestStore.CreateInitializedAsync(StoreName, multipleActiveResultSets: true); public override async Task Can_configure_SingleQuery_at_context_level() { @@ -153,7 +155,7 @@ public override async Task Using_AsSingleQuery_without_context_configuration_doe await base.Using_AsSingleQuery_without_context_configuration_does_not_throw_warning(); AssertSql( -""" + """ SELECT [p].[Id], [c].[Id], [c].[ParentId], [a].[Id], [a].[ParentId] FROM [Parents] AS [p] LEFT JOIN [Child] AS [c] ON [p].[Id] = [c].[ParentId] @@ -268,8 +270,8 @@ ORDER BY [p1].[Id] public virtual async Task Using_AsSplitQuery_without_multiple_active_result_sets_works() { var contextFactory = await InitializeAsync( - seed: c => c.Seed(), - createTestStore: () => SqlServerTestStore.CreateInitialized(StoreName, multipleActiveResultSets: false)); + seed: c => c.SeedAsync(), + createTestStore: async () => await SqlServerTestStore.CreateInitializedAsync(StoreName, multipleActiveResultSets: false)); using var context = contextFactory.CreateContext(); context.Parents.Include(p => p.Children1).Include(p => p.Children2).AsSplitQuery().ToList(); @@ -301,7 +303,7 @@ public override async Task NoTracking_split_query_creates_only_required_instance await base.NoTracking_split_query_creates_only_required_instances(async); AssertSql( -""" + """ SELECT TOP(1) [t].[Id], [t].[Value] FROM [Tests] AS [t] ORDER BY [t].[Id] diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/GearsOfWarQuerySqlServerFixture.cs b/test/EFCore.SqlServer.FunctionalTests/Query/GearsOfWarQuerySqlServerFixture.cs index bff862279b0..5b68608def6 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/GearsOfWarQuerySqlServerFixture.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/GearsOfWarQuerySqlServerFixture.cs @@ -27,9 +27,9 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con }); } - protected override void Seed(GearsOfWarContext context) + protected override async Task SeedAsync(GearsOfWarContext context) { - base.Seed(context); + await base.SeedAsync(context); // Set up full-text search and add some full-text binary data context.Database.ExecuteSqlRaw( diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/IncompleteMappingInheritanceQuerySqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/Query/IncompleteMappingInheritanceQuerySqlServerTest.cs index a2a2c61e319..23c8121533d 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/IncompleteMappingInheritanceQuerySqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/IncompleteMappingInheritanceQuerySqlServerTest.cs @@ -437,7 +437,7 @@ FROM [Animals] AS [a] """); } - public override void Can_insert_update_delete() + public override Task Can_insert_update_delete() => base.Can_insert_update_delete(); public override async Task Byte_enum_value_constant_used_in_projection(bool async) @@ -541,9 +541,9 @@ FROM [Animals] AS [a0] """); } - public override void Member_access_on_intermediate_type_works() + public override async Task Member_access_on_intermediate_type_works() { - base.Member_access_on_intermediate_type_works(); + await base.Member_access_on_intermediate_type_works(); AssertSql( """ @@ -645,9 +645,9 @@ FROM [Animals] AS [a] """); } - public override void Setting_foreign_key_to_a_different_type_throws() + public override async Task Setting_foreign_key_to_a_different_type_throws() { - base.Setting_foreign_key_to_a_different_type_throws(); + await base.Setting_foreign_key_to_a_different_type_throws(); AssertSql( """ diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/NonSharedPrimitiveCollectionsQuerySqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/Query/NonSharedPrimitiveCollectionsQuerySqlServerTest.cs index 1be07ae2d93..e35cd767d91 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/NonSharedPrimitiveCollectionsQuerySqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/NonSharedPrimitiveCollectionsQuerySqlServerTest.cs @@ -662,7 +662,7 @@ private async Task TestOrderedArray( array2.SetValue(value2, 2); context.Entry(instance2).Property("SomeArray").CurrentValue = array2; - context.SaveChanges(); + return context.SaveChangesAsync(); }); await using var context = contextFactory.CreateContext(); @@ -880,8 +880,8 @@ public virtual async Task Ordered_collection_with_split_query() onModelCreating: mb => mb.Entity(), seed: context => { - context.Add(new Context32976.Principal { Ints = [2, 3, 4]}); - context.SaveChanges(); + context.Add(new Context32976.Principal { Ints = [2, 3, 4] }); + return context.SaveChangesAsync(); }); await using var context = contextFactory.CreateContext(); diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/OwnedEntityQuerySqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/Query/OwnedEntityQuerySqlServerTest.cs index e50c12e936e..c70570a8c7d 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/OwnedEntityQuerySqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/OwnedEntityQuerySqlServerTest.cs @@ -19,7 +19,7 @@ protected override ITestStoreFactory TestStoreFactory [ConditionalFact] public virtual async Task Optional_dependent_is_null_when_sharing_required_column_with_principal() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var query = context.Set().OrderByDescending(e => e.Id).ToList(); Assert.Equal(3, query.Count); @@ -74,7 +74,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .HasColumnName("RowVersion"); }); - public void Seed() + public Task SeedAsync() { AddRange( new User22054 @@ -104,7 +104,7 @@ public void Seed() }, new User22054 { Contact = null, Data = null }); - SaveChanges(); + return SaveChangesAsync(); } public class User22054 @@ -143,7 +143,7 @@ public class Address22054 [ConditionalFact] public virtual async Task Owned_entity_mapped_to_separate_table() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using var context = contextFactory.CreateContext(); var masterTrunk = context.MasterTrunk.OrderBy(e => EF.Property(e, "Id")).FirstOrDefault(); @@ -199,7 +199,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) }); } - public void Seed() + public Task SeedAsync() { var masterTrunk = new MasterTrunk22340 { @@ -208,7 +208,7 @@ public void Seed() }; Add(masterTrunk); - SaveChanges(); + return SaveChangesAsync(); } public class MasterTrunk22340 @@ -239,7 +239,7 @@ public class Currency22340 [ConditionalFact] public virtual async Task Collection_include_on_owner_with_owned_type_mapped_to_different_table() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using (var context = contextFactory.CreateContext()) { var owner = context.Set().Include(e => e.Dependents).AsSplitQuery().OrderBy(e => e.Id).Single(); @@ -284,7 +284,7 @@ ORDER BY [o].[Id] Assert.Equal("A", owner.Owned.Value); AssertSql( -""" + """ SELECT TOP(2) [s].[Id], [o].[SecondOwner23211Id], [o].[Value] FROM [SecondOwner23211] AS [s] LEFT JOIN [Owned23211] AS [o] ON [s].[Id] = [o].[SecondOwner23211Id] @@ -314,7 +314,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) modelBuilder.Entity().OwnsOne(e => e.Owned, b => b.ToTable("Owned23211")); } - public void Seed() + public Task SeedAsync() { Add( new Owner23211 @@ -325,13 +325,9 @@ public void Seed() }); Add( - new SecondOwner23211 - { - Dependents = [new(), new()], - Owned = new OwnedType23211 { Value = "A" } - }); + new SecondOwner23211 { Dependents = [new(), new()], Owned = new OwnedType23211 { Value = "A" } }); - SaveChanges(); + return SaveChangesAsync(); } public class Owner23211 @@ -372,14 +368,14 @@ public override async Task Include_collection_for_entity_with_owned_type_works() await base.Include_collection_for_entity_with_owned_type_works(); AssertSql( -""" + """ SELECT [m].[Id], [m].[Title], [m].[Details_Info], [m].[Details_Rating], [a].[Id], [a].[MovieId], [a].[Name], [a].[Details_Info], [a].[Details_Rating] FROM [Movies] AS [m] LEFT JOIN [Actors] AS [a] ON [m].[Id] = [a].[MovieId] ORDER BY [m].[Id] """, - // - """ + // + """ SELECT [m].[Id], [m].[Title], [m].[Details_Info], [m].[Details_Rating], [a].[Id], [a].[MovieId], [a].[Name], [a].[Details_Info], [a].[Details_Rating] FROM [Movies] AS [m] LEFT JOIN [Actors] AS [a] ON [m].[Id] = [a].[MovieId] @@ -392,7 +388,7 @@ public override async Task Multilevel_owned_entities_determine_correct_nullabili await base.Multilevel_owned_entities_determine_correct_nullability(); AssertSql( -""" + """ @p0='BaseEntity' (Nullable = false) (Size = 13) SET IMPLICIT_TRANSACTIONS OFF; @@ -408,7 +404,7 @@ public override async Task Correlated_subquery_with_owned_navigation_being_compa await base.Correlated_subquery_with_owned_navigation_being_compared_to_null_works(); AssertSql( -""" + """ SELECT [p].[Id], CASE WHEN [a].[Turnovers_AmountIn] IS NULL THEN CAST(1 AS bit) ELSE CAST(0 AS bit) @@ -510,7 +506,7 @@ public override async Task Nested_owned_required_dependents_are_materialized() await base.Nested_owned_required_dependents_are_materialized(); AssertSql( -""" + """ SELECT [e].[Id], [e].[Contact_Name], [e].[Contact_Address_City], [e].[Contact_Address_State], [e].[Contact_Address_Street], [e].[Contact_Address_Zip] FROM [Entity] AS [e] """); @@ -549,7 +545,7 @@ public override async Task Projecting_owned_collection_and_aggregate(bool async) await base.Projecting_owned_collection_and_aggregate(async); AssertSql( -""" + """ SELECT [b].[Id], ( SELECT COALESCE(SUM([p].[CommentsCount]), 0) FROM [Post] AS [p] @@ -565,7 +561,7 @@ public override async Task Projecting_correlated_collection_property_for_owned_e await base.Projecting_correlated_collection_property_for_owned_entity(async); AssertSql( -""" + """ SELECT [w].[WarehouseCode], [w].[Id], [w0].[CountryCode], [w0].[WarehouseCode], [w0].[Id] FROM [Warehouses] AS [w] LEFT JOIN [WarehouseDestinationCountry] AS [w0] ON [w].[WarehouseCode] = [w0].[WarehouseCode] diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/RawSqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/Query/RawSqlServerTest.cs index 8b0c505ea05..b6525c3fa55 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/RawSqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/RawSqlServerTest.cs @@ -13,7 +13,7 @@ public class RawSqlServerTest : NonSharedModelTestBase [ConditionalFact] public virtual async Task ToQuery_can_use_FromSqlRaw() { - var contextFactory = await InitializeAsync(seed: c => c.Seed()); + var contextFactory = await InitializeAsync(seed: c => c.SeedAsync()); using (var context = contextFactory.CreateContext()) { @@ -41,7 +41,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) #pragma warning restore CS0618 // Type or member is obsolete } - public void Seed() + public Task SeedAsync() { AddRange( new Order13346 { Amount = 1 }, @@ -50,7 +50,7 @@ public void Seed() new Order13346 { Amount = 4 } ); - SaveChanges(); + return SaveChangesAsync(); } public class Order13346 diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/TPCInheritanceQuerySqlServerTestBase.cs b/test/EFCore.SqlServer.FunctionalTests/Query/TPCInheritanceQuerySqlServerTestBase.cs index fc9099a724b..f29b96bb199 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/TPCInheritanceQuerySqlServerTestBase.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/TPCInheritanceQuerySqlServerTestBase.cs @@ -91,7 +91,7 @@ ORDER BY [e1].[Id] """); } - public override void Can_insert_update_delete() + public override Task Can_insert_update_delete() => base.Can_insert_update_delete(); public override async Task Can_query_all_animals(bool async) @@ -453,9 +453,9 @@ FROM [Roses] AS [r] """); } - public override void Member_access_on_intermediate_type_works() + public override async Task Member_access_on_intermediate_type_works() { - base.Member_access_on_intermediate_type_works(); + await base.Member_access_on_intermediate_type_works(); AssertSql( """ @@ -479,7 +479,7 @@ public override async Task OfType_Union_subquery(bool async) AssertSql(); } - public override void Setting_foreign_key_to_a_different_type_throws() + public override Task Setting_foreign_key_to_a_different_type_throws() => base.Setting_foreign_key_to_a_different_type_throws(); public override async Task Subquery_OfType(bool async) diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/TPHInheritanceQuerySqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/Query/TPHInheritanceQuerySqlServerTest.cs index 1a52c27b8ac..42500b42a56 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/TPHInheritanceQuerySqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/TPHInheritanceQuerySqlServerTest.cs @@ -8,7 +8,8 @@ namespace Microsoft.EntityFrameworkCore.Query; #nullable disable -public class TPHInheritanceQuerySqlServerTest(TPHInheritanceQuerySqlServerFixture fixture, ITestOutputHelper testOutputHelper) : TPHInheritanceQueryTestBase(fixture, testOutputHelper) +public class TPHInheritanceQuerySqlServerTest(TPHInheritanceQuerySqlServerFixture fixture, ITestOutputHelper testOutputHelper) + : TPHInheritanceQueryTestBase(fixture, testOutputHelper) { [ConditionalFact] public virtual void Check_all_tests_overridden() @@ -228,6 +229,9 @@ FROM [Plants] AS [p] """); } + public override Task Can_insert_update_delete() + => base.Can_insert_update_delete(); + public override async Task Can_query_all_animals(bool async) { await base.Can_query_all_animals(async); @@ -411,9 +415,6 @@ FROM [Animals] AS [a] """); } - public override void Can_insert_update_delete() - => base.Can_insert_update_delete(); - public override async Task Byte_enum_value_constant_used_in_projection(bool async) { await base.Byte_enum_value_constant_used_in_projection(async); @@ -514,9 +515,9 @@ FROM [Animals] AS [a0] """); } - public override void Member_access_on_intermediate_type_works() + public override async Task Member_access_on_intermediate_type_works() { - base.Member_access_on_intermediate_type_works(); + await base.Member_access_on_intermediate_type_works(); AssertSql( """ @@ -616,9 +617,9 @@ FROM [Animals] AS [a] """); } - public override void Setting_foreign_key_to_a_different_type_throws() + public override async Task Setting_foreign_key_to_a_different_type_throws() { - base.Setting_foreign_key_to_a_different_type_throws(); + await base.Setting_foreign_key_to_a_different_type_throws(); AssertSql( """ diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/TPHTemporalFiltersInheritanceQuerySqlServerFixture.cs b/test/EFCore.SqlServer.FunctionalTests/Query/TPHTemporalFiltersInheritanceQuerySqlServerFixture.cs index b3e8cf4d49b..7da8893c875 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/TPHTemporalFiltersInheritanceQuerySqlServerFixture.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/TPHTemporalFiltersInheritanceQuerySqlServerFixture.cs @@ -24,9 +24,9 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con modelBuilder.Entity().ToTable(tb => tb.IsTemporal()); } - protected override void Seed(InheritanceContext context) + protected override async Task SeedAsync(InheritanceContext context) { - base.Seed(context); + await base.SeedAsync(context); ChangesDate = new DateTime(2010, 1, 1); @@ -34,7 +34,7 @@ protected override void Seed(InheritanceContext context) context.RemoveRange(context.ChangeTracker.Entries().Where(e => e.Entity is Plant).Select(e => e.Entity)); context.RemoveRange(context.ChangeTracker.Entries().Where(e => e.Entity is Country).Select(e => e.Entity)); context.RemoveRange(context.ChangeTracker.Entries().Where(e => e.Entity is Drink).Select(e => e.Entity)); - context.SaveChanges(); + await context.SaveChangesAsync(); var tableNames = new List { @@ -46,14 +46,14 @@ protected override void Seed(InheritanceContext context) foreach (var tableName in tableNames) { - context.Database.ExecuteSqlRaw($"ALTER TABLE [{tableName}] SET (SYSTEM_VERSIONING = OFF)"); - context.Database.ExecuteSqlRaw($"ALTER TABLE [{tableName}] DROP PERIOD FOR SYSTEM_TIME"); + await context.Database.ExecuteSqlRawAsync($"ALTER TABLE [{tableName}] SET (SYSTEM_VERSIONING = OFF)"); + await context.Database.ExecuteSqlRawAsync($"ALTER TABLE [{tableName}] DROP PERIOD FOR SYSTEM_TIME"); - context.Database.ExecuteSqlRaw($"UPDATE [{tableName + "History"}] SET PeriodStart = '2000-01-01T01:00:00.0000000Z'"); - context.Database.ExecuteSqlRaw($"UPDATE [{tableName + "History"}] SET PeriodEnd = '2020-07-01T07:00:00.0000000Z'"); + await context.Database.ExecuteSqlRawAsync($"UPDATE [{tableName + "History"}] SET PeriodStart = '2000-01-01T01:00:00.0000000Z'"); + await context.Database.ExecuteSqlRawAsync($"UPDATE [{tableName + "History"}] SET PeriodEnd = '2020-07-01T07:00:00.0000000Z'"); - context.Database.ExecuteSqlRaw($"ALTER TABLE [{tableName}] ADD PERIOD FOR SYSTEM_TIME ([PeriodStart], [PeriodEnd])"); - context.Database.ExecuteSqlRaw( + await context.Database.ExecuteSqlRawAsync($"ALTER TABLE [{tableName}] ADD PERIOD FOR SYSTEM_TIME ([PeriodStart], [PeriodEnd])"); + await context.Database.ExecuteSqlRawAsync( $"ALTER TABLE [{tableName}] SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = [dbo].[{tableName + "History"}]))"); } } diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/TPTInheritanceQuerySqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/Query/TPTInheritanceQuerySqlServerTest.cs index 75efabae11e..fbd4212621a 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/TPTInheritanceQuerySqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/TPTInheritanceQuerySqlServerTest.cs @@ -7,7 +7,8 @@ namespace Microsoft.EntityFrameworkCore.Query; #nullable disable -public class TPTInheritanceQuerySqlServerTest(TPTInheritanceQuerySqlServerFixture fixture, ITestOutputHelper testOutputHelper) : TPTInheritanceQueryTestBase(fixture, testOutputHelper) +public class TPTInheritanceQuerySqlServerTest(TPTInheritanceQuerySqlServerFixture fixture, ITestOutputHelper testOutputHelper) + : TPTInheritanceQueryTestBase(fixture, testOutputHelper) { [ConditionalFact] public virtual void Check_all_tests_overridden() @@ -97,7 +98,7 @@ ORDER BY [s].[Id] """); } - public override void Can_insert_update_delete() + public override Task Can_insert_update_delete() => base.Can_insert_update_delete(); public override async Task Can_query_all_animals(bool async) @@ -480,9 +481,9 @@ WHERE [r].[Species] IS NOT NULL """); } - public override void Member_access_on_intermediate_type_works() + public override async Task Member_access_on_intermediate_type_works() { - base.Member_access_on_intermediate_type_works(); + await base.Member_access_on_intermediate_type_works(); AssertSql( """ @@ -508,9 +509,9 @@ public override async Task OfType_Union_subquery(bool async) AssertSql(" "); } - public override void Setting_foreign_key_to_a_different_type_throws() + public override async Task Setting_foreign_key_to_a_different_type_throws() { - base.Setting_foreign_key_to_a_different_type_throws(); + await base.Setting_foreign_key_to_a_different_type_throws(); AssertSql( """ diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/TemporalComplexNavigationsQuerySqlServerFixture.cs b/test/EFCore.SqlServer.FunctionalTests/Query/TemporalComplexNavigationsQuerySqlServerFixture.cs index 541abe0a15d..77f0e8c7d9b 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/TemporalComplexNavigationsQuerySqlServerFixture.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/TemporalComplexNavigationsQuerySqlServerFixture.cs @@ -24,9 +24,9 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con modelBuilder.Entity().ToTable(tb => tb.IsTemporal()); } - protected override void Seed(ComplexNavigationsContext context) + protected override async Task SeedAsync(ComplexNavigationsContext context) { - base.Seed(context); + await base.SeedAsync(context); ChangesDate = new DateTime(2010, 1, 1); @@ -41,44 +41,44 @@ protected override void Seed(ComplexNavigationsContext context) // clean up intermittent history since in the Seed method we do fixup in multiple stages foreach (var tableName in tableNames) { - context.Database.ExecuteSqlRaw($"ALTER TABLE [{tableName}] SET (SYSTEM_VERSIONING = OFF)"); - context.Database.ExecuteSqlRaw($"DELETE FROM [{tableName + "History"}]"); - context.Database.ExecuteSqlRaw( + await context.Database.ExecuteSqlRawAsync($"ALTER TABLE [{tableName}] SET (SYSTEM_VERSIONING = OFF)"); + await context.Database.ExecuteSqlRawAsync($"DELETE FROM [{tableName + "History"}]"); + await context.Database.ExecuteSqlRawAsync( $"ALTER TABLE [{tableName}] SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = [dbo].[{tableName + "History"}]))"); } foreach (var entityOne in context.ChangeTracker.Entries().Where(e => e.Entity is Level1).Select(e => e.Entity)) { - ((Level1)entityOne).Name = ((Level1)entityOne).Name + "Modified"; + ((Level1)entityOne).Name += "Modified"; } foreach (var entityOne in context.ChangeTracker.Entries().Where(e => e.Entity is Level2).Select(e => e.Entity)) { - ((Level2)entityOne).Name = ((Level2)entityOne).Name + "Modified"; + ((Level2)entityOne).Name += "Modified"; } foreach (var entityOne in context.ChangeTracker.Entries().Where(e => e.Entity is Level3).Select(e => e.Entity)) { - ((Level3)entityOne).Name = ((Level3)entityOne).Name + "Modified"; + ((Level3)entityOne).Name += "Modified"; } foreach (var entityOne in context.ChangeTracker.Entries().Where(e => e.Entity is Level4).Select(e => e.Entity)) { - ((Level4)entityOne).Name = ((Level4)entityOne).Name + "Modified"; + ((Level4)entityOne).Name += "Modified"; } - context.SaveChanges(); + await context.SaveChangesAsync(); foreach (var tableName in tableNames) { - context.Database.ExecuteSqlRaw($"ALTER TABLE [{tableName}] SET (SYSTEM_VERSIONING = OFF)"); - context.Database.ExecuteSqlRaw($"ALTER TABLE [{tableName}] DROP PERIOD FOR SYSTEM_TIME"); + await context.Database.ExecuteSqlRawAsync($"ALTER TABLE [{tableName}] SET (SYSTEM_VERSIONING = OFF)"); + await context.Database.ExecuteSqlRawAsync($"ALTER TABLE [{tableName}] DROP PERIOD FOR SYSTEM_TIME"); - context.Database.ExecuteSqlRaw($"UPDATE [{tableName + "History"}] SET PeriodStart = '2000-01-01T01:00:00.0000000Z'"); - context.Database.ExecuteSqlRaw($"UPDATE [{tableName + "History"}] SET PeriodEnd = '2020-07-01T07:00:00.0000000Z'"); + await context.Database.ExecuteSqlRawAsync($"UPDATE [{tableName + "History"}] SET PeriodStart = '2000-01-01T01:00:00.0000000Z'"); + await context.Database.ExecuteSqlRawAsync($"UPDATE [{tableName + "History"}] SET PeriodEnd = '2020-07-01T07:00:00.0000000Z'"); - context.Database.ExecuteSqlRaw($"ALTER TABLE [{tableName}] ADD PERIOD FOR SYSTEM_TIME ([PeriodStart], [PeriodEnd])"); - context.Database.ExecuteSqlRaw( + await context.Database.ExecuteSqlRawAsync($"ALTER TABLE [{tableName}] ADD PERIOD FOR SYSTEM_TIME ([PeriodStart], [PeriodEnd])"); + await context.Database.ExecuteSqlRawAsync( $"ALTER TABLE [{tableName}] SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = [dbo].[{tableName + "History"}]))"); } } diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/TemporalComplexNavigationsSharedTypeQuerySqlServerFixture.cs b/test/EFCore.SqlServer.FunctionalTests/Query/TemporalComplexNavigationsSharedTypeQuerySqlServerFixture.cs index 5e721834203..d4ba23b24b6 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/TemporalComplexNavigationsSharedTypeQuerySqlServerFixture.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/TemporalComplexNavigationsSharedTypeQuerySqlServerFixture.cs @@ -66,50 +66,50 @@ protected override void Configure(OwnedNavigationBuilder l4) })); } - protected override void Seed(ComplexNavigationsContext context) + protected override async Task SeedAsync(ComplexNavigationsContext context) { - base.Seed(context); + await base.SeedAsync(context); ChangesDate = new DateTime(2010, 1, 1); // clean up intermittent history since in the Seed method we do fixup in multiple stages var tableName = nameof(Level1); - context.Database.ExecuteSqlRaw($"ALTER TABLE [{tableName}] SET (SYSTEM_VERSIONING = OFF)"); - context.Database.ExecuteSqlRaw($"DELETE FROM [{tableName + "History"}]"); - context.Database.ExecuteSqlRaw( + await context.Database.ExecuteSqlRawAsync($"ALTER TABLE [{tableName}] SET (SYSTEM_VERSIONING = OFF)"); + await context.Database.ExecuteSqlRawAsync($"DELETE FROM [{tableName + "History"}]"); + await context.Database.ExecuteSqlRawAsync( $"ALTER TABLE [{tableName}] SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = [dbo].[{tableName + "History"}]))"); foreach (var entityOne in context.ChangeTracker.Entries().Where(e => e.Entity is Level1).Select(e => e.Entity)) { - ((Level1)entityOne).Name = ((Level1)entityOne).Name + "Modified"; + ((Level1)entityOne).Name += "Modified"; } foreach (var entityOne in context.ChangeTracker.Entries().Where(e => e.Entity is Level2).Select(e => e.Entity)) { - ((Level2)entityOne).Name = ((Level2)entityOne).Name + "Modified"; + ((Level2)entityOne).Name += "Modified"; } foreach (var entityOne in context.ChangeTracker.Entries().Where(e => e.Entity is Level3).Select(e => e.Entity)) { - ((Level3)entityOne).Name = ((Level3)entityOne).Name + "Modified"; + ((Level3)entityOne).Name += "Modified"; } foreach (var entityOne in context.ChangeTracker.Entries().Where(e => e.Entity is Level4).Select(e => e.Entity)) { - ((Level4)entityOne).Name = ((Level4)entityOne).Name + "Modified"; + ((Level4)entityOne).Name += "Modified"; } context.SaveChanges(); - context.Database.ExecuteSqlRaw($"ALTER TABLE [{tableName}] SET (SYSTEM_VERSIONING = OFF)"); - context.Database.ExecuteSqlRaw($"ALTER TABLE [{tableName}] DROP PERIOD FOR SYSTEM_TIME"); + await context.Database.ExecuteSqlRawAsync($"ALTER TABLE [{tableName}] SET (SYSTEM_VERSIONING = OFF)"); + await context.Database.ExecuteSqlRawAsync($"ALTER TABLE [{tableName}] DROP PERIOD FOR SYSTEM_TIME"); - context.Database.ExecuteSqlRaw($"UPDATE [{tableName + "History"}] SET PeriodStart = '2000-01-01T01:00:00.0000000Z'"); - context.Database.ExecuteSqlRaw($"UPDATE [{tableName + "History"}] SET PeriodEnd = '2020-07-01T07:00:00.0000000Z'"); + await context.Database.ExecuteSqlRawAsync($"UPDATE [{tableName + "History"}] SET PeriodStart = '2000-01-01T01:00:00.0000000Z'"); + await context.Database.ExecuteSqlRawAsync($"UPDATE [{tableName + "History"}] SET PeriodEnd = '2020-07-01T07:00:00.0000000Z'"); - context.Database.ExecuteSqlRaw($"ALTER TABLE [{tableName}] ADD PERIOD FOR SYSTEM_TIME ([PeriodStart], [PeriodEnd])"); - context.Database.ExecuteSqlRaw( + await context.Database.ExecuteSqlRawAsync($"ALTER TABLE [{tableName}] ADD PERIOD FOR SYSTEM_TIME ([PeriodStart], [PeriodEnd])"); + await context.Database.ExecuteSqlRawAsync( $"ALTER TABLE [{tableName}] SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = [dbo].[{tableName + "History"}]))"); } } diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/TemporalGearsOfWarQuerySqlServerFixture.cs b/test/EFCore.SqlServer.FunctionalTests/Query/TemporalGearsOfWarQuerySqlServerFixture.cs index 3ece8773079..9edbb19030e 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/TemporalGearsOfWarQuerySqlServerFixture.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/TemporalGearsOfWarQuerySqlServerFixture.cs @@ -36,22 +36,23 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con base.OnModelCreating(modelBuilder, context); } - protected override void Seed(GearsOfWarContext context) + protected override async Task SeedAsync(GearsOfWarContext context) { - base.Seed(context); + await base.SeedAsync(context); ChangesDate = new DateTime(2010, 1, 1); //// clean up intermittent history - we do the data fixup in 2 steps (due to cycle) //// so we want to remove the temporary states, so that further manipulation is easier - context.Database.ExecuteSqlRaw("ALTER TABLE [LocustLeaders] SET (SYSTEM_VERSIONING = OFF)"); - context.Database.ExecuteSqlRaw("DELETE FROM [LocustLeadersHistory]"); - context.Database.ExecuteSqlRaw( + await context.Database.ExecuteSqlRawAsync("ALTER TABLE [LocustLeaders] SET (SYSTEM_VERSIONING = OFF)"); + await context.Database.ExecuteSqlRawAsync("DELETE FROM [LocustLeadersHistory]"); + await context.Database.ExecuteSqlRawAsync( "ALTER TABLE [LocustLeaders] SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = [dbo].[LocustLeadersHistory]))"); - context.Database.ExecuteSqlRaw("ALTER TABLE [Missions] SET (SYSTEM_VERSIONING = OFF)"); - context.Database.ExecuteSqlRaw("DELETE FROM [MissionsHistory]"); - context.Database.ExecuteSqlRaw("ALTER TABLE [Missions] SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = [dbo].[MissionsHistory]))"); + await context.Database.ExecuteSqlRawAsync("ALTER TABLE [Missions] SET (SYSTEM_VERSIONING = OFF)"); + await context.Database.ExecuteSqlRawAsync("DELETE FROM [MissionsHistory]"); + await context.Database.ExecuteSqlRawAsync( + "ALTER TABLE [Missions] SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = [dbo].[MissionsHistory]))"); context.RemoveRange(context.ChangeTracker.Entries().Where(e => e.Entity is City).Select(e => e.Entity)); context.RemoveRange(context.ChangeTracker.Entries().Where(e => e.Entity is CogTag).Select(e => e.Entity)); @@ -61,16 +62,17 @@ protected override void Seed(GearsOfWarContext context) context.RemoveRange(context.ChangeTracker.Entries().Where(e => e.Entity is Squad).Select(e => e.Entity)); context.RemoveRange(context.ChangeTracker.Entries().Where(e => e.Entity is SquadMission).Select(e => e.Entity)); context.RemoveRange(context.ChangeTracker.Entries().Where(e => e.Entity is Weapon).Select(e => e.Entity)); - context.SaveChanges(); + await context.SaveChangesAsync(); context.RemoveRange(context.ChangeTracker.Entries().Where(e => e.Entity is Faction).Select(e => e.Entity)); context.RemoveRange(context.ChangeTracker.Entries().Where(e => e.Entity is LocustLeader).Select(e => e.Entity)); - context.SaveChanges(); + await context.SaveChangesAsync(); // clean up Faction history - context.Database.ExecuteSqlRaw("ALTER TABLE [Factions] SET (SYSTEM_VERSIONING = OFF)"); - context.Database.ExecuteSqlRaw("DELETE FROM [FactionsHistory] WHERE CommanderName IS NULL"); - context.Database.ExecuteSqlRaw("ALTER TABLE [Factions] SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = [dbo].[FactionsHistory]))"); + await context.Database.ExecuteSqlRawAsync("ALTER TABLE [Factions] SET (SYSTEM_VERSIONING = OFF)"); + await context.Database.ExecuteSqlRawAsync("DELETE FROM [FactionsHistory] WHERE CommanderName IS NULL"); + await context.Database.ExecuteSqlRawAsync( + "ALTER TABLE [Factions] SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = [dbo].[FactionsHistory]))"); var tableNames = new List { diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/TemporalManyToManyQuerySqlServerFixture.cs b/test/EFCore.SqlServer.FunctionalTests/Query/TemporalManyToManyQuerySqlServerFixture.cs index 4a9a0aa593f..f49768ac2fd 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/TemporalManyToManyQuerySqlServerFixture.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/TemporalManyToManyQuerySqlServerFixture.cs @@ -364,9 +364,9 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con }); } - protected override void Seed(ManyToManyContext context) + protected override async Task SeedAsync(ManyToManyContext context) { - base.Seed(context); + await base.SeedAsync(context); ChangesDate = new DateTime(2010, 1, 1); @@ -380,7 +380,7 @@ protected override void Seed(ManyToManyContext context) context.RemoveRange(context.ChangeTracker.Entries().Where(e => e.Entity is UnidirectionalEntityOne).Select(e => e.Entity)); context.RemoveRange(context.ChangeTracker.Entries().Where(e => e.Entity is UnidirectionalEntityCompositeKey).Select(e => e.Entity)); context.RemoveRange(context.ChangeTracker.Entries().Where(e => e.Entity is UnidirectionalEntityRoot).Select(e => e.Entity)); - context.SaveChanges(); + await context.SaveChangesAsync(); var tableNames = new List { @@ -424,14 +424,14 @@ protected override void Seed(ManyToManyContext context) foreach (var tableName in tableNames) { - context.Database.ExecuteSqlRaw($"ALTER TABLE [{tableName}] SET (SYSTEM_VERSIONING = OFF)"); - context.Database.ExecuteSqlRaw($"ALTER TABLE [{tableName}] DROP PERIOD FOR SYSTEM_TIME"); + await context.Database.ExecuteSqlRawAsync($"ALTER TABLE [{tableName}] SET (SYSTEM_VERSIONING = OFF)"); + await context.Database.ExecuteSqlRawAsync($"ALTER TABLE [{tableName}] DROP PERIOD FOR SYSTEM_TIME"); - context.Database.ExecuteSqlRaw($"UPDATE [{tableName + "History"}] SET PeriodStart = '2000-01-01T01:00:00.0000000Z'"); - context.Database.ExecuteSqlRaw($"UPDATE [{tableName + "History"}] SET PeriodEnd = '2020-07-01T07:00:00.0000000Z'"); + await context.Database.ExecuteSqlRawAsync($"UPDATE [{tableName + "History"}] SET PeriodStart = '2000-01-01T01:00:00.0000000Z'"); + await context.Database.ExecuteSqlRawAsync($"UPDATE [{tableName + "History"}] SET PeriodEnd = '2020-07-01T07:00:00.0000000Z'"); - context.Database.ExecuteSqlRaw($"ALTER TABLE [{tableName}] ADD PERIOD FOR SYSTEM_TIME ([PeriodStart], [PeriodEnd])"); - context.Database.ExecuteSqlRaw( + await context.Database.ExecuteSqlRawAsync($"ALTER TABLE [{tableName}] ADD PERIOD FOR SYSTEM_TIME ([PeriodStart], [PeriodEnd])"); + await context.Database.ExecuteSqlRawAsync( $"ALTER TABLE [{tableName}] SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = [dbo].[{tableName + "History"}]))"); } } diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/TemporalOwnedQuerySqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/Query/TemporalOwnedQuerySqlServerTest.cs index 1420ff1b1eb..6d44b5c618f 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/TemporalOwnedQuerySqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/TemporalOwnedQuerySqlServerTest.cs @@ -1968,13 +1968,13 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con modelBuilder.Entity().OwnsOne(e => e.Gas); } - protected override void Seed(PoolableDbContext context) + protected override async Task SeedAsync(PoolableDbContext context) { - base.Seed(context); + await base.SeedAsync(context); ChangesDate = new DateTime(2010, 1, 1); - var ownedPeople = context.Set().AsTracking().ToList(); + var ownedPeople = await context.Set().AsTracking().ToListAsync(); foreach (var ownedPerson in ownedPeople) { ownedPerson["Name"] = "Modified" + ownedPerson["Name"]; @@ -1990,7 +1990,7 @@ protected override void Seed(PoolableDbContext context) } } - var stars = context.Set().AsTracking().ToList(); + var stars = await context.Set().AsTracking().ToListAsync(); foreach (var star in stars) { star.Name = "Modified" + star.Name; @@ -2003,22 +2003,22 @@ protected override void Seed(PoolableDbContext context) } } - var planets = context.Set().AsTracking().ToList(); + var planets = await context.Set().AsTracking().ToListAsync(); foreach (var planet in planets) { planet.Name = "Modified" + planet.Name; } - var moons = context.Set().AsTracking().ToList(); + var moons = await context.Set().AsTracking().ToListAsync(); foreach (var moon in moons) { moon.Diameter += 1000; } - var finks = context.Set().AsTracking().ToList(); + var finks = await context.Set().AsTracking().ToListAsync(); context.Set().RemoveRange(finks); - var bartons = context.Set().Include(x => x.Throned).AsTracking().ToList(); + var bartons = await context.Set().Include(x => x.Throned).AsTracking().ToListAsync(); foreach (var barton in bartons) { barton.Simple = "Modified" + barton.Simple; @@ -2028,7 +2028,7 @@ protected override void Seed(PoolableDbContext context) } } - context.SaveChanges(); + await context.SaveChangesAsync(); var tableNames = new List { @@ -2045,14 +2045,17 @@ protected override void Seed(PoolableDbContext context) foreach (var tableName in tableNames) { - context.Database.ExecuteSqlRaw($"ALTER TABLE [{tableName}] SET (SYSTEM_VERSIONING = OFF)"); - context.Database.ExecuteSqlRaw($"ALTER TABLE [{tableName}] DROP PERIOD FOR SYSTEM_TIME"); + await context.Database.ExecuteSqlRawAsync($"ALTER TABLE [{tableName}] SET (SYSTEM_VERSIONING = OFF)"); + await context.Database.ExecuteSqlRawAsync($"ALTER TABLE [{tableName}] DROP PERIOD FOR SYSTEM_TIME"); - context.Database.ExecuteSqlRaw($"UPDATE [{tableName + "History"}] SET PeriodStart = '2000-01-01T01:00:00.0000000Z'"); - context.Database.ExecuteSqlRaw($"UPDATE [{tableName + "History"}] SET PeriodEnd = '2020-07-01T07:00:00.0000000Z'"); + await context.Database.ExecuteSqlRawAsync( + $"UPDATE [{tableName + "History"}] SET PeriodStart = '2000-01-01T01:00:00.0000000Z'"); + await context.Database.ExecuteSqlRawAsync( + $"UPDATE [{tableName + "History"}] SET PeriodEnd = '2020-07-01T07:00:00.0000000Z'"); - context.Database.ExecuteSqlRaw($"ALTER TABLE [{tableName}] ADD PERIOD FOR SYSTEM_TIME ([PeriodStart], [PeriodEnd])"); - context.Database.ExecuteSqlRaw( + await context.Database.ExecuteSqlRawAsync( + $"ALTER TABLE [{tableName}] ADD PERIOD FOR SYSTEM_TIME ([PeriodStart], [PeriodEnd])"); + await context.Database.ExecuteSqlRawAsync( $"ALTER TABLE [{tableName}] SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = [dbo].[{tableName + "History"}]))"); } } diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/TemporalTableSqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/Query/TemporalTableSqlServerTest.cs index 63320585dd0..0a1206251ed 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/TemporalTableSqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/TemporalTableSqlServerTest.cs @@ -476,7 +476,7 @@ protected Task> InitializeAsync( Action onModelCreating, bool seed = true) => InitializeAsync( - onModelCreating, shouldLogCategory: _ => true, seed: seed ? c => c.Seed() : null); + onModelCreating, shouldLogCategory: _ => true, seed: seed ? c => c.SeedAsync() : null); protected virtual void OnModelCreating(ModelBuilder modelBuilder) { diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/UdfDbFunctionSqlServerTests.cs b/test/EFCore.SqlServer.FunctionalTests/Query/UdfDbFunctionSqlServerTests.cs index c12a2f41770..c4dcabf79ac 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/UdfDbFunctionSqlServerTests.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/UdfDbFunctionSqlServerTests.cs @@ -1014,11 +1014,11 @@ protected override string StoreName protected override ITestStoreFactory TestStoreFactory => SqlServerTestStoreFactory.Instance; - protected override void Seed(DbContext context) + protected override async Task SeedAsync(DbContext context) { - base.Seed(context); + await base.SeedAsync(context); - context.Database.ExecuteSqlRaw( + await context.Database.ExecuteSqlRawAsync( @"create function [dbo].[CustomerOrderCount] (@customerId int) returns int as @@ -1026,7 +1026,7 @@ returns int return (select count(id) from orders where customerId = @customerId); end"); - context.Database.ExecuteSqlRaw( + await context.Database.ExecuteSqlRawAsync( @"create function[dbo].[StarValue] (@starCount int, @value nvarchar(max)) returns nvarchar(max) as @@ -1034,7 +1034,7 @@ returns nvarchar(max) return replicate('*', @starCount) + @value end"); - context.Database.ExecuteSqlRaw( + await context.Database.ExecuteSqlRawAsync( @"create function[dbo].[DollarValue] (@starCount int, @value nvarchar(max)) returns nvarchar(max) as @@ -1042,7 +1042,7 @@ returns nvarchar(max) return replicate('$', @starCount) + @value end"); - context.Database.ExecuteSqlRaw( + await context.Database.ExecuteSqlRawAsync( @"create function [dbo].[GetReportingPeriodStartDate] (@period int) returns DateTime as @@ -1050,7 +1050,7 @@ returns DateTime return '1998-01-01' end"); - context.Database.ExecuteSqlRaw( + await context.Database.ExecuteSqlRawAsync( @"create function [dbo].[GetCustomerWithMostOrdersAfterDate] (@searchDate Date) returns int as @@ -1062,7 +1062,7 @@ group by CustomerId order by count(id) desc) end"); - context.Database.ExecuteSqlRaw( + await context.Database.ExecuteSqlRawAsync( @"create function [dbo].[IsTopCustomer] (@customerId int) returns bit as @@ -1073,7 +1073,7 @@ returns bit return 0 end"); - context.Database.ExecuteSqlRaw( + await context.Database.ExecuteSqlRawAsync( @"create function [dbo].[IdentityString] (@s nvarchar(max)) returns nvarchar(max) as @@ -1081,7 +1081,7 @@ returns nvarchar(max) return @s; end"); - context.Database.ExecuteSqlRaw( + await context.Database.ExecuteSqlRawAsync( @"create function [dbo].[IdentityStringPropagatesNull] (@s nvarchar(max)) returns nvarchar(max) as @@ -1089,7 +1089,7 @@ returns nvarchar(max) return @s; end"); - context.Database.ExecuteSqlRaw( + await context.Database.ExecuteSqlRawAsync( @"create function [dbo].[IdentityStringNonNullable] (@s nvarchar(max)) returns nvarchar(max) as @@ -1097,7 +1097,7 @@ returns nvarchar(max) return COALESCE(@s, 'NULL'); end"); - context.Database.ExecuteSqlRaw( + await context.Database.ExecuteSqlRawAsync( @"create function [dbo].[IdentityStringNonNullableFluent] (@s nvarchar(max)) returns nvarchar(max) as @@ -1105,7 +1105,7 @@ returns nvarchar(max) return COALESCE(@s, 'NULL'); end"); - context.Database.ExecuteSqlRaw( + await context.Database.ExecuteSqlRawAsync( @"create function [dbo].[StringLength] (@s nvarchar(max)) returns int as @@ -1113,7 +1113,7 @@ returns int return LEN(@s); end"); - context.Database.ExecuteSqlRaw( + await context.Database.ExecuteSqlRawAsync( @"create function [dbo].GetCustomerOrderCountByYear(@customerId int) returns @reports table ( @@ -1133,7 +1133,7 @@ order by year(orderDate) return end"); - context.Database.ExecuteSqlRaw( + await context.Database.ExecuteSqlRawAsync( @"create function [dbo].GetCustomerOrderCountByYearOnlyFrom2000(@customerId int, @onlyFrom2000 bit) returns @reports table ( @@ -1153,7 +1153,7 @@ order by year(orderDate) return end"); - context.Database.ExecuteSqlRaw( + await context.Database.ExecuteSqlRawAsync( @"create function [dbo].GetTopTwoSellingProducts() returns @products table ( @@ -1171,7 +1171,7 @@ order by totalSold desc return end"); - context.Database.ExecuteSqlRaw( + await context.Database.ExecuteSqlRawAsync( @"create function [dbo].GetTopSellingProductsForCustomer(@customerId int) returns @products table ( @@ -1190,7 +1190,7 @@ group by ProductID return end"); - context.Database.ExecuteSqlRaw( + await context.Database.ExecuteSqlRawAsync( @"create function [dbo].GetOrdersWithMultipleProducts(@customerId int) returns @orders table ( @@ -1211,7 +1211,7 @@ having count(productId) > 1 return end"); - context.Database.ExecuteSqlRaw( + await context.Database.ExecuteSqlRawAsync( @"create function [dbo].[AddValues] (@a int, @b int) returns int as diff --git a/test/EFCore.SqlServer.FunctionalTests/SaveChangesInterceptionSqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/SaveChangesInterceptionSqlServerTest.cs index 659fc243d18..9df0700d64a 100644 --- a/test/EFCore.SqlServer.FunctionalTests/SaveChangesInterceptionSqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/SaveChangesInterceptionSqlServerTest.cs @@ -28,7 +28,7 @@ public virtual async Task Intercept_concurrency_with_relational_specific_data(bo var saveChangesInterceptor = new RelationalConcurrencySaveChangesInterceptor(); var commandInterceptor = new TestCommandInterceptor(); - var context = CreateContext(saveChangesInterceptor, commandInterceptor); + var context = await CreateContextAsync(saveChangesInterceptor, commandInterceptor); using var _ = context; @@ -171,7 +171,8 @@ public override DbContextOptionsBuilder AddOptions(DbContextOptionsBuilder build } public class SaveChangesInterceptionSqlServerTest(SaveChangesInterceptionSqlServerTest.InterceptionSqlServerFixture fixture) - : SaveChangesInterceptionSqlServerTestBase(fixture), IClassFixture + : SaveChangesInterceptionSqlServerTestBase(fixture), + IClassFixture { public class InterceptionSqlServerFixture : InterceptionSqlServerFixtureBase { @@ -183,7 +184,8 @@ protected override bool ShouldSubscribeToDiagnosticListener } } - public class SaveChangesInterceptionWithDiagnosticsSqlServerTest(SaveChangesInterceptionWithDiagnosticsSqlServerTest.InterceptionSqlServerFixture fixture) + public class SaveChangesInterceptionWithDiagnosticsSqlServerTest( + SaveChangesInterceptionWithDiagnosticsSqlServerTest.InterceptionSqlServerFixture fixture) : SaveChangesInterceptionSqlServerTestBase(fixture), IClassFixture { diff --git a/test/EFCore.SqlServer.FunctionalTests/SequenceEndToEndTest.cs b/test/EFCore.SqlServer.FunctionalTests/SequenceEndToEndTest.cs index da2a90c6d83..c27a01857bc 100644 --- a/test/EFCore.SqlServer.FunctionalTests/SequenceEndToEndTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/SequenceEndToEndTest.cs @@ -7,7 +7,7 @@ namespace Microsoft.EntityFrameworkCore; #nullable disable -public class SequenceEndToEndTest : IDisposable +public class SequenceEndToEndTest : IAsyncLifetime { [ConditionalFact] public void Can_use_sequence_end_to_end() @@ -403,13 +403,14 @@ private class Unicon public string Name { get; set; } } - public SequenceEndToEndTest() - { - TestStore = SqlServerTestStore.CreateInitialized("SequenceEndToEndTest"); - } + protected SqlServerTestStore TestStore { get; private set; } - protected SqlServerTestStore TestStore { get; } + public async Task InitializeAsync() + => TestStore = await SqlServerTestStore.CreateInitializedAsync("SequenceEndToEndTest"); - public void Dispose() - => TestStore.Dispose(); + public Task DisposeAsync() + { + TestStore.Dispose(); + return Task.CompletedTask; + } } diff --git a/test/EFCore.SqlServer.FunctionalTests/SequentialGuidEndToEndTest.cs b/test/EFCore.SqlServer.FunctionalTests/SequentialGuidEndToEndTest.cs index 406aca4aa4b..ab5b04f98ce 100644 --- a/test/EFCore.SqlServer.FunctionalTests/SequentialGuidEndToEndTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/SequentialGuidEndToEndTest.cs @@ -7,7 +7,7 @@ namespace Microsoft.EntityFrameworkCore; #nullable disable -public class SequentialGuidEndToEndTest : IDisposable +public class SequentialGuidEndToEndTest : IAsyncLifetime { [ConditionalFact] public async Task Can_use_sequential_GUID_end_to_end_async() @@ -101,13 +101,14 @@ private class Pegasus public int Index { get; set; } } - public SequentialGuidEndToEndTest() - { - TestStore = SqlServerTestStore.CreateInitialized("SequentialGuidEndToEndTest"); - } + protected SqlServerTestStore TestStore { get; private set; } - protected SqlServerTestStore TestStore { get; } + public async Task InitializeAsync() + => TestStore = await SqlServerTestStore.CreateInitializedAsync("SequentialGuidEndToEndTest"); - public virtual void Dispose() - => TestStore.Dispose(); + public Task DisposeAsync() + { + TestStore.Dispose(); + return Task.CompletedTask; + } } diff --git a/test/EFCore.SqlServer.FunctionalTests/SqlServerConfigPatternsTest.cs b/test/EFCore.SqlServer.FunctionalTests/SqlServerConfigPatternsTest.cs index 29e186663c0..d438844b951 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 (SqlServerTestStore.GetNorthwindStore()) + 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 (SqlServerTestStore.GetNorthwindStore()) + 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 (SqlServerTestStore.GetNorthwindStore()) + 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 (SqlServerTestStore.GetNorthwindStore()) + using (await SqlServerTestStore.GetNorthwindStoreAsync()) { using var context = new NorthwindContext( new DbContextOptionsBuilder() @@ -125,9 +125,9 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) public class ExplicitServicesAndNoConfig { [ConditionalFact] - public void Throws_on_attempt_to_use_SQL_Server_without_providing_connection_string() + public async Task Throws_on_attempt_to_use_SQL_Server_without_providing_connection_string() { - using (SqlServerTestStore.GetNorthwindStore()) + using (await SqlServerTestStore.GetNorthwindStoreAsync()) { Assert.Equal( CoreStrings.NoProviderConfigured, @@ -156,9 +156,9 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) public class NoServicesAndNoConfig { [ConditionalFact] - public void Throws_on_attempt_to_use_context_with_no_store() + public async Task Throws_on_attempt_to_use_context_with_no_store() { - using (SqlServerTestStore.GetNorthwindStore()) + using (await SqlServerTestStore.GetNorthwindStoreAsync()) { Assert.Equal( CoreStrings.NoProviderConfigured, @@ -186,13 +186,13 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) public class ImplicitConfigButNoServices { [ConditionalFact] - public void Throws_on_attempt_to_use_store_with_no_store_services() + public async Task Throws_on_attempt_to_use_store_with_no_store_services() { var serviceCollection = new ServiceCollection(); new EntityFrameworkServicesBuilder(serviceCollection).TryAddCoreServices(); var serviceProvider = serviceCollection.BuildServiceProvider(validateScopes: true); - using (SqlServerTestStore.GetNorthwindStore()) + 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 (SqlServerTestStore.GetNorthwindStore()) + using (await SqlServerTestStore.GetNorthwindStoreAsync()) { await serviceProvider.GetRequiredService().TestAsync(); } @@ -286,7 +286,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 (SqlServerTestStore.GetNorthwindStore()) + using (await SqlServerTestStore.GetNorthwindStoreAsync()) { await serviceProvider.GetRequiredService().TestAsync(); } @@ -327,7 +327,7 @@ public class ConstructorArgsToBuilder [ConditionalFact] public async Task Can_pass_context_options_to_constructor_and_use_in_builder() { - using (SqlServerTestStore.GetNorthwindStore()) + using (await SqlServerTestStore.GetNorthwindStoreAsync()) { using var context = new NorthwindContext( new DbContextOptionsBuilder() @@ -352,7 +352,7 @@ public class ConstructorArgsToOnConfiguring [ConditionalFact] public async Task Can_pass_connection_string_to_constructor_and_use_in_OnConfiguring() { - using (SqlServerTestStore.GetNorthwindStore()) + using (await SqlServerTestStore.GetNorthwindStoreAsync()) { using var context = new NorthwindContext(SqlServerNorthwindTestStoreFactory.NorthwindConnectionString); Assert.Equal(91, await context.Customers.CountAsync()); @@ -380,7 +380,7 @@ public class NestedContext [ConditionalFact] public async Task Can_use_one_context_nested_inside_another_of_the_same_type() { - using (SqlServerTestStore.GetNorthwindStore()) + 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 c3d3e9dae79..81551fe7d17 100644 --- a/test/EFCore.SqlServer.FunctionalTests/SqlServerDatabaseCreatorTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/SqlServerDatabaseCreatorTest.cs @@ -82,8 +82,8 @@ 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 - ? SqlServerTestStore.CreateInitialized("ExistingBloggingFile", useFileName: true) - : SqlServerTestStore.GetOrCreateInitialized("ExistingBlogging"); + ? await SqlServerTestStore.CreateInitializedAsync("ExistingBloggingFile", useFileName: true) + : await SqlServerTestStore.GetOrCreateInitializedAsync("ExistingBlogging"); using var context = new BloggingContext(testDatabase); var creator = GetDatabaseCreator(context); @@ -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 = SqlServerTestStore.CreateInitialized("EnsureDeleteBlogging" + (file ? "File" : ""), file); + using var testDatabase = await SqlServerTestStore.CreateInitializedAsync("EnsureDeleteBlogging" + (file ? "File" : ""), file); if (!open) { testDatabase.CloseConnection(); @@ -251,7 +251,7 @@ private static async Task Creates_physical_database_and_schema_test( using var context = new BloggingContext(testDatabase); if (createDatabase) { - testDatabase.Initialize(null, (Func)null); + await testDatabase.InitializeAsync(null, (Func)null); } else { @@ -327,7 +327,7 @@ 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 = SqlServerTestStore.CreateInitialized("InitializedBlogging" + (file ? "File" : ""), file); + using var testDatabase = await SqlServerTestStore.CreateInitializedAsync("InitializedBlogging" + (file ? "File" : ""), file); using var context = new BloggingContext(testDatabase); context.Database.EnsureCreatedResiliently(); @@ -376,7 +376,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 = SqlServerTestStore.GetOrCreateInitialized("Empty"); + using var testDatabase = await SqlServerTestStore.GetOrCreateInitializedAsync("Empty"); var creator = GetDatabaseCreator(testDatabase); await GetExecutionStrategy(testDatabase).ExecuteAsync( @@ -394,8 +394,8 @@ 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 = SqlServerTestStore.GetOrCreate("ExistingTables") - .InitializeSqlServer(null, t => new BloggingContext(t), null); + using var testDatabase = await SqlServerTestStore.GetOrCreate("ExistingTables") + .InitializeSqlServerAsync(null, t => new BloggingContext(t), null); var creator = GetDatabaseCreator(testDatabase); await GetExecutionStrategy(testDatabase).ExecuteAsync( @@ -417,7 +417,7 @@ public class SqlServerDatabaseCreatorDeleteTest : SqlServerDatabaseCreatorTest [InlineData(false, false)] public static async Task Deletes_database(bool async, bool ambientTransaction) { - using var testDatabase = SqlServerTestStore.CreateInitialized("DeleteBlogging"); + using var testDatabase = await SqlServerTestStore.CreateInitializedAsync("DeleteBlogging"); testDatabase.CloseConnection(); var creator = GetDatabaseCreator(testDatabase); @@ -479,7 +479,7 @@ public class SqlServerDatabaseCreatorCreateTablesTest : SqlServerDatabaseCreator [InlineData(false, false)] public async Task Creates_schema_in_existing_database_test(bool async, bool ambientTransaction) { - using var testDatabase = SqlServerTestStore.GetOrCreateInitialized("ExistingBlogging" + (async ? "Async" : "")); + using var testDatabase = await SqlServerTestStore.GetOrCreateInitializedAsync("ExistingBlogging" + (async ? "Async" : "")); using var context = new BloggingContext(testDatabase); var creator = GetDatabaseCreator(context); @@ -648,7 +648,7 @@ await testDatabase.ExecuteScalarAsync( [InlineData(false)] public async Task Throws_if_database_already_exists(bool async) { - using var testDatabase = SqlServerTestStore.GetOrCreateInitialized("ExistingBlogging"); + using var testDatabase = await SqlServerTestStore.GetOrCreateInitializedAsync("ExistingBlogging"); var creator = GetDatabaseCreator(testDatabase); var ex = async @@ -680,7 +680,8 @@ protected static IExecutionStrategy GetExecutionStrategy(SqlServerTestStore test => new BloggingContext(testStore).GetService().Create(); // ReSharper disable once ClassNeverInstantiated.Local - private class TestSqlServerExecutionStrategyFactory(ExecutionStrategyDependencies dependencies) : SqlServerExecutionStrategyFactory(dependencies) + private class TestSqlServerExecutionStrategyFactory(ExecutionStrategyDependencies dependencies) + : SqlServerExecutionStrategyFactory(dependencies) { protected override IExecutionStrategy CreateDefaultStrategy(ExecutionStrategyDependencies dependencies) => new NonRetryingExecutionStrategy(dependencies); diff --git a/test/EFCore.SqlServer.FunctionalTests/SqlServerEndToEndTest.cs b/test/EFCore.SqlServer.FunctionalTests/SqlServerEndToEndTest.cs index e25e5a6e8cf..b97e8543014 100644 --- a/test/EFCore.SqlServer.FunctionalTests/SqlServerEndToEndTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/SqlServerEndToEndTest.cs @@ -28,9 +28,9 @@ public SqlServerEndToEndTest(SqlServerFixture fixture) } [ConditionalFact] - public void Can_use_decimal_and_byte_as_identity_columns() + public async Task Can_use_decimal_and_byte_as_identity_columns() { - using var testDatabase = SqlServerTestStore.CreateInitialized(DatabaseName); + 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" }; @@ -215,9 +215,9 @@ private class ByteAdNum } [ConditionalFact] // Issue #29931 - public void Can_use_SqlQuery_when_context_has_DbFunction() + public async Task Can_use_SqlQuery_when_context_has_DbFunction() { - using var testDatabase = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); var options = Fixture.CreateOptions(testDatabase); using (var context = new DbFunctionContext(options)) { @@ -255,9 +255,9 @@ private class RawResult } [ConditionalFact] - public void Can_use_string_enum_or_byte_array_as_key() + public async Task Can_use_string_enum_or_byte_array_as_key() { - using var testDatabase = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); var sNum1 = new SNum { TheWalrus = "I" }; var sNum2 = new SNum { TheWalrus = "Am" }; @@ -291,9 +291,9 @@ public void Can_use_string_enum_or_byte_array_as_key() } [ConditionalFact] - public void Can_remove_multiple_byte_array_as_key() + public async Task Can_remove_multiple_byte_array_as_key() { - using var testDatabase = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); var bNum1 = new BNum { TheWalrus = "Eggman" }; var bNum2 = new BNum { TheWalrus = "Eggmen" }; @@ -326,9 +326,9 @@ private class ENumContext(DbContextOptions options) : DbContext(options) } [ConditionalFact] - public void Can_add_table_splitting_dependent_after_principal() + public async Task Can_add_table_splitting_dependent_after_principal() { - using var testDatabase = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); var options = Fixture.CreateOptions(testDatabase); EvaluationAction evaluationAction = null; @@ -369,9 +369,9 @@ public void Can_add_table_splitting_dependent_after_principal() } [ConditionalFact] - public void Throws_when_adding_table_splitting_dependent_without_principal() + public async Task Throws_when_adding_table_splitting_dependent_without_principal() { - using var testDatabase = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); var options = Fixture.CreateOptions(testDatabase); using (var context = new ProjectContext(options)) @@ -463,7 +463,7 @@ private class BNum [ConditionalFact] public async Task Can_add_and_remove_entities_with_keys_of_different_type() { - using var testDatabase = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); var options = Fixture.CreateOptions(testDatabase); using (var context = new CompositeKeysDbContext(options)) @@ -513,9 +513,9 @@ private class Int64CompositeKeys } [ConditionalFact] - public void Can_insert_non_owner_principal_for_owned() + public async Task Can_insert_non_owner_principal_for_owned() { - using var testDatabase = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); var options = Fixture.CreateOptions(testDatabase); using (var context = new FileContext(options)) @@ -577,7 +577,7 @@ private sealed class FileSource [ConditionalFact] public async Task Can_insert_TPT_dependents_with_identity() { - using var testDatabase = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); var options = Fixture.CreateOptions(testDatabase); using (var context = new CarContext(options)) @@ -613,9 +613,9 @@ private class Ferrari : Car } [ConditionalFact] - public void Can_run_linq_query_on_entity_set() + public async Task Can_run_linq_query_on_entity_set() { - using var testStore = SqlServerTestStore.GetNorthwindStore(); + using var testStore = await SqlServerTestStore.GetNorthwindStoreAsync(); using var db = new NorthwindContext(Fixture.CreateOptions(testStore)); var results = db.Customers .Where(c => c.CompanyName.StartsWith("A")) @@ -635,9 +635,9 @@ public void Can_run_linq_query_on_entity_set() } [ConditionalFact] - public void Can_run_linq_query_on_entity_set_with_value_buffer_reader() + public async Task Can_run_linq_query_on_entity_set_with_value_buffer_reader() { - using var testStore = SqlServerTestStore.GetNorthwindStore(); + using var testStore = await SqlServerTestStore.GetNorthwindStoreAsync(); using var db = new NorthwindContext(Fixture.CreateOptions(testStore)); var results = db.Customers .Where(c => c.CompanyName.StartsWith("A")) @@ -657,9 +657,9 @@ public void Can_run_linq_query_on_entity_set_with_value_buffer_reader() } [ConditionalFact] - public void Can_enumerate_entity_set() + public async Task Can_enumerate_entity_set() { - using var testStore = SqlServerTestStore.GetNorthwindStore(); + using var testStore = await SqlServerTestStore.GetNorthwindStoreAsync(); using var db = new NorthwindContext(Fixture.CreateOptions(testStore)); var results = new List(); foreach (var item in db.Customers) @@ -675,7 +675,7 @@ public void Can_enumerate_entity_set() [ConditionalFact] public async Task Can_save_changes() { - using var testDatabase = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); var options = Fixture.CreateOptions(testDatabase); using (var db = new BloggingContext(options)) { @@ -748,7 +748,7 @@ public async Task Can_save_changes() [ConditionalFact] public async Task Can_save_changes_in_tracked_entities() { - using var testDatabase = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); int updatedId; int deletedId; int addedId; @@ -803,9 +803,9 @@ public async Task Can_save_changes_in_tracked_entities() } [ConditionalFact] - public void Can_track_an_entity_with_more_than_10_properties() + public async Task Can_track_an_entity_with_more_than_10_properties() { - using var testDatabase = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); var options = Fixture.CreateOptions(testDatabase); using (var context = new GameDbContext(options)) { @@ -832,9 +832,9 @@ public void Can_track_an_entity_with_more_than_10_properties() } [ConditionalFact] - public void Can_replace_identifying_FK_entity_with_many_to_many() + public async Task Can_replace_identifying_FK_entity_with_many_to_many() { - using var testDatabase = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); var options = Fixture.CreateOptions(testDatabase); using (var context = new SomeDbContext(options)) @@ -872,7 +872,7 @@ public void Can_replace_identifying_FK_entity_with_many_to_many() new object[] { 0, 1, 2, 3, 4, 7 }, 2, MemberType = typeof(DataGenerator))] - public void Can_insert_entities_with_generated_PKs(int studentCount, int courseCount) + public async Task Can_insert_entities_with_generated_PKs(int studentCount, int courseCount) { var students = new Student[] { @@ -937,7 +937,7 @@ public void Can_insert_entities_with_generated_PKs(int studentCount, int courseC new() { Title = "Literature", Credits = 4 } }; - using var testDatabase = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); var options = Fixture.CreateOptions(testDatabase); var nextCourse = 0; @@ -949,7 +949,7 @@ public void Can_insert_entities_with_generated_PKs(int studentCount, int courseC if (courseCount > 1) { students[i].Courses.Add(courses[nextCourse++]); - if(nextCourse >= courseCount) + if (nextCourse >= courseCount) { nextCourse = 0; } @@ -960,6 +960,7 @@ public void Can_insert_entities_with_generated_PKs(int studentCount, int courseC nextCourse = 0; } } + context.Students.Add(students[i]); } @@ -968,33 +969,35 @@ public void Can_insert_entities_with_generated_PKs(int studentCount, int courseC context.Courses.Add(courses[i]); } - Assert.All(context.Enrollments.Local, e => - { - var entry = context.Entry(e); - var student = e.Student; - var course = e.Course; - Assert.Equal(student.Id, e.StudentId); - Assert.Equal(course.Id, e.CourseId); - Assert.Equal(context.Entry(student).Property(e => e.Id).CurrentValue, entry.Property(e => e.StudentId).CurrentValue); - Assert.Equal(context.Entry(course).Property(e => e.Id).CurrentValue, entry.Property(e => e.CourseId).CurrentValue); - Assert.True(entry.Property(e => e.StudentId).IsTemporary); - Assert.True(entry.Property(e => e.CourseId).IsTemporary); - Assert.True(context.Entry(student).Property(e => e.Id).IsTemporary); - Assert.True(context.Entry(course).Property(e => e.Id).IsTemporary); - }); + Assert.All( + context.Enrollments.Local, e => + { + var entry = context.Entry(e); + var student = e.Student; + var course = e.Course; + Assert.Equal(student.Id, e.StudentId); + Assert.Equal(course.Id, e.CourseId); + Assert.Equal(context.Entry(student).Property(e => e.Id).CurrentValue, entry.Property(e => e.StudentId).CurrentValue); + Assert.Equal(context.Entry(course).Property(e => e.Id).CurrentValue, entry.Property(e => e.CourseId).CurrentValue); + Assert.True(entry.Property(e => e.StudentId).IsTemporary); + Assert.True(entry.Property(e => e.CourseId).IsTemporary); + Assert.True(context.Entry(student).Property(e => e.Id).IsTemporary); + Assert.True(context.Entry(course).Property(e => e.Id).IsTemporary); + }); context.SaveChanges(); - Assert.All(context.Enrollments.Local, e => - { - var entry = context.Entry(e); - var student = e.Student; - var course = e.Course; - Assert.Equal(student.Id, e.StudentId); - Assert.Equal(course.Id, e.CourseId); - Assert.False(entry.Property(e => e.StudentId).IsTemporary); - Assert.False(entry.Property(e => e.CourseId).IsTemporary); - }); + Assert.All( + context.Enrollments.Local, e => + { + var entry = context.Entry(e); + var student = e.Student; + var course = e.Course; + Assert.Equal(student.Id, e.StudentId); + Assert.Equal(course.Id, e.CourseId); + Assert.False(entry.Property(e => e.StudentId).IsTemporary); + Assert.False(entry.Property(e => e.CourseId).IsTemporary); + }); } using (var context = new UniversityContext(options)) @@ -1003,13 +1006,14 @@ public void Can_insert_entities_with_generated_PKs(int studentCount, int courseC Assert.Equal(courseCount, context.Courses.ToList().Count()); var enrollments = context.Enrollments.Include(e => e.Course).Include(e => e.Student).ToList(); - Assert.All(enrollments, e => - { - var student = e.Student; - var course = e.Course; - Assert.Equal(student.Id, e.StudentId); - Assert.Equal(course.Id, e.CourseId); - }); + Assert.All( + enrollments, e => + { + var student = e.Student; + var course = e.Course; + Assert.Equal(student.Id, e.StudentId); + Assert.Equal(course.Id, e.CourseId); + }); } } @@ -1184,9 +1188,9 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) } [ConditionalFact] - public void Adding_an_item_to_a_collection_marks_it_as_modified() + public async Task Adding_an_item_to_a_collection_marks_it_as_modified() { - using var testDatabase = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); var options = Fixture.CreateOptions(testDatabase); using var context = new GameDbContext(options); @@ -1209,9 +1213,9 @@ public void Adding_an_item_to_a_collection_marks_it_as_modified() } [ConditionalFact] - public void Can_set_reference_twice() + public async Task Can_set_reference_twice() { - using var testDatabase = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); var options = Fixture.CreateOptions(testDatabase); using (var context = new GameDbContext(options)) @@ -1249,9 +1253,9 @@ public void Can_set_reference_twice() } [ConditionalFact] - public void Can_include_on_loaded_entity() + public async Task Can_include_on_loaded_entity() { - using var testDatabase = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); var options = Fixture.CreateOptions(testDatabase); using (var context = new GameDbContext(options)) @@ -1479,7 +1483,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) [ConditionalFact] public async Task Tracking_entities_asynchronously_returns_tracked_entities_back() { - using var testStore = SqlServerTestStore.GetNorthwindStore(); + using var testStore = await SqlServerTestStore.GetNorthwindStoreAsync(); using var db = new NorthwindContext(Fixture.CreateOptions(testStore)); var customer = await db.Customers.OrderBy(c => c.CustomerID).FirstOrDefaultAsync(); @@ -1493,7 +1497,7 @@ 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 = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); var options = Fixture.CreateOptions(testStore); await testStore.ExecuteNonQueryAsync("CREATE SCHEMA Apple"); @@ -1560,7 +1564,7 @@ public Task Can_round_trip_changes_with_changed_only_notification_entities() private async Task RoundTripChanges() where TBlog : class, IBlog, new() { - using var testDatabase = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testDatabase = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); var options = Fixture.CreateOptions(testDatabase); int blog1Id; diff --git a/test/EFCore.SqlServer.FunctionalTests/SqlServerQueryTriggersTest.cs b/test/EFCore.SqlServer.FunctionalTests/SqlServerQueryTriggersTest.cs index 504b450d12a..aba2e2b5383 100644 --- a/test/EFCore.SqlServer.FunctionalTests/SqlServerQueryTriggersTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/SqlServerQueryTriggersTest.cs @@ -7,7 +7,8 @@ namespace Microsoft.EntityFrameworkCore; #nullable disable -public class SqlServerQueryTriggersTest(SqlServerQueryTriggersTest.SqlServerTriggersFixture fixture) : IClassFixture +public class SqlServerQueryTriggersTest(SqlServerQueryTriggersTest.SqlServerTriggersFixture fixture) + : IClassFixture { private SqlServerTriggersFixture Fixture { get; } = fixture; @@ -110,11 +111,11 @@ protected override string StoreName protected override ITestStoreFactory TestStoreFactory => SqlServerTestStoreFactory.Instance; - protected override void Seed(DbContext context) + protected override async Task SeedAsync(DbContext context) { - context.Database.EnsureCreatedResiliently(); + await context.Database.EnsureCreatedResilientlyAsync(); - context.Database.ExecuteSqlRaw( + await context.Database.ExecuteSqlRawAsync( @" CREATE TRIGGER TRG_InsertUpdateProduct ON UpdatedProducts diff --git a/test/EFCore.SqlServer.FunctionalTests/SqlServerTriggersTest.cs b/test/EFCore.SqlServer.FunctionalTests/SqlServerTriggersTest.cs index 79774f4af38..78638b3abeb 100644 --- a/test/EFCore.SqlServer.FunctionalTests/SqlServerTriggersTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/SqlServerTriggersTest.cs @@ -8,7 +8,8 @@ namespace Microsoft.EntityFrameworkCore; #nullable disable -public class SqlServerTriggersTest(SqlServerTriggersTest.SqlServerTriggersFixture fixture) : IClassFixture +public class SqlServerTriggersTest(SqlServerTriggersTest.SqlServerTriggersFixture fixture) + : IClassFixture { private SqlServerTriggersFixture Fixture { get; } = fixture; @@ -143,11 +144,11 @@ protected override string StoreName protected override ITestStoreFactory TestStoreFactory => SqlServerTestStoreFactory.Instance; - protected override void Seed(PoolableDbContext context) + protected override async Task SeedAsync(PoolableDbContext context) { - context.Database.EnsureCreatedResiliently(); + await context.Database.EnsureCreatedResilientlyAsync(); - context.Database.ExecuteSqlRaw( + await context.Database.ExecuteSqlRawAsync( @" CREATE TRIGGER TRG_InsertProduct ON Products @@ -161,7 +162,7 @@ INSERT INTO ProductBackups SELECT * FROM INSERTED; END"); - context.Database.ExecuteSqlRaw( + await context.Database.ExecuteSqlRawAsync( @" CREATE TRIGGER TRG_UpdateProduct ON Products @@ -179,7 +180,7 @@ INNER JOIN Products p WHERE p.Id IN(SELECT INSERTED.Id FROM INSERTED); END"); - context.Database.ExecuteSqlRaw( + await context.Database.ExecuteSqlRawAsync( @" CREATE TRIGGER TRG_DeleteProduct ON Products diff --git a/test/EFCore.SqlServer.FunctionalTests/SqlServerTypeAliasTest.cs b/test/EFCore.SqlServer.FunctionalTests/SqlServerTypeAliasTest.cs index 8d82c0b5c5e..132022c41c4 100644 --- a/test/EFCore.SqlServer.FunctionalTests/SqlServerTypeAliasTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/SqlServerTypeAliasTest.cs @@ -12,9 +12,9 @@ public class SqlServerTypeAliasTest(SqlServerFixture fixture) : IClassFixture modelBuilder) : ContextBase(databaseName, modelBuilder); [ConditionalFact] - public void Insert_with_sequence_HiLo() + public async Task Insert_with_sequence_HiLo() { - using var testStore = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); using (var context = new BlogContextHiLo(testStore.Name, OnModelCreating)) { context.Database.EnsureCreatedResiliently(); @@ -98,9 +98,9 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) } [ConditionalFact] - public void Insert_with_key_sequence() + public async Task Insert_with_key_sequence() { - using var testStore = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); using (var context = new BlogContextKeySequence(testStore.Name, OnModelCreating)) { context.Database.EnsureCreatedResiliently(); @@ -140,9 +140,9 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) } [ConditionalFact] - public void Insert_with_non_key_sequence() + public async Task Insert_with_non_key_sequence() { - using var testStore = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); using (var context = new BlogContextNonKeySequence(testStore.Name, OnModelCreating)) { context.Database.EnsureCreatedResiliently(); @@ -179,9 +179,9 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) } [ConditionalFact] - public void Insert_with_default_value_from_sequence() + public async Task Insert_with_default_value_from_sequence() { - using var testStore = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); using (var context = new BlogContextDefaultValue(testStore.Name, OnModelCreating)) { context.Database.EnsureCreatedResiliently(); @@ -234,7 +234,8 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) } } - public class BlogContextDefaultValueNoMigrations(string databaseName, Action modelBuilder) : ContextBase(databaseName, modelBuilder) + public class BlogContextDefaultValueNoMigrations(string databaseName, Action modelBuilder) + : ContextBase(databaseName, modelBuilder) { protected override void OnModelCreating(ModelBuilder modelBuilder) { @@ -248,9 +249,9 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) } [ConditionalFact] - public void Insert_with_default_string_value_from_sequence() + public async Task Insert_with_default_string_value_from_sequence() { - using var testStore = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); using (var context = new BlogContextStringDefaultValue(testStore.Name, OnModelCreating, StringSentinel)) { context.Database.EnsureCreatedResiliently(); @@ -271,7 +272,8 @@ public void Insert_with_default_string_value_from_sequence() } } - public class BlogContextStringDefaultValue(string databaseName, Action modelBuilder, string stringSentinel) : ContextBase(databaseName, modelBuilder) + public class BlogContextStringDefaultValue(string databaseName, Action modelBuilder, string stringSentinel) + : ContextBase(databaseName, modelBuilder) { private readonly string _stringSentinel = stringSentinel; @@ -300,9 +302,9 @@ public class BlogWithStringKey } [ConditionalFact] - public void Insert_with_key_default_value_from_sequence() + public async Task Insert_with_key_default_value_from_sequence() { - using var testStore = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); using (var context = new BlogContextKeyColumnWithDefaultValue(testStore.Name, OnModelCreating)) { context.Database.EnsureCreatedResiliently(); @@ -321,7 +323,8 @@ public void Insert_with_key_default_value_from_sequence() } } - public class BlogContextKeyColumnWithDefaultValue(string databaseName, Action modelBuilder) : ContextBase(databaseName, modelBuilder) + public class BlogContextKeyColumnWithDefaultValue(string databaseName, Action modelBuilder) + : ContextBase(databaseName, modelBuilder) { protected override void OnModelCreating(ModelBuilder modelBuilder) { @@ -340,9 +343,9 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) } [ConditionalFact] - public void Insert_uint_to_Identity_column_using_value_converter() + public async Task Insert_uint_to_Identity_column_using_value_converter() { - using var testStore = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); using (var context = new BlogContextUIntToIdentityUsingValueConverter(testStore.Name, OnModelCreating, UIntSentinel)) { context.Database.EnsureCreatedResiliently(); @@ -363,7 +366,8 @@ public void Insert_uint_to_Identity_column_using_value_converter() } } - public class BlogContextUIntToIdentityUsingValueConverter(string databaseName, Action modelBuilder, uint uintSentinel) : ContextBase(databaseName, modelBuilder) + public class BlogContextUIntToIdentityUsingValueConverter(string databaseName, Action modelBuilder, uint uintSentinel) + : ContextBase(databaseName, modelBuilder) { private readonly uint _uintSentinel = uintSentinel; @@ -388,9 +392,9 @@ public class BlogWithUIntKey } [ConditionalFact] - public void Insert_int_enum_to_Identity_column() + public async Task Insert_int_enum_to_Identity_column() { - using var testStore = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); using (var context = new BlogContextIntEnumToIdentity(testStore.Name, OnModelCreating, IntKeySentinel)) { context.Database.EnsureCreatedResiliently(); @@ -411,7 +415,8 @@ public void Insert_int_enum_to_Identity_column() } } - public class BlogContextIntEnumToIdentity(string databaseName, Action modelBuilder, IntKey sentinel) : ContextBase(databaseName, modelBuilder) + public class BlogContextIntEnumToIdentity(string databaseName, Action modelBuilder, IntKey sentinel) + : ContextBase(databaseName, modelBuilder) { private readonly IntKey _sentinel = sentinel; @@ -443,9 +448,9 @@ public enum IntKey } [ConditionalFact] - public void Insert_ulong_enum_to_Identity_column() + public async Task Insert_ulong_enum_to_Identity_column() { - using var testStore = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); using (var context = new BlogContextULongEnumToIdentity(testStore.Name, OnModelCreating, ULongKeySentinel)) { context.Database.EnsureCreatedResiliently(); @@ -466,7 +471,8 @@ public void Insert_ulong_enum_to_Identity_column() } } - public class BlogContextULongEnumToIdentity(string databaseName, Action modelBuilder, ULongKey sentinel) : ContextBase(databaseName, modelBuilder) + public class BlogContextULongEnumToIdentity(string databaseName, Action modelBuilder, ULongKey sentinel) + : ContextBase(databaseName, modelBuilder) { private readonly ULongKey _sentinel = sentinel; @@ -497,9 +503,9 @@ public enum ULongKey : ulong } [ConditionalFact] - public void Insert_string_to_Identity_column_using_value_converter() + public async Task Insert_string_to_Identity_column_using_value_converter() { - using var testStore = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); using (var context = new BlogContextStringToIdentityUsingValueConverter(testStore.Name, OnModelCreating, StringSentinel)) { context.Database.EnsureCreatedResiliently(); @@ -520,7 +526,8 @@ public void Insert_string_to_Identity_column_using_value_converter() } } - public class BlogContextStringToIdentityUsingValueConverter(string databaseName, Action modelBuilder, string sentinel) : ContextBase(databaseName, modelBuilder) + public class BlogContextStringToIdentityUsingValueConverter(string databaseName, Action modelBuilder, string sentinel) + : ContextBase(databaseName, modelBuilder) { private readonly string _sentinel = sentinel; @@ -546,9 +553,9 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) } [ConditionalFact] - public void Insert_with_explicit_non_default_keys() + public async Task Insert_with_explicit_non_default_keys() { - using var testStore = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); using (var context = new BlogContextNoKeyGeneration(testStore.Name, OnModelCreating)) { context.Database.EnsureCreatedResiliently(); @@ -568,7 +575,8 @@ public void Insert_with_explicit_non_default_keys() } } - public class BlogContextNoKeyGeneration(string databaseName, Action modelBuilder) : ContextBase(databaseName, modelBuilder) + public class BlogContextNoKeyGeneration(string databaseName, Action modelBuilder) + : ContextBase(databaseName, modelBuilder) { protected override void OnModelCreating(ModelBuilder modelBuilder) { @@ -582,9 +590,9 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) } [ConditionalFact] - public void Insert_with_explicit_with_default_keys() + public async Task Insert_with_explicit_with_default_keys() { - using var testStore = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); using (var context = new BlogContextNoKeyGenerationNullableKey(testStore.Name, OnModelCreating, NullableIntSentinel)) { context.Database.EnsureCreatedResiliently(); @@ -605,7 +613,8 @@ public void Insert_with_explicit_with_default_keys() } } - public class BlogContextNoKeyGenerationNullableKey(string databaseName, Action modelBuilder, int? sentinel) : ContextBase(databaseName, modelBuilder) + public class BlogContextNoKeyGenerationNullableKey(string databaseName, Action modelBuilder, int? sentinel) + : ContextBase(databaseName, modelBuilder) { private readonly int? _sentinel = sentinel; @@ -622,9 +631,9 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) } [ConditionalFact] - public void Insert_with_non_key_default_value() + public async Task Insert_with_non_key_default_value() { - using var testStore = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); using (var context = new BlogContextNonKeyDefaultValue(testStore.Name, OnModelCreating)) { @@ -692,9 +701,9 @@ public void Insert_with_non_key_default_value() [ConditionalFact] [SqlServerCondition(SqlServerCondition.SupportsSqlClr)] - public void Insert_with_non_key_default_spatial_value() + public async Task Insert_with_non_key_default_spatial_value() { - using var testStore = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); using (var context = new BlogContextNonKeyDefaultSpatialValue(testStore.Name, OnModelCreating)) { @@ -760,7 +769,8 @@ public void Insert_with_non_key_default_spatial_value() } } - public class BlogContextNonKeyDefaultValue(string databaseName, Action modelBuilder) : ContextBase(databaseName, modelBuilder) + public class BlogContextNonKeyDefaultValue(string databaseName, Action modelBuilder) + : ContextBase(databaseName, modelBuilder) { protected override void OnModelCreating(ModelBuilder modelBuilder) { @@ -783,7 +793,8 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) } } - public class BlogContextNonKeyDefaultSpatialValue(string databaseName, Action modelBuilder) : ContextBase(databaseName, modelBuilder) + public class BlogContextNonKeyDefaultSpatialValue(string databaseName, Action modelBuilder) + : ContextBase(databaseName, modelBuilder) { protected override void OnModelCreating(ModelBuilder modelBuilder) { @@ -807,9 +818,9 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) } [ConditionalFact] - public void Insert_with_non_key_default_value_readonly() + public async Task Insert_with_non_key_default_value_readonly() { - using var testStore = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); using (var context = new BlogContextNonKeyReadOnlyDefaultValue(testStore.Name, OnModelCreating, IntSentinel, DateTimeSentinel)) { context.Database.EnsureCreatedResiliently(); @@ -884,9 +895,9 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) } [ConditionalFact] - public void Insert_and_update_with_computed_column() + public async Task Insert_and_update_with_computed_column() { - using var testStore = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); using (var context = new BlogContextComputedColumn(testStore.Name, OnModelCreating, IntSentinel, StringSentinel)) { context.Database.EnsureCreatedResiliently(); @@ -919,7 +930,8 @@ public void Insert_and_update_with_computed_column() } } - public class BlogContextComputedColumn(string databaseName, Action modelBuilder, int intSentinel, string stringSentinel) : ContextBase(databaseName, modelBuilder) + public class BlogContextComputedColumn(string databaseName, Action modelBuilder, int intSentinel, string stringSentinel) + : ContextBase(databaseName, modelBuilder) { private readonly int _intSentinel = intSentinel; private readonly string _stringSentinel = stringSentinel; @@ -960,9 +972,9 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) // #6044 [ConditionalFact] - public void Insert_and_update_with_computed_column_with_function() + public async Task Insert_and_update_with_computed_column_with_function() { - using var testStore = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); using (var context = new BlogContextComputedColumnWithFunction(testStore.Name, OnModelCreating, IntSentinel, StringSentinel)) { context.Database.ExecuteSqlRaw @@ -1035,20 +1047,21 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) // #6044 [ConditionalFact] - public void Insert_and_update_with_computed_column_with_querying_function() + public async Task Insert_and_update_with_computed_column_with_querying_function() { SqlServerTestStore testStore = null; try { - testStore = SqlServerTestStore.CreateInitialized(DatabaseName); - using (var context = new BlogContextComputedColumnWithTriggerMetadata(testStore.Name, OnModelCreating, IntSentinel, StringSentinel)) - { - context.GetService().CreateTables(); + testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); + using (var context = new BlogContextComputedColumnWithTriggerMetadata( + testStore.Name, OnModelCreating, IntSentinel, StringSentinel)) + { + context.GetService().CreateTables(); - context.Database.ExecuteSqlRaw("ALTER TABLE dbo.FullNameBlogs DROP COLUMN FullName;"); + context.Database.ExecuteSqlRaw("ALTER TABLE dbo.FullNameBlogs DROP COLUMN FullName;"); - context.Database.ExecuteSqlRaw( - @"CREATE FUNCTION [dbo].[GetFullName](@Id int) + context.Database.ExecuteSqlRaw( + @"CREATE FUNCTION [dbo].[GetFullName](@Id int) RETURNS nvarchar(max) WITH SCHEMABINDING AS BEGIN DECLARE @FullName nvarchar(max); @@ -1056,8 +1069,8 @@ RETURNS nvarchar(max) WITH SCHEMABINDING AS RETURN @FullName END"); - context.Database.ExecuteSqlRaw("ALTER TABLE dbo.FullNameBlogs ADD FullName AS [dbo].[GetFullName]([Id]); "); - } + context.Database.ExecuteSqlRaw("ALTER TABLE dbo.FullNameBlogs ADD FullName AS [dbo].[GetFullName]([Id]); "); + } using (var context = new BlogContextComputedColumnWithTriggerMetadata( testStore.Name, OnModelCreating, IntSentinel, StringSentinel)) @@ -1131,7 +1144,7 @@ RETURN @FullName [MemberData(nameof(IsAsyncData))] public async Task Insert_with_computed_column_with_function_without_metadata_configuration(bool async) { - using var testStore = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); using (var context = new BlogContextComputedColumn(testStore.Name, OnModelCreating, IntSentinel, StringSentinel)) { context.GetService().CreateTables(); @@ -1181,7 +1194,7 @@ 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 = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); using (var context = new BlogContextComputedColumn(testStore.Name, OnModelCreating, IntSentinel, StringSentinel)) { context.GetService().CreateTables(); @@ -1220,9 +1233,9 @@ ON [FullNameBlogs] } [ConditionalFact] - public void Insert_with_client_generated_GUID_key() + public async Task Insert_with_client_generated_GUID_key() { - using var testStore = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); Guid afterSave; using (var context = new BlogContextClientGuidKey(testStore.Name, OnModelCreating, GuidSentinel)) { @@ -1257,7 +1270,8 @@ public void Insert_with_client_generated_GUID_key() } } - public class BlogContextClientGuidKey(string databaseName, Action modelBuilder, Guid sentinel) : ContextBase(databaseName, modelBuilder) + public class BlogContextClientGuidKey(string databaseName, Action modelBuilder, Guid sentinel) + : ContextBase(databaseName, modelBuilder) { private readonly Guid _sentinel = sentinel; @@ -1277,9 +1291,9 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) [ConditionalFact] [SqlServerCondition(SqlServerCondition.IsNotSqlAzure)] - public void Insert_with_ValueGeneratedOnAdd_GUID_nonkey_property_throws() + public async Task Insert_with_ValueGeneratedOnAdd_GUID_nonkey_property_throws() { - using var testStore = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); using var context = new BlogContextClientGuidNonKey(testStore.Name, OnModelCreating, GuidSentinel); context.Database.EnsureCreatedResiliently(); @@ -1298,7 +1312,8 @@ public void Insert_with_ValueGeneratedOnAdd_GUID_nonkey_property_throws() Assert.Single(updateException.Entries); } - public class BlogContextClientGuidNonKey(string databaseName, Action modelBuilder, Guid sentinel) : ContextBase(databaseName, modelBuilder) + public class BlogContextClientGuidNonKey(string databaseName, Action modelBuilder, Guid sentinel) + : ContextBase(databaseName, modelBuilder) { private readonly Guid _sentinel = sentinel; @@ -1316,9 +1331,9 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) } [ConditionalFact] - public void Insert_with_server_generated_GUID_key() + public async Task Insert_with_server_generated_GUID_key() { - using var testStore = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); Guid afterSave; using (var context = new BlogContextServerGuidKey(testStore.Name, OnModelCreating, GuidSentinel)) { @@ -1355,7 +1370,8 @@ public void Insert_with_server_generated_GUID_key() } } - public class BlogContextServerGuidKey(string databaseName, Action modelBuilder, Guid sentinel) : ContextBase(databaseName, modelBuilder) + public class BlogContextServerGuidKey(string databaseName, Action modelBuilder, Guid sentinel) + : ContextBase(databaseName, modelBuilder) { private readonly Guid _sentinel = sentinel; @@ -1375,9 +1391,9 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) // Negative cases [ConditionalFact] - public void Insert_with_explicit_non_default_keys_by_default() + public async Task Insert_with_explicit_non_default_keys_by_default() { - using var testStore = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); using var context = new BlogContext(testStore.Name, OnModelCreating); context.Database.EnsureCreatedResiliently(); @@ -1392,9 +1408,9 @@ public void Insert_with_explicit_non_default_keys_by_default() } [ConditionalFact] - public void Insert_with_explicit_default_keys() + public async Task Insert_with_explicit_default_keys() { - using var testStore = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); using var context = new BlogContext(testStore.Name, OnModelCreating); context.Database.EnsureCreatedResiliently(); @@ -1412,9 +1428,9 @@ public void Insert_with_explicit_default_keys() public class BlogContext(string databaseName, Action modelBuilder) : ContextBase(databaseName, modelBuilder); [ConditionalFact] - public void Insert_with_implicit_default_keys() + public async Task Insert_with_implicit_default_keys() { - using var testStore = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); using (var context = new BlogContextSpecifyKeysUsingDefault(testStore.Name, OnModelCreating, IntSentinel)) { context.Database.EnsureCreatedResiliently(); @@ -1434,7 +1450,8 @@ public void Insert_with_implicit_default_keys() } } - public class BlogContextSpecifyKeysUsingDefault(string databaseName, Action modelBuilder, int sentinel) : ContextBase(databaseName, modelBuilder) + public class BlogContextSpecifyKeysUsingDefault(string databaseName, Action modelBuilder, int sentinel) + : ContextBase(databaseName, modelBuilder) { private readonly int _sentinel = sentinel; @@ -1451,9 +1468,9 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) } [ConditionalFact] - public void Insert_explicit_value_throws_when_readonly_sequence_before_save() + public async Task Insert_explicit_value_throws_when_readonly_sequence_before_save() { - using var testStore = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); using var context = new BlogContextReadOnlySequenceKeyColumnWithDefaultValue(testStore.Name, OnModelCreating, IntSentinel); context.Database.EnsureCreatedResiliently(); @@ -1467,7 +1484,8 @@ public void Insert_explicit_value_throws_when_readonly_sequence_before_save() Assert.Throws(() => context.SaveChanges()).Message); } - public class BlogContextReadOnlySequenceKeyColumnWithDefaultValue(string databaseName, Action modelBuilder, int sentinel) : ContextBase(databaseName, modelBuilder) + public class BlogContextReadOnlySequenceKeyColumnWithDefaultValue(string databaseName, Action modelBuilder, int sentinel) + : ContextBase(databaseName, modelBuilder) { private readonly int _sentinel = sentinel; @@ -1488,9 +1506,9 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) } [ConditionalFact] - public void Insert_explicit_value_throws_when_readonly_before_save() + public async Task Insert_explicit_value_throws_when_readonly_before_save() { - using var testStore = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); using var context = new BlogContextNonKeyReadOnlyDefaultValue(testStore.Name, OnModelCreating, IntSentinel, DateTimeSentinel); context.Database.EnsureCreatedResiliently(); @@ -1516,9 +1534,9 @@ public void Insert_explicit_value_throws_when_readonly_before_save() } [ConditionalFact] - public void Insert_explicit_value_into_computed_column() + public async Task Insert_explicit_value_into_computed_column() { - using var testStore = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); using var context = new BlogContextComputedColumn(testStore.Name, OnModelCreating, IntSentinel, StringSentinel); context.Database.EnsureCreatedResiliently(); @@ -1539,9 +1557,9 @@ public void Insert_explicit_value_into_computed_column() } [ConditionalFact] - public void Update_explicit_value_in_computed_column() + public async Task Update_explicit_value_in_computed_column() { - using var testStore = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); using (var context = new BlogContextComputedColumn(testStore.Name, OnModelCreating, IntSentinel, StringSentinel)) { context.Database.EnsureCreatedResiliently(); @@ -1574,9 +1592,9 @@ public void Update_explicit_value_in_computed_column() // Concurrency [ConditionalFact] - public void Resolve_concurrency() + public async Task Resolve_concurrency() { - using var testStore = SqlServerTestStore.CreateInitialized(DatabaseName); + using var testStore = await SqlServerTestStore.CreateInitializedAsync(DatabaseName); using var context = new BlogContextConcurrencyWithRowversion(testStore.Name, OnModelCreating, IntSentinel, TimestampSentinel); context.Database.EnsureCreatedResiliently(); diff --git a/test/EFCore.SqlServer.FunctionalTests/StoreGeneratedFixupSqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/StoreGeneratedFixupSqlServerTest.cs index 6a3545c803c..ad983e50b9b 100644 --- a/test/EFCore.SqlServer.FunctionalTests/StoreGeneratedFixupSqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/StoreGeneratedFixupSqlServerTest.cs @@ -7,13 +7,14 @@ namespace Microsoft.EntityFrameworkCore; #nullable disable -public class StoreGeneratedFixupSqlServerTest(StoreGeneratedFixupSqlServerTest.StoreGeneratedFixupSqlServerFixture fixture) : StoreGeneratedFixupRelationalTestBase< - StoreGeneratedFixupSqlServerTest.StoreGeneratedFixupSqlServerFixture>(fixture) +public class StoreGeneratedFixupSqlServerTest(StoreGeneratedFixupSqlServerTest.StoreGeneratedFixupSqlServerFixture fixture) + : StoreGeneratedFixupRelationalTestBase< + StoreGeneratedFixupSqlServerTest.StoreGeneratedFixupSqlServerFixture>(fixture) { [ConditionalFact] - public void Temp_values_are_replaced_on_save() - => ExecuteWithStrategyInTransaction( - context => + public Task Temp_values_are_replaced_on_save() + => ExecuteWithStrategyInTransactionAsync( + async context => { var entry = context.Add(new TestTemp()); @@ -22,7 +23,7 @@ public void Temp_values_are_replaced_on_save() var tempValue = entry.Property(e => e.Id).CurrentValue; - context.SaveChanges(); + await context.SaveChangesAsync(); Assert.False(entry.Property(e => e.Id).IsTemporary); Assert.NotEqual(tempValue, entry.Property(e => e.Id).CurrentValue); diff --git a/test/EFCore.SqlServer.FunctionalTests/StoreGeneratedSqlServerTestBase.cs b/test/EFCore.SqlServer.FunctionalTests/StoreGeneratedSqlServerTestBase.cs index 2b9e30cd9bc..eb52642dfa6 100644 --- a/test/EFCore.SqlServer.FunctionalTests/StoreGeneratedSqlServerTestBase.cs +++ b/test/EFCore.SqlServer.FunctionalTests/StoreGeneratedSqlServerTestBase.cs @@ -298,11 +298,11 @@ protected class LongToDecimalDependentOptional } [ConditionalFact] - public virtual void Insert_update_and_delete_with_long_to_decimal_conversion() + public virtual Task Insert_update_and_delete_with_long_to_decimal_conversion() { var id1 = 0L; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var principal1 = context.Add( new LongToDecimalPrincipal @@ -313,7 +313,7 @@ public virtual void Insert_update_and_delete_with_long_to_decimal_conversion() RequiredDependents = { new LongToDecimalDependentRequired(), new LongToDecimalDependentRequired() } }).Entity; - context.SaveChanges(); + await context.SaveChangesAsync(); id1 = principal1.Id; Assert.NotEqual(0L, id1); @@ -337,14 +337,13 @@ public virtual void Insert_update_and_delete_with_long_to_decimal_conversion() Assert.Same(principal1, dependent.Principal); Assert.Equal(id1, dependent.PrincipalId); } - }, - context => + }, async context => { - var principal1 = context.Set() + var principal1 = await context.Set() .Include(e => e.Dependents) .Include(e => e.OptionalDependents) .Include(e => e.RequiredDependents) - .Single(); + .SingleAsync(); Assert.Equal(principal1.Id, id1); foreach (var dependent in principal1.Dependents) @@ -369,21 +368,20 @@ public virtual void Insert_update_and_delete_with_long_to_decimal_conversion() principal1.OptionalDependents.Remove(principal1.OptionalDependents.First()); principal1.RequiredDependents.Remove(principal1.RequiredDependents.First()); - context.SaveChanges(); - }, - context => + await context.SaveChangesAsync(); + }, async context => { - var dependents1 = context.Set().Include(e => e.Principal).ToList(); + var dependents1 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Equal(2, dependents1.Count); Assert.Null( context.Entry(dependents1.Single(e => e.Principal == null)) .Property("PrincipalId").CurrentValue); - var optionalDependents1 = context.Set().Include(e => e.Principal).ToList(); + var optionalDependents1 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Equal(2, optionalDependents1.Count); Assert.Null(optionalDependents1.Single(e => e.Principal == null).PrincipalId); - var requiredDependents1 = context.Set().Include(e => e.Principal).ToList(); + var requiredDependents1 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Single(requiredDependents1); context.Remove(dependents1.Single(e => e.Principal != null)); @@ -391,24 +389,23 @@ public virtual void Insert_update_and_delete_with_long_to_decimal_conversion() context.Remove(requiredDependents1.Single()); context.Remove(requiredDependents1.Single().Principal); - context.SaveChanges(); - }, - context => + await context.SaveChangesAsync(); + }, async context => { - Assert.Equal(1, context.Set().Count()); - Assert.Equal(1, context.Set().Count()); - Assert.Equal(0, context.Set().Count()); + Assert.Equal(1, await context.Set().CountAsync()); + Assert.Equal(1, await context.Set().CountAsync()); + Assert.Equal(0, await context.Set().CountAsync()); }); } [ConditionalFact] - public virtual void Insert_update_and_delete_with_wrapped_int_key_using_hi_lo() + public virtual Task Insert_update_and_delete_with_wrapped_int_key_using_hi_lo() { var id1 = 0; var id2 = 0; var id3 = 0; - ExecuteWithStrategyInTransaction( - context => + return ExecuteWithStrategyInTransactionAsync( + async context => { var principal1 = context.Add( new WrappedIntHiLoClassPrincipal @@ -449,7 +446,7 @@ public virtual void Insert_update_and_delete_with_wrapped_int_key_using_hi_lo() } }).Entity; - context.SaveChanges(); + await context.SaveChangesAsync(); id1 = principal1.Id.Value; Assert.NotEqual(0, id1); @@ -519,14 +516,13 @@ public virtual void Insert_update_and_delete_with_wrapped_int_key_using_hi_lo() Assert.Same(principal3, dependent.Principal); Assert.Equal(id3, dependent.PrincipalId.Value); } - }, - context => + }, async context => { - var principal1 = context.Set() + var principal1 = await context.Set() .Include(e => e.Dependents) .Include(e => e.OptionalDependents) .Include(e => e.RequiredDependents) - .Single(); + .SingleAsync(); Assert.Equal(principal1.Id.Value, id1); foreach (var dependent in principal1.Dependents) @@ -547,11 +543,11 @@ public virtual void Insert_update_and_delete_with_wrapped_int_key_using_hi_lo() Assert.Equal(id1, dependent.PrincipalId.Value); } - var principal2 = context.Set() + var principal2 = await context.Set() .Include(e => e.Dependents) .Include(e => e.OptionalDependents) .Include(e => e.RequiredDependents) - .Single(); + .SingleAsync(); Assert.Equal(principal2.Id.Value, id2); foreach (var dependent in principal2.Dependents) @@ -572,11 +568,11 @@ public virtual void Insert_update_and_delete_with_wrapped_int_key_using_hi_lo() Assert.Equal(id2, dependent.PrincipalId.Value); } - var principal3 = context.Set() + var principal3 = await context.Set() .Include(e => e.Dependents) .Include(e => e.OptionalDependents) .Include(e => e.RequiredDependents) - .Single(); + .SingleAsync(); Assert.Equal(principal3.Id.Value, id3); foreach (var dependent in principal3.Dependents) @@ -609,47 +605,50 @@ public virtual void Insert_update_and_delete_with_wrapped_int_key_using_hi_lo() principal2.RequiredDependents.Remove(principal2.RequiredDependents.First()); principal3.RequiredDependents.Remove(principal3.RequiredDependents.First()); - context.SaveChanges(); - }, - context => + await context.SaveChangesAsync(); + }, async context => { - var dependents1 = context.Set().Include(e => e.Principal).ToList(); + var dependents1 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Equal(2, dependents1.Count); Assert.Null( context.Entry(dependents1.Single(e => e.Principal == null)) .Property("PrincipalId").CurrentValue); - var optionalDependents1 = context.Set().Include(e => e.Principal).ToList(); + var optionalDependents1 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Equal(2, optionalDependents1.Count); Assert.Null(optionalDependents1.Single(e => e.Principal == null).PrincipalId); - var requiredDependents1 = context.Set().Include(e => e.Principal).ToList(); + var requiredDependents1 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Single(requiredDependents1); - var dependents2 = context.Set().Include(e => e.Principal).ToList(); + var dependents2 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Equal(2, dependents2.Count); Assert.Null( context.Entry(dependents2.Single(e => e.Principal == null)) .Property("PrincipalId").CurrentValue); - var optionalDependents2 = context.Set().Include(e => e.Principal).ToList(); + var optionalDependents2 = + await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Equal(2, optionalDependents2.Count); Assert.Null(optionalDependents2.Single(e => e.Principal == null).PrincipalId); - var requiredDependents2 = context.Set().Include(e => e.Principal).ToList(); + var requiredDependents2 = + await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Single(requiredDependents2); - var dependents3 = context.Set().Include(e => e.Principal).ToList(); + var dependents3 = await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Equal(2, dependents3.Count); Assert.Null( context.Entry(dependents3.Single(e => e.Principal == null)) .Property("PrincipalId").CurrentValue); - var optionalDependents3 = context.Set().Include(e => e.Principal).ToList(); + var optionalDependents3 = + await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Equal(2, optionalDependents3.Count); Assert.Null(optionalDependents3.Single(e => e.Principal == null).PrincipalId); - var requiredDependents3 = context.Set().Include(e => e.Principal).ToList(); + var requiredDependents3 = + await context.Set().Include(e => e.Principal).ToListAsync(); Assert.Single(requiredDependents3); context.Remove(dependents1.Single(e => e.Principal != null)); @@ -667,21 +666,20 @@ public virtual void Insert_update_and_delete_with_wrapped_int_key_using_hi_lo() context.Remove(requiredDependents3.Single()); context.Remove(requiredDependents3.Single().Principal); - context.SaveChanges(); - }, - context => + await context.SaveChangesAsync(); + }, async context => { - Assert.Equal(1, context.Set().Count()); - Assert.Equal(1, context.Set().Count()); - Assert.Equal(1, context.Set().Count()); + Assert.Equal(1, await context.Set().CountAsync()); + Assert.Equal(1, await context.Set().CountAsync()); + Assert.Equal(1, await context.Set().CountAsync()); - Assert.Equal(1, context.Set().Count()); - Assert.Equal(1, context.Set().Count()); - Assert.Equal(1, context.Set().Count()); + Assert.Equal(1, await context.Set().CountAsync()); + Assert.Equal(1, await context.Set().CountAsync()); + Assert.Equal(1, await context.Set().CountAsync()); - Assert.Equal(0, context.Set().Count()); - Assert.Equal(0, context.Set().Count()); - Assert.Equal(0, context.Set().Count()); + Assert.Equal(0, await context.Set().CountAsync()); + Assert.Equal(0, await context.Set().CountAsync()); + Assert.Equal(0, await context.Set().CountAsync()); }); } @@ -689,7 +687,7 @@ protected override void UseTransaction(DatabaseFacade facade, IDbContextTransact => facade.UseTransaction(transaction.GetDbTransaction()); [ConditionalFact] - public virtual void Exception_in_SaveChanges_causes_store_values_to_be_reverted() + public virtual async Task Exception_in_SaveChanges_causes_store_values_to_be_reverted() { var entities = new List(); for (var i = 0; i < 100; i++) @@ -725,8 +723,8 @@ public virtual void Exception_in_SaveChanges_causes_store_values_to_be_reverted( for (var i = 0; i < 2; i++) { - ExecuteWithStrategyInTransaction( - context => + await ExecuteWithStrategyInTransactionAsync( + async context => { context.AddRange(entities); @@ -758,7 +756,7 @@ public virtual void Exception_in_SaveChanges_causes_store_values_to_be_reverted( // inner exception for details. // SqlException : Cannot insert explicit value for identity column in table // 'Blog' when IDENTITY_INSERT is set to OFF. - var updateException = Assert.Throws(() => context.SaveChanges()); + var updateException = await Assert.ThrowsAsync(() => context.SaveChangesAsync()); Assert.Single(updateException.Entries); foreach (var entity in entities.Take(100)) diff --git a/test/EFCore.SqlServer.FunctionalTests/TestUtilities/SqlServerTestStore.cs b/test/EFCore.SqlServer.FunctionalTests/TestUtilities/SqlServerTestStore.cs index a1a7bc9e254..aa06149f2b5 100644 --- a/test/EFCore.SqlServer.FunctionalTests/TestUtilities/SqlServerTestStore.cs +++ b/test/EFCore.SqlServer.FunctionalTests/TestUtilities/SqlServerTestStore.cs @@ -16,15 +16,15 @@ public class SqlServerTestStore : RelationalTestStore private static string CurrentDirectory => Environment.CurrentDirectory; - public static SqlServerTestStore GetNorthwindStore() - => (SqlServerTestStore)SqlServerNorthwindTestStoreFactory.Instance - .GetOrCreate(SqlServerNorthwindTestStoreFactory.Name).Initialize(null, (Func?)null); + public static async Task GetNorthwindStoreAsync() + => (SqlServerTestStore)await SqlServerNorthwindTestStoreFactory.Instance + .GetOrCreate(SqlServerNorthwindTestStoreFactory.Name).InitializeAsync(null, (Func?)null); public static SqlServerTestStore GetOrCreate(string name) => new(name); - public static SqlServerTestStore GetOrCreateInitialized(string name) - => new SqlServerTestStore(name).InitializeSqlServer(null, (Func?)null, null); + public static async Task GetOrCreateInitializedAsync(string name) + => await new SqlServerTestStore(name).InitializeSqlServerAsync(null, (Func?)null, null); public static SqlServerTestStore GetOrCreateWithInitScript(string name, string initScript) => new(name, initScript: initScript); @@ -39,9 +39,12 @@ public static SqlServerTestStore GetOrCreateWithScriptPath( public static SqlServerTestStore Create(string name, bool useFileName = false) => new(name, useFileName, shared: false); - public static SqlServerTestStore CreateInitialized(string name, bool useFileName = false, bool? multipleActiveResultSets = null) - => new SqlServerTestStore(name, useFileName, shared: false, multipleActiveResultSets: multipleActiveResultSets) - .InitializeSqlServer(null, (Func?)null, null); + public static async Task CreateInitializedAsync( + string name, + bool useFileName = false, + bool? multipleActiveResultSets = null) + => await new SqlServerTestStore(name, useFileName, shared: false, multipleActiveResultSets: multipleActiveResultSets) + .InitializeSqlServerAsync(null, (Func?)null, null); private readonly string? _fileName; private readonly string? _initScript; @@ -70,37 +73,40 @@ private SqlServerTestStore( } - public SqlServerTestStore InitializeSqlServer( + public async Task InitializeSqlServerAsync( IServiceProvider? serviceProvider, Func? createContext, - Action? seed) - => (SqlServerTestStore)Initialize(serviceProvider, createContext, seed); + Func? seed) + => (SqlServerTestStore)await InitializeAsync(serviceProvider, createContext, seed); - public SqlServerTestStore InitializeSqlServer( + public async Task InitializeSqlServerAsync( IServiceProvider serviceProvider, Func createContext, - Action seed) - => InitializeSqlServer(serviceProvider, () => createContext(this), seed); + Func seed) + => await InitializeSqlServerAsync(serviceProvider, () => createContext(this), seed); - protected override void Initialize(Func createContext, Action? seed, Action? clean) + protected override async Task InitializeAsync(Func createContext, Func? seed, Func? clean) { - if (CreateDatabase(clean)) + if (await CreateDatabase(clean)) { if (_scriptPath != null) { - ExecuteScript(File.ReadAllText(_scriptPath)); + ExecuteScript(await File.ReadAllTextAsync(_scriptPath)); } else { using var context = createContext(); - context.Database.EnsureCreatedResiliently(); + await context.Database.EnsureCreatedResilientlyAsync(); if (_initScript != null) { ExecuteScript(_initScript); } - seed?.Invoke(context); + if (seed != null) + { + await seed(context); + } } } } @@ -110,7 +116,7 @@ public override DbContextOptionsBuilder AddProviderOptions(DbContextOptionsBuild .UseSqlServer(Connection, b => b.ApplyConfiguration()) .ConfigureWarnings(b => b.Ignore(SqlServerEventId.SavepointsDisabledBecauseOfMARS)); - private bool CreateDatabase(Action? clean) + private async Task CreateDatabase(Func? clean) { using (var master = new SqlConnection(CreateConnectionString("master", fileName: null, multipleActiveResultSets: false))) { @@ -129,8 +135,13 @@ private bool CreateDatabase(Action? clean) new DbContextOptionsBuilder() .EnableServiceProviderCaching(false)) .Options); - Clean(context); - clean?.Invoke(context); + await CleanAsync(context); + + if (clean != null) + { + await clean(context); + } + return true; } @@ -145,8 +156,11 @@ private bool CreateDatabase(Action? clean) return true; } - public override void Clean(DbContext context) - => context.Database.EnsureClean(); + public override Task CleanAsync(DbContext context) + { + context.Database.EnsureClean(); + return Task.CompletedTask; + } public void ExecuteScript(string script) => Execute( diff --git a/test/EFCore.SqlServer.FunctionalTests/TransactionSqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/TransactionSqlServerTest.cs index 10c903b13aa..6a54a9ce49b 100644 --- a/test/EFCore.SqlServer.FunctionalTests/TransactionSqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/TransactionSqlServerTest.cs @@ -10,7 +10,8 @@ namespace Microsoft.EntityFrameworkCore; #nullable disable -public class TransactionSqlServerTest(TransactionSqlServerTest.TransactionSqlServerFixture fixture) : TransactionTestBase(fixture) +public class TransactionSqlServerTest(TransactionSqlServerTest.TransactionSqlServerFixture fixture) + : TransactionTestBase(fixture) { // Test relies on savepoints, which are disabled when MARS is enabled public override Task SaveChanges_implicitly_creates_savepoint(bool async) @@ -86,22 +87,22 @@ public class TransactionSqlServerFixture : TransactionFixtureBase protected override ITestStoreFactory TestStoreFactory => SqlServerTestStoreFactory.Instance; - protected override void Seed(PoolableDbContext context) + protected override async Task SeedAsync(PoolableDbContext context) { - base.Seed(context); + await base.SeedAsync(context); - context.Database.ExecuteSqlRaw("ALTER DATABASE [" + StoreName + "] SET ALLOW_SNAPSHOT_ISOLATION ON"); - context.Database.ExecuteSqlRaw("ALTER DATABASE [" + StoreName + "] SET READ_COMMITTED_SNAPSHOT ON"); + await context.Database.ExecuteSqlRawAsync("ALTER DATABASE [" + StoreName + "] SET ALLOW_SNAPSHOT_ISOLATION ON"); + await context.Database.ExecuteSqlRawAsync("ALTER DATABASE [" + StoreName + "] SET READ_COMMITTED_SNAPSHOT ON"); } - public override void Reseed() + public override async Task ReseedAsync() { using var context = CreateContext(); - context.Set().RemoveRange(context.Set()); - context.Set().RemoveRange(context.Set()); + context.Set().RemoveRange(await context.Set().ToListAsync()); + context.Set().RemoveRange(await context.Set().ToListAsync()); context.SaveChanges(); - base.Seed(context); + await base.SeedAsync(context); } public override DbContextOptionsBuilder AddOptions(DbContextOptionsBuilder builder) diff --git a/test/EFCore.SqlServer.FunctionalTests/Update/MismatchedKeyTypesSqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/Update/MismatchedKeyTypesSqlServerTest.cs index 66fae63f990..684c25c2cca 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Update/MismatchedKeyTypesSqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Update/MismatchedKeyTypesSqlServerTest.cs @@ -3,7 +3,8 @@ namespace Microsoft.EntityFrameworkCore.Update; -public class MismatchedKeyTypesSqlServerTest(MismatchedKeyTypesSqlServerTest.MismatchedKeyTypesSqlServerFixture fixture) : IClassFixture +public class MismatchedKeyTypesSqlServerTest(MismatchedKeyTypesSqlServerTest.MismatchedKeyTypesSqlServerFixture fixture) + : IClassFixture { public MismatchedKeyTypesSqlServerFixture Fixture { get; } = fixture; @@ -730,21 +731,9 @@ protected class OptionalSingleBadComposite public int? PrincipalId3 { get; set; } } - public class MismatchedKeyTypesSqlServerFixture : IDisposable + public class MismatchedKeyTypesSqlServerFixture : IAsyncLifetime { - public MismatchedKeyTypesSqlServerFixture() - { - Store = SqlServerTestStore.CreateInitialized("MismatchedKeyTypes"); - - using (var context = new MismatchedKeyTypesContextNoFks(this)) - { - context.Database.EnsureClean(); - } - - Seed(); - } - - public void Seed() + public async Task SeedAsync() { using var context = new MismatchedKeyTypesContext(this); @@ -790,13 +779,28 @@ public void Seed() Id3 = -1 }); - context.SaveChanges(); + await context.SaveChangesAsync(); } - public SqlServerTestStore Store { get; set; } + public SqlServerTestStore Store { get; set; } = null!; + + public async Task InitializeAsync() + { + Store = await SqlServerTestStore.CreateInitializedAsync("MismatchedKeyTypes"); + + using (var context = new MismatchedKeyTypesContextNoFks(this)) + { + context.Database.EnsureClean(); + } + + await SeedAsync(); + } - public void Dispose() - => Store.Dispose(); + public Task DisposeAsync() + { + Store.Dispose(); + return Task.CompletedTask; + } } private class TemporaryByteValueGenerator : ValueGenerator diff --git a/test/EFCore.SqlServer.FunctionalTests/Update/NonSharedModelUpdatesSqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/Update/NonSharedModelUpdatesSqlServerTest.cs index 5c87fe17189..4b7780efc13 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Update/NonSharedModelUpdatesSqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Update/NonSharedModelUpdatesSqlServerTest.cs @@ -95,10 +95,11 @@ public virtual async Task Bulk_insert_result_set_mapping() mb.Entity().ToTable("Users"); mb.Entity().ToTable("DailyDigests"); }, - createTestStore: () => SqlServerTestStore.GetOrCreateWithScriptPath( - "Issue29502", - Path.Combine("Update", "Issue29502.sql"), - shared: false)); + createTestStore: () => Task.FromResult( + SqlServerTestStore.GetOrCreateWithScriptPath( + "Issue29502", + Path.Combine("Update", "Issue29502.sql"), + shared: false))); await ExecuteWithStrategyInTransactionAsync( contextFactory, diff --git a/test/EFCore.SqlServer.FunctionalTests/Update/StoreValueGenerationWithoutOutputSqlServerFixture.cs b/test/EFCore.SqlServer.FunctionalTests/Update/StoreValueGenerationWithoutOutputSqlServerFixture.cs index 249dac31666..9b133708e51 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Update/StoreValueGenerationWithoutOutputSqlServerFixture.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Update/StoreValueGenerationWithoutOutputSqlServerFixture.cs @@ -9,14 +9,14 @@ namespace Microsoft.EntityFrameworkCore.Update; public abstract class StoreValueGenerationWithoutOutputSqlServerFixture : StoreValueGenerationSqlServerFixtureBase { - protected override void Seed(StoreValueGenerationContext context) + protected override async Task SeedAsync(StoreValueGenerationContext context) { - base.Seed(context); + await base.SeedAsync(context); // Add triggers to all tables foreach (var table in context.Model.GetEntityTypes().Select(e => e.GetTableName())) { - context.Database.ExecuteSqlRaw( + await context.Database.ExecuteSqlRawAsync( $@" CREATE OR ALTER TRIGGER [{table}_Trigger] ON [{table}] diff --git a/test/EFCore.SqlServer.FunctionalTests/Update/UpdatesSqlServerTPCTest.cs b/test/EFCore.SqlServer.FunctionalTests/Update/UpdatesSqlServerTPCTest.cs index 515ac9c89eb..3f02486912d 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Update/UpdatesSqlServerTPCTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Update/UpdatesSqlServerTPCTest.cs @@ -5,11 +5,12 @@ namespace Microsoft.EntityFrameworkCore.Update; -public class UpdatesSqlServerTPCTest(UpdatesSqlServerTPCTest.UpdatesSqlServerTPCFixture fixture, ITestOutputHelper testOutputHelper) : UpdatesSqlServerTestBase(fixture, testOutputHelper) +public class UpdatesSqlServerTPCTest(UpdatesSqlServerTPCTest.UpdatesSqlServerTPCFixture fixture, ITestOutputHelper testOutputHelper) + : UpdatesSqlServerTestBase(fixture, testOutputHelper) { - public override void Save_with_shared_foreign_key() + public override async Task Save_with_shared_foreign_key() { - base.Save_with_shared_foreign_key(); + await base.Save_with_shared_foreign_key(); AssertContainsSql( @"@p0=NULL (Size = 8000) (DbType = Binary) @@ -31,9 +32,9 @@ OUTPUT INSERTED.[Id] VALUES (@p0, @p1);"); } - public override void Save_replaced_principal() + public override async Task Save_replaced_principal() { - base.Save_replaced_principal(); + await base.Save_replaced_principal(); AssertSql( """ diff --git a/test/EFCore.SqlServer.FunctionalTests/Update/UpdatesSqlServerTPTTest.cs b/test/EFCore.SqlServer.FunctionalTests/Update/UpdatesSqlServerTPTTest.cs index 4eec8156e62..b90081b5225 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Update/UpdatesSqlServerTPTTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Update/UpdatesSqlServerTPTTest.cs @@ -7,9 +7,9 @@ namespace Microsoft.EntityFrameworkCore.Update; public class UpdatesSqlServerTPTTest(UpdatesSqlServerTPTTest.UpdatesSqlServerTPTFixture fixture, ITestOutputHelper testOutputHelper) : UpdatesSqlServerTestBase(fixture, testOutputHelper) { - public override void Save_with_shared_foreign_key() + public override async Task Save_with_shared_foreign_key() { - base.Save_with_shared_foreign_key(); + await base.Save_with_shared_foreign_key(); AssertContainsSql( @"@p0=NULL (Size = 8000) (DbType = Binary) @@ -31,9 +31,9 @@ OUTPUT INSERTED.[Id] VALUES (@p0, @p1);"); } - public override void Save_replaced_principal() + public override async Task Save_replaced_principal() { - base.Save_replaced_principal(); + await base.Save_replaced_principal(); AssertSql( """ diff --git a/test/EFCore.SqlServer.FunctionalTests/Update/UpdatesSqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/Update/UpdatesSqlServerTest.cs index a22d5306533..f98cae5f0b6 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Update/UpdatesSqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Update/UpdatesSqlServerTest.cs @@ -3,11 +3,12 @@ namespace Microsoft.EntityFrameworkCore.Update; -public class UpdatesSqlServerTest(UpdatesSqlServerTest.UpdatesSqlServerFixture fixture, ITestOutputHelper testOutputHelper) : UpdatesSqlServerTestBase(fixture, testOutputHelper) +public class UpdatesSqlServerTest(UpdatesSqlServerTest.UpdatesSqlServerFixture fixture, ITestOutputHelper testOutputHelper) + : UpdatesSqlServerTestBase(fixture, testOutputHelper) { - public override void Save_with_shared_foreign_key() + public override async Task Save_with_shared_foreign_key() { - base.Save_with_shared_foreign_key(); + await base.Save_with_shared_foreign_key(); AssertContainsSql( @"@p0=NULL (Size = 8000) (DbType = Binary) @@ -30,9 +31,9 @@ OUTPUT INSERTED.[Id] VALUES (@p0, @p1, @p2);"); } - public override void Save_replaced_principal() + public override async Task Save_replaced_principal() { - base.Save_replaced_principal(); + await base.Save_replaced_principal(); AssertSql( """ diff --git a/test/EFCore.SqlServer.FunctionalTests/Update/UpdatesSqlServerTestBase.cs b/test/EFCore.SqlServer.FunctionalTests/Update/UpdatesSqlServerTestBase.cs index 987f75619e0..14ab500ba54 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Update/UpdatesSqlServerTestBase.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Update/UpdatesSqlServerTestBase.cs @@ -8,18 +8,18 @@ namespace Microsoft.EntityFrameworkCore.Update; public abstract class UpdatesSqlServerTestBase : UpdatesRelationalTestBase where TFixture : UpdatesSqlServerTestBase.UpdatesSqlServerFixtureBase { - public UpdatesSqlServerTestBase(TFixture fixture, ITestOutputHelper testOutputHelper) + protected UpdatesSqlServerTestBase(TFixture fixture, ITestOutputHelper testOutputHelper) : base(fixture) { Fixture.TestSqlLoggerFactory.SetTestOutputHelper(testOutputHelper); Fixture.TestSqlLoggerFactory.Clear(); } - public override void Can_add_and_remove_self_refs() + public override async Task Can_add_and_remove_self_refs() { - Fixture.ResetIdentity(); + await Fixture.ResetIdentity(); - base.Can_add_and_remove_self_refs(); + await base.Can_add_and_remove_self_refs(); AssertSql( """ @@ -260,10 +260,10 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con modelBuilder.Entity().HasIndex(p => new { p.Name, p.Price }).HasFilter("Name IS NOT NULL"); } - public virtual void ResetIdentity() + public virtual async Task ResetIdentity() { var context = CreateContext(); - context.Database.ExecuteSqlRaw(ResetIdentitySql); + await context.Database.ExecuteSqlRawAsync(ResetIdentitySql); TestSqlLoggerFactory.Clear(); } diff --git a/test/EFCore.Sqlite.FunctionalTests/BuiltInDataTypesSqliteTest.cs b/test/EFCore.Sqlite.FunctionalTests/BuiltInDataTypesSqliteTest.cs index 5434585c55c..1d92a24bc37 100644 --- a/test/EFCore.Sqlite.FunctionalTests/BuiltInDataTypesSqliteTest.cs +++ b/test/EFCore.Sqlite.FunctionalTests/BuiltInDataTypesSqliteTest.cs @@ -1628,9 +1628,9 @@ SELECT substr("o"."Bytes", 1, 1) Assert.Equal(expectedResults, results); } - public override void Object_to_string_conversion() + public override async Task Object_to_string_conversion() { - base.Object_to_string_conversion(); + await base.Object_to_string_conversion(); AssertSql( """ diff --git a/test/EFCore.Sqlite.FunctionalTests/CustomConvertersSqliteTest.cs b/test/EFCore.Sqlite.FunctionalTests/CustomConvertersSqliteTest.cs index 4a9b5538034..7571112cd34 100644 --- a/test/EFCore.Sqlite.FunctionalTests/CustomConvertersSqliteTest.cs +++ b/test/EFCore.Sqlite.FunctionalTests/CustomConvertersSqliteTest.cs @@ -14,14 +14,13 @@ public CustomConvertersSqliteTest(CustomConvertersSqliteFixture fixture) } // Disabled: SQLite database is case-sensitive - public override void Can_insert_and_read_back_with_case_insensitive_string_key() - { - } + public override Task Can_insert_and_read_back_with_case_insensitive_string_key() + => Task.CompletedTask; [ConditionalFact] - public override void Value_conversion_is_appropriately_used_for_join_condition() + public override async Task Value_conversion_is_appropriately_used_for_join_condition() { - base.Value_conversion_is_appropriately_used_for_join_condition(); + await base.Value_conversion_is_appropriately_used_for_join_condition(); AssertSql( """ @@ -35,9 +34,9 @@ public override void Value_conversion_is_appropriately_used_for_join_condition() } [ConditionalFact] - public override void Value_conversion_is_appropriately_used_for_left_join_condition() + public override async Task Value_conversion_is_appropriately_used_for_left_join_condition() { - base.Value_conversion_is_appropriately_used_for_left_join_condition(); + await base.Value_conversion_is_appropriately_used_for_left_join_condition(); AssertSql( """ @@ -51,9 +50,9 @@ public override void Value_conversion_is_appropriately_used_for_left_join_condit } [ConditionalFact] - public override void Where_bool_gets_converted_to_equality_when_value_conversion_is_used() + public override async Task Where_bool_gets_converted_to_equality_when_value_conversion_is_used() { - base.Where_bool_gets_converted_to_equality_when_value_conversion_is_used(); + await base.Where_bool_gets_converted_to_equality_when_value_conversion_is_used(); AssertSql( """ @@ -64,9 +63,9 @@ public override void Where_bool_gets_converted_to_equality_when_value_conversion } [ConditionalFact] - public override void Where_negated_bool_gets_converted_to_equality_when_value_conversion_is_used() + public override async Task Where_negated_bool_gets_converted_to_equality_when_value_conversion_is_used() { - base.Where_negated_bool_gets_converted_to_equality_when_value_conversion_is_used(); + await base.Where_negated_bool_gets_converted_to_equality_when_value_conversion_is_used(); AssertSql( """ @@ -76,9 +75,9 @@ public override void Where_negated_bool_gets_converted_to_equality_when_value_co """); } - public override void Where_bool_with_value_conversion_inside_comparison_doesnt_get_converted_twice() + public override async Task Where_bool_with_value_conversion_inside_comparison_doesnt_get_converted_twice() { - base.Where_bool_with_value_conversion_inside_comparison_doesnt_get_converted_twice(); + await base.Where_bool_with_value_conversion_inside_comparison_doesnt_get_converted_twice(); AssertSql( """ @@ -94,9 +93,9 @@ public override void Where_bool_with_value_conversion_inside_comparison_doesnt_g """); } - public override void Select_bool_with_value_conversion_is_used() + public override async Task Select_bool_with_value_conversion_is_used() { - base.Select_bool_with_value_conversion_is_used(); + await base.Select_bool_with_value_conversion_is_used(); AssertSql( """ @@ -106,9 +105,9 @@ public override void Select_bool_with_value_conversion_is_used() } [ConditionalFact] - public override void Where_bool_gets_converted_to_equality_when_value_conversion_is_used_using_EFProperty() + public override async Task Where_bool_gets_converted_to_equality_when_value_conversion_is_used_using_EFProperty() { - base.Where_bool_gets_converted_to_equality_when_value_conversion_is_used_using_EFProperty(); + await base.Where_bool_gets_converted_to_equality_when_value_conversion_is_used_using_EFProperty(); AssertSql( """ @@ -119,9 +118,9 @@ public override void Where_bool_gets_converted_to_equality_when_value_conversion } [ConditionalFact] - public override void Where_bool_gets_converted_to_equality_when_value_conversion_is_used_using_indexer() + public override async Task Where_bool_gets_converted_to_equality_when_value_conversion_is_used_using_indexer() { - base.Where_bool_gets_converted_to_equality_when_value_conversion_is_used_using_indexer(); + await base.Where_bool_gets_converted_to_equality_when_value_conversion_is_used_using_indexer(); AssertSql( """ diff --git a/test/EFCore.Sqlite.FunctionalTests/DataAnnotationSqliteTest.cs b/test/EFCore.Sqlite.FunctionalTests/DataAnnotationSqliteTest.cs index 85126cfc195..7572ec3744c 100644 --- a/test/EFCore.Sqlite.FunctionalTests/DataAnnotationSqliteTest.cs +++ b/test/EFCore.Sqlite.FunctionalTests/DataAnnotationSqliteTest.cs @@ -89,9 +89,9 @@ public override IModel TableNameAttribute_affects_table_name_in_TPH() return model; } - public override void ConcurrencyCheckAttribute_throws_if_value_in_database_changed() + public override async Task ConcurrencyCheckAttribute_throws_if_value_in_database_changed() { - base.ConcurrencyCheckAttribute_throws_if_value_in_database_changed(); + await base.ConcurrencyCheckAttribute_throws_if_value_in_database_changed(); AssertSql( """ @@ -131,9 +131,9 @@ LIMIT 1 """); } - public override void DatabaseGeneratedAttribute_autogenerates_values_when_set_to_identity() + public override async Task DatabaseGeneratedAttribute_autogenerates_values_when_set_to_identity() { - base.DatabaseGeneratedAttribute_autogenerates_values_when_set_to_identity(); + await base.DatabaseGeneratedAttribute_autogenerates_values_when_set_to_identity(); AssertSql( """ @@ -152,24 +152,27 @@ public override void DatabaseGeneratedAttribute_autogenerates_values_when_set_to } // Sqlite does not support length - public override void MaxLengthAttribute_throws_while_inserting_value_longer_than_max_length() + public override Task MaxLengthAttribute_throws_while_inserting_value_longer_than_max_length() { using var context = CreateContext(); Assert.Equal(10, context.Model.FindEntityType(typeof(One)).FindProperty("MaxLengthProperty").GetMaxLength()); + return Task.CompletedTask; } // Sqlite does not support length - public override void StringLengthAttribute_throws_while_inserting_value_longer_than_max_length() + public override Task StringLengthAttribute_throws_while_inserting_value_longer_than_max_length() { using var context = CreateContext(); Assert.Equal(16, context.Model.FindEntityType(typeof(Two)).FindProperty("Data").GetMaxLength()); + return Task.CompletedTask; } // Sqlite does not support rowversion. See issue #2195 - public override void TimestampAttribute_throws_if_value_in_database_changed() + public override Task TimestampAttribute_throws_if_value_in_database_changed() { using var context = CreateContext(); Assert.True(context.Model.FindEntityType(typeof(Two)).FindProperty("Timestamp").IsConcurrencyToken); + return Task.CompletedTask; } private void AssertSql(params string[] expected) diff --git a/test/EFCore.Sqlite.FunctionalTests/FieldMappingSqliteTest.cs b/test/EFCore.Sqlite.FunctionalTests/FieldMappingSqliteTest.cs index 9d8566fbeca..605bd3ddf6b 100644 --- a/test/EFCore.Sqlite.FunctionalTests/FieldMappingSqliteTest.cs +++ b/test/EFCore.Sqlite.FunctionalTests/FieldMappingSqliteTest.cs @@ -100,9 +100,8 @@ public override void Projection_read_only_props(bool tracking) { } - public override void Update_read_only_props() - { - } + public override Task Update_read_only_props() + => Task.CompletedTask; public override void Simple_query_read_only_props_with_named_fields(bool tracking) { @@ -136,9 +135,8 @@ public override void Projection_read_only_props_with_named_fields(bool tracking) { } - public override void Update_read_only_props_with_named_fields() - { - } + public override Task Update_read_only_props_with_named_fields() + => Task.CompletedTask; public override void Simple_query_write_only_props(bool tracking) { @@ -172,9 +170,8 @@ public override void Projection_write_only_props(bool tracking) { } - public override void Update_write_only_props() - { - } + public override Task Update_write_only_props() + => Task.CompletedTask; public override void Simple_query_write_only_props_with_named_fields(bool tracking) { @@ -208,9 +205,8 @@ public override void Projection_write_only_props_with_named_fields(bool tracking { } - public override void Update_write_only_props_with_named_fields() - { - } + public override Task Update_write_only_props_with_named_fields() + => Task.CompletedTask; public override void Simple_query_fields_only(bool tracking) { @@ -244,9 +240,8 @@ public override void Projection_fields_only(bool tracking) { } - public override void Update_fields_only() - { - } + public override Task Update_fields_only() + => Task.CompletedTask; public override void Simple_query_fields_only_for_navs_too(bool tracking) { @@ -280,9 +275,8 @@ public override void Projection_fields_only_only_for_navs_too(bool tracking) { } - public override void Update_fields_only_only_for_navs_too() - { - } + public override Task Update_fields_only_only_for_navs_too() + => Task.CompletedTask; public override void Include_collection_full_props(bool tracking) { @@ -300,9 +294,8 @@ public override void Load_reference_full_props() { } - public override void Update_full_props() - { - } + public override Task Update_full_props() + => Task.CompletedTask; public override void Simple_query_props_with_IReadOnlyCollection(bool tracking) { @@ -336,9 +329,8 @@ public override void Projection_props_with_IReadOnlyCollection(bool tracking) { } - public override void Update_props_with_IReadOnlyCollection() - { - } + public override Task Update_props_with_IReadOnlyCollection() + => Task.CompletedTask; public class EnforcePropertyFixture : FieldMappingSqliteFixtureBase { diff --git a/test/EFCore.Sqlite.FunctionalTests/GraphUpdates/ProxyGraphUpdatesSqliteTest.cs b/test/EFCore.Sqlite.FunctionalTests/GraphUpdates/ProxyGraphUpdatesSqliteTest.cs index 2c665cf45a7..fbf93814554 100644 --- a/test/EFCore.Sqlite.FunctionalTests/GraphUpdates/ProxyGraphUpdatesSqliteTest.cs +++ b/test/EFCore.Sqlite.FunctionalTests/GraphUpdates/ProxyGraphUpdatesSqliteTest.cs @@ -29,7 +29,8 @@ protected override ITestStoreFactory TestStoreFactory } } - public class LazyLoading(LazyLoading.ProxyGraphUpdatesWithLazyLoadingSqliteFixture fixture) : ProxyGraphUpdatesSqliteTestBase(fixture) + public class LazyLoading(LazyLoading.ProxyGraphUpdatesWithLazyLoadingSqliteFixture fixture) + : ProxyGraphUpdatesSqliteTestBase(fixture) { protected override bool DoesLazyLoading => true; @@ -50,13 +51,12 @@ protected override IServiceCollection AddServices(IServiceCollection serviceColl } } - public class ChangeTracking(ChangeTracking.ProxyGraphUpdatesWithChangeTrackingSqliteFixture fixture) : ProxyGraphUpdatesSqliteTestBase(fixture) + public class ChangeTracking(ChangeTracking.ProxyGraphUpdatesWithChangeTrackingSqliteFixture fixture) + : ProxyGraphUpdatesSqliteTestBase(fixture) { - // Needs lazy loading - public override void Save_two_entity_cycle_with_lazy_loading() - { - } + public override Task Save_two_entity_cycle_with_lazy_loading() + => Task.CompletedTask; protected override bool DoesLazyLoading => false; @@ -77,8 +77,10 @@ protected override IServiceCollection AddServices(IServiceCollection serviceColl } } - public class ChangeTrackingAndLazyLoading(ChangeTrackingAndLazyLoading.ProxyGraphUpdatesWithChangeTrackingAndLazyLoadingSqliteFixture fixture) : ProxyGraphUpdatesSqliteTestBase< - ChangeTrackingAndLazyLoading.ProxyGraphUpdatesWithChangeTrackingAndLazyLoadingSqliteFixture>(fixture) + public class ChangeTrackingAndLazyLoading( + ChangeTrackingAndLazyLoading.ProxyGraphUpdatesWithChangeTrackingAndLazyLoadingSqliteFixture fixture) + : ProxyGraphUpdatesSqliteTestBase< + ChangeTrackingAndLazyLoading.ProxyGraphUpdatesWithChangeTrackingAndLazyLoadingSqliteFixture>(fixture) { protected override bool DoesLazyLoading => true; diff --git a/test/EFCore.Sqlite.FunctionalTests/JsonTypesSqliteTest.cs b/test/EFCore.Sqlite.FunctionalTests/JsonTypesSqliteTest.cs index 9830c4806d2..6ded4822d55 100644 --- a/test/EFCore.Sqlite.FunctionalTests/JsonTypesSqliteTest.cs +++ b/test/EFCore.Sqlite.FunctionalTests/JsonTypesSqliteTest.cs @@ -9,7 +9,7 @@ namespace Microsoft.EntityFrameworkCore; [SpatialiteRequired] public class JsonTypesSqliteTest : JsonTypesRelationalTestBase { - public override void Can_read_write_binary_JSON_values(string value, string json) + public override Task Can_read_write_binary_JSON_values(string value, string json) => base.Can_read_write_binary_JSON_values( value, value switch { @@ -21,7 +21,7 @@ public override void Can_read_write_binary_JSON_values(string value, string json }); [ConditionalFact] - public override void Can_read_write_collection_of_decimal_JSON_values() + public override Task Can_read_write_collection_of_decimal_JSON_values() => Can_read_and_write_JSON_value>( nameof(DecimalCollectionType.Decimal), [ @@ -33,7 +33,7 @@ public override void Can_read_write_collection_of_decimal_JSON_values() mappedCollection: true); [ConditionalFact] - public override void Can_read_write_collection_of_DateTime_JSON_values() + public override Task Can_read_write_collection_of_DateTime_JSON_values() => Can_read_and_write_JSON_value>( nameof(DateTimeCollectionType.DateTime), [ @@ -45,7 +45,7 @@ public override void Can_read_write_collection_of_DateTime_JSON_values() mappedCollection: true); [ConditionalFact] - public override void Can_read_write_collection_of_DateTimeOffset_JSON_values() + public override Task Can_read_write_collection_of_DateTimeOffset_JSON_values() => Can_read_and_write_JSON_value>( nameof(DateTimeOffsetCollectionType.DateTimeOffset), [ @@ -59,7 +59,7 @@ public override void Can_read_write_collection_of_DateTimeOffset_JSON_values() mappedCollection: true); [ConditionalFact] - public override void Can_read_write_collection_of_GUID_JSON_values() + public override Task Can_read_write_collection_of_GUID_JSON_values() => Can_read_and_write_JSON_value>( nameof(GuidCollectionType.Guid), [ @@ -71,7 +71,7 @@ public override void Can_read_write_collection_of_GUID_JSON_values() mappedCollection: true); [ConditionalFact] - public override void Can_read_write_collection_of_binary_JSON_values() + public override Task Can_read_write_collection_of_binary_JSON_values() => Can_read_and_write_JSON_value>( nameof(BytesCollectionType.Bytes), [ @@ -84,7 +84,7 @@ public override void Can_read_write_collection_of_binary_JSON_values() mappedCollection: true); [ConditionalFact] - public override void Can_read_write_collection_of_decimal_with_precision_and_scale_JSON_values() + public override Task Can_read_write_collection_of_decimal_with_precision_and_scale_JSON_values() => Can_read_and_write_JSON_collection_value>( b => b.ElementType().HasPrecision(12, 6), nameof(DecimalCollectionType.Decimal), @@ -97,7 +97,7 @@ public override void Can_read_write_collection_of_decimal_with_precision_and_sca facets: new Dictionary { { CoreAnnotationNames.Precision, 12 }, { CoreAnnotationNames.Scale, 6 } }); [ConditionalFact] - public override void Can_read_write_collection_of_Guid_converted_to_bytes_JSON_values() + public override Task Can_read_write_collection_of_Guid_converted_to_bytes_JSON_values() => Can_read_and_write_JSON_collection_value>( b => b.ElementType().HasConversion(), nameof(GuidCollectionType.Guid), @@ -109,69 +109,64 @@ public override void Can_read_write_collection_of_Guid_converted_to_bytes_JSON_v """{"Prop":["00000000000000000000000000000000","2F24448C3F8E204A8BE898C7C1AADEBD","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"]}""", facets: new Dictionary { { CoreAnnotationNames.ProviderClrType, typeof(byte[]) } }); - public override void Can_read_write_DateTime_JSON_values(string value, string json) - { + public override Task Can_read_write_DateTime_JSON_values(string value, string json) // Cannot override since the base test contains [InlineData] attributes which still apply, and which contain data we need // to override. See Can_read_write_DateTime_JSON_values_sqlite instead. - } + => Task.CompletedTask; [ConditionalTheory] [InlineData("0001-01-01T00:00:00.0000000", """{"Prop":"0001-01-01 00:00:00"}""")] [InlineData("9999-12-31T23:59:59.9999999", """{"Prop":"9999-12-31 23:59:59.9999999"}""")] [InlineData("2023-05-29T10:52:47.2064353", """{"Prop":"2023-05-29 10:52:47.2064353"}""")] - public virtual void Can_read_write_DateTime_JSON_values_sqlite(string value, string json) + public virtual Task Can_read_write_DateTime_JSON_values_sqlite(string value, string json) => Can_read_and_write_JSON_value( nameof(DateTimeType.DateTime), DateTime.Parse(value, CultureInfo.InvariantCulture), json); - public override void Can_read_write_DateTimeOffset_JSON_values(string value, string json) - { + public override Task Can_read_write_DateTimeOffset_JSON_values(string value, string json) // Cannot override since the base test contains [InlineData] attributes which still apply, and which contain data we need // to override. See Can_read_write_DateTimeOffset_JSON_values_sqlite instead. - } + => Task.CompletedTask; [ConditionalTheory] [InlineData("0001-01-01T00:00:00.0000000-01:00", """{"Prop":"0001-01-01 00:00:00-01:00"}""")] [InlineData("9999-12-31T23:59:59.9999999+02:00", """{"Prop":"9999-12-31 23:59:59.9999999+02:00"}""")] [InlineData("0001-01-01T00:00:00.0000000-03:00", """{"Prop":"0001-01-01 00:00:00-03:00"}""")] [InlineData("2023-05-29T11:11:15.5672854+04:00", """{"Prop":"2023-05-29 11:11:15.5672854+04:00"}""")] - public virtual void Can_read_write_DateTimeOffset_JSON_values_sqlite(string value, string json) + public virtual Task Can_read_write_DateTimeOffset_JSON_values_sqlite(string value, string json) => Can_read_and_write_JSON_value( nameof(DateTimeOffsetType.DateTimeOffset), DateTimeOffset.Parse(value, CultureInfo.InvariantCulture), json); - public override void Can_read_write_decimal_JSON_values(decimal value, string json) - { + public override Task Can_read_write_decimal_JSON_values(decimal value, string json) // Cannot override since the base test contains [InlineData] attributes which still apply, and which contain data we need // to override. See Can_read_write_decimal_JSON_values_sqlite instead. - } + => Task.CompletedTask; [ConditionalTheory] [InlineData("-79228162514264337593543950335", """{"Prop":"-79228162514264337593543950335.0"}""")] [InlineData("79228162514264337593543950335", """{"Prop":"79228162514264337593543950335.0"}""")] [InlineData("0.0", """{"Prop":"0.0"}""")] [InlineData("1.1", """{"Prop":"1.1"}""")] - public virtual void Can_read_write_decimal_JSON_values_sqlite(decimal value, string json) + public virtual Task Can_read_write_decimal_JSON_values_sqlite(decimal value, string json) => Can_read_and_write_JSON_value(nameof(DecimalType.Decimal), value, json); - public override void Can_read_write_GUID_JSON_values(Guid value, string json) - { + public override Task Can_read_write_GUID_JSON_values(Guid value, string json) // Cannot override since the base test contains [InlineData] attributes which still apply, and which contain data we need // to override. See Can_read_write_GUID_JSON_values_sqlite instead. - } + => Task.CompletedTask; [ConditionalTheory] [InlineData("00000000-0000-0000-0000-000000000000", """{"Prop":"00000000-0000-0000-0000-000000000000"}""")] [InlineData("FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF", """{"Prop":"FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF"}""")] [InlineData("8C44242F-8E3F-4A20-8BE8-98C7C1AADEBD", """{"Prop":"8C44242F-8E3F-4A20-8BE8-98C7C1AADEBD"}""")] - public virtual void Can_read_write_GUID_JSON_values_sqlite(Guid value, string json) + public virtual Task Can_read_write_GUID_JSON_values_sqlite(Guid value, string json) => Can_read_and_write_JSON_value(nameof(GuidType.Guid), value, json); - public override void Can_read_write_nullable_binary_JSON_values(string? value, string json) - { + public override Task Can_read_write_nullable_binary_JSON_values(string? value, string json) // Cannot override since the base test contains [InlineData] attributes which still apply, and which contain data we need // to override. See Can_read_write_nullable_binary_JSON_values_sqlite instead. - } + => Task.CompletedTask; [ConditionalTheory] [InlineData("0,0,0,1", """{"Prop":"00000001"}""")] @@ -179,7 +174,7 @@ public override void Can_read_write_nullable_binary_JSON_values(string? value, s [InlineData("", """{"Prop":""}""")] [InlineData("1,2,3,4", """{"Prop":"01020304"}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_binary_JSON_values_sqlite(string? value, string json) + public virtual Task Can_read_write_nullable_binary_JSON_values_sqlite(string? value, string json) => Can_read_and_write_JSON_value( nameof(NullableBytesType.Bytes), value == null @@ -188,27 +183,25 @@ public virtual void Can_read_write_nullable_binary_JSON_values_sqlite(string? va ? [] : value.Split(',').Select(e => byte.Parse(e)).ToArray(), json); - public override void Can_read_write_nullable_DateTime_JSON_values(string? value, string json) - { + public override Task Can_read_write_nullable_DateTime_JSON_values(string? value, string json) // Cannot override since the base test contains [InlineData] attributes which still apply, and which contain data we need // to override. See Can_read_write_nullable_DateTime_JSON_values_sqlite instead. - } + => Task.CompletedTask; [ConditionalTheory] [InlineData("0001-01-01T00:00:00.0000000", """{"Prop":"0001-01-01 00:00:00"}""")] [InlineData("9999-12-31T23:59:59.9999999", """{"Prop":"9999-12-31 23:59:59.9999999"}""")] [InlineData("2023-05-29T10:52:47.2064353", """{"Prop":"2023-05-29 10:52:47.2064353"}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_DateTime_JSON_values_sqlite(string? value, string json) + public virtual Task Can_read_write_nullable_DateTime_JSON_values_sqlite(string? value, string json) => Can_read_and_write_JSON_value( nameof(NullableDateTimeType.DateTime), value == null ? default(DateTime?) : DateTime.Parse(value, CultureInfo.InvariantCulture), json); - public override void Can_read_write_nullable_DateTimeOffset_JSON_values(string? value, string json) - { + public override Task Can_read_write_nullable_DateTimeOffset_JSON_values(string? value, string json) // Cannot override since the base test contains [InlineData] attributes which still apply, and which contain data we need // to override. See Can_read_write_nullable_DateTimeOffset_JSON_values_sqlite instead. - } + => Task.CompletedTask; [ConditionalTheory] [InlineData("0001-01-01T00:00:00.0000000-01:00", """{"Prop":"0001-01-01 00:00:00-01:00"}""")] @@ -216,16 +209,15 @@ public override void Can_read_write_nullable_DateTimeOffset_JSON_values(string? [InlineData("0001-01-01T00:00:00.0000000-03:00", """{"Prop":"0001-01-01 00:00:00-03:00"}""")] [InlineData("2023-05-29T11:11:15.5672854+04:00", """{"Prop":"2023-05-29 11:11:15.5672854+04:00"}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_DateTimeOffset_JSON_values_sqlite(string? value, string json) + public virtual Task Can_read_write_nullable_DateTimeOffset_JSON_values_sqlite(string? value, string json) => Can_read_and_write_JSON_value( nameof(NullableDateTimeOffsetType.DateTimeOffset), value == null ? default(DateTimeOffset?) : DateTimeOffset.Parse(value, CultureInfo.InvariantCulture), json); - public override void Can_read_write_nullable_decimal_JSON_values(string? value, string json) - { + public override Task Can_read_write_nullable_decimal_JSON_values(string? value, string json) // Cannot override since the base test contains [InlineData] attributes which still apply, and which contain data we need // to override. See Can_read_write_nullable_decimal_JSON_values_sqlite instead. - } + => Task.CompletedTask; [ConditionalTheory] [InlineData("-79228162514264337593543950335", """{"Prop":"-79228162514264337593543950335.0"}""")] @@ -233,29 +225,28 @@ public override void Can_read_write_nullable_decimal_JSON_values(string? value, [InlineData("0.0", """{"Prop":"0.0"}""")] [InlineData("1.1", """{"Prop":"1.1"}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_decimal_JSON_values_sqlite(string? value, string json) + public virtual Task Can_read_write_nullable_decimal_JSON_values_sqlite(string? value, string json) => Can_read_and_write_JSON_value( nameof(NullableDecimalType.Decimal), value == null ? default(decimal?) : decimal.Parse(value, CultureInfo.InvariantCulture), json); - public override void Can_read_write_nullable_GUID_JSON_values(string? value, string json) - { + public override Task Can_read_write_nullable_GUID_JSON_values(string? value, string json) // Cannot override since the base test contains [InlineData] attributes which still apply, and which contain data we need // to override. See Can_read_write_nullable_GUID_JSON_values_sqlite instead. - } + => Task.CompletedTask; [ConditionalTheory] [InlineData("00000000-0000-0000-0000-000000000000", """{"Prop":"00000000-0000-0000-0000-000000000000"}""")] [InlineData("FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF", """{"Prop":"FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF"}""")] [InlineData("8C44242F-8E3F-4A20-8BE8-98C7C1AADEBD", """{"Prop":"8C44242F-8E3F-4A20-8BE8-98C7C1AADEBD"}""")] [InlineData(null, """{"Prop":null}""")] - public virtual void Can_read_write_nullable_GUID_JSON_values_sqlite(string? value, string json) + public virtual Task Can_read_write_nullable_GUID_JSON_values_sqlite(string? value, string json) => Can_read_and_write_JSON_value( nameof(NullableGuidType.Guid), value == null ? null : Guid.Parse(value, CultureInfo.InvariantCulture), json); [ConditionalFact] - public override void Can_read_write_collection_of_nullable_binary_JSON_values() + public override Task Can_read_write_collection_of_nullable_binary_JSON_values() => Can_read_and_write_JSON_value>( nameof(NullableBytesCollectionType.Bytes), [ @@ -269,7 +260,7 @@ public override void Can_read_write_collection_of_nullable_binary_JSON_values() mappedCollection: true); [ConditionalFact] - public override void Can_read_write_collection_of_nullable_DateTime_JSON_values() + public override Task Can_read_write_collection_of_nullable_DateTime_JSON_values() => Can_read_and_write_JSON_value>( nameof(NullableDateTimeCollectionType.DateTime), [ @@ -282,7 +273,7 @@ public override void Can_read_write_collection_of_nullable_DateTime_JSON_values( mappedCollection: true); [ConditionalFact] - public override void Can_read_write_collection_of_nullable_DateTimeOffset_JSON_values() + public override Task Can_read_write_collection_of_nullable_DateTimeOffset_JSON_values() => Can_read_and_write_JSON_value>( nameof(NullableDateTimeOffsetCollectionType.DateTimeOffset), [ @@ -297,7 +288,7 @@ public override void Can_read_write_collection_of_nullable_DateTimeOffset_JSON_v mappedCollection: true); [ConditionalFact] - public override void Can_read_write_collection_of_nullable_decimal_JSON_values() + public override Task Can_read_write_collection_of_nullable_decimal_JSON_values() => Can_read_and_write_JSON_value>( nameof(NullableDecimalCollectionType.Decimal), [ @@ -310,7 +301,7 @@ public override void Can_read_write_collection_of_nullable_decimal_JSON_values() mappedCollection: true); [ConditionalFact] - public override void Can_read_write_collection_of_nullable_GUID_JSON_values() + public override Task Can_read_write_collection_of_nullable_GUID_JSON_values() => Can_read_and_write_JSON_value>( nameof(NullableGuidCollectionType.Guid), [ @@ -322,13 +313,16 @@ public override void Can_read_write_collection_of_nullable_GUID_JSON_values() """{"Prop":["00000000-0000-0000-0000-000000000000",null,"8C44242F-8E3F-4A20-8BE8-98C7C1AADEBD","FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF"]}""", mappedCollection: true); - protected override ITestStoreFactory TestStoreFactory => SqliteTestStoreFactory.Instance; + protected override ITestStoreFactory TestStoreFactory + => SqliteTestStoreFactory.Instance; + protected override DbContextOptionsBuilder AddOptions(DbContextOptionsBuilder builder) { builder = base.AddOptions(builder) - .ConfigureWarnings(w => w - .Ignore(SqliteEventId.SchemaConfiguredWarning) - .Ignore(SqliteEventId.CompositeKeyWithValueGeneration)); + .ConfigureWarnings( + w => w + .Ignore(SqliteEventId.SchemaConfiguredWarning) + .Ignore(SqliteEventId.CompositeKeyWithValueGeneration)); new SqliteDbContextOptionsBuilder(builder).UseNetTopologySuite(); return builder; } diff --git a/test/EFCore.Sqlite.FunctionalTests/Query/AdHocJsonQuerySqliteTest.cs b/test/EFCore.Sqlite.FunctionalTests/Query/AdHocJsonQuerySqliteTest.cs index f8faee753c5..fcc06b5f823 100644 --- a/test/EFCore.Sqlite.FunctionalTests/Query/AdHocJsonQuerySqliteTest.cs +++ b/test/EFCore.Sqlite.FunctionalTests/Query/AdHocJsonQuerySqliteTest.cs @@ -10,7 +10,7 @@ public class AdHocJsonQuerySqliteTest : AdHocJsonQueryTestBase protected override ITestStoreFactory TestStoreFactory => SqliteTestStoreFactory.Instance; - protected override void Seed29219(MyContext29219 ctx) + protected override async Task Seed29219(MyContext29219 ctx) { var entity1 = new MyEntity29219 { @@ -32,19 +32,19 @@ protected override void Seed29219(MyContext29219 ctx) }; ctx.Entities.AddRange(entity1, entity2); - ctx.SaveChanges(); + await ctx.SaveChangesAsync(); - ctx.Database.ExecuteSql( + await ctx.Database.ExecuteSqlAsync( $$""" INSERT INTO "Entities" ("Id", "Reference", "Collection") VALUES(3, '{ "NonNullableScalar" : 30 }', '[{ "NonNullableScalar" : 10001 }]') """); } - protected override void Seed30028(MyContext30028 ctx) + protected override async Task Seed30028(MyContext30028 ctx) { // complete - ctx.Database.ExecuteSql( + await ctx.Database.ExecuteSqlAsync( $$$$""" INSERT INTO "Entities" ("Id", "Json") VALUES( @@ -53,7 +53,7 @@ protected override void Seed30028(MyContext30028 ctx) """); // missing collection - ctx.Database.ExecuteSql( + await ctx.Database.ExecuteSqlAsync( $$$$""" INSERT INTO "Entities" ("Id", "Json") VALUES( @@ -62,7 +62,7 @@ protected override void Seed30028(MyContext30028 ctx) """); // missing optional reference - ctx.Database.ExecuteSql( + await ctx.Database.ExecuteSqlAsync( $$$$""" INSERT INTO "Entities" ("Id", "Json") VALUES( @@ -71,7 +71,7 @@ protected override void Seed30028(MyContext30028 ctx) """); // missing required reference - ctx.Database.ExecuteSql( + await ctx.Database.ExecuteSqlAsync( $$$$""" INSERT INTO "Entities" ("Id", "Json") VALUES( @@ -80,14 +80,14 @@ protected override void Seed30028(MyContext30028 ctx) """); } - protected override void Seed33046(Context33046 ctx) - => ctx.Database.ExecuteSql( + protected override async Task Seed33046(Context33046 ctx) + => await ctx.Database.ExecuteSqlAsync( $$""" INSERT INTO "Reviews" ("Rounds", "Id") VALUES('[{"RoundNumber":11,"SubRounds":[{"SubRoundNumber":111},{"SubRoundNumber":112}]}]', 1) """); - protected override void SeedArrayOfPrimitives(MyContextArrayOfPrimitives ctx) + protected override Task SeedArrayOfPrimitives(MyContextArrayOfPrimitives ctx) { var entity1 = new MyEntityArrayOfPrimitives { @@ -130,11 +130,11 @@ protected override void SeedArrayOfPrimitives(MyContextArrayOfPrimitives ctx) }; ctx.Entities.AddRange(entity1, entity2); - ctx.SaveChanges(); + return ctx.SaveChangesAsync(); } - protected override void SeedJunkInJson(MyContextJunkInJson ctx) - => ctx.Database.ExecuteSql( + protected override Task SeedJunkInJson(MyContextJunkInJson ctx) + => ctx.Database.ExecuteSqlAsync( $$$""" INSERT INTO "Entities" ("Collection", "CollectionWithCtor", "Reference", "ReferenceWithCtor", "Id") VALUES( @@ -145,16 +145,16 @@ protected override void SeedJunkInJson(MyContextJunkInJson ctx) 1) """); - protected override void SeedTrickyBuffering(MyContextTrickyBuffering ctx) - => ctx.Database.ExecuteSql( + protected override Task SeedTrickyBuffering(MyContextTrickyBuffering ctx) + => ctx.Database.ExecuteSqlAsync( $$$""" INSERT INTO "Entities" ("Reference", "Id") VALUES( '{"Name": "r1", "Number": 7, "JunkReference":{"Something": "SomeValue" }, "JunkCollection": [{"Foo": "junk value"}], "NestedReference": {"DoB": "2000-01-01T00:00:00"}, "NestedCollection": [{"DoB": "2000-02-01T00:00:00", "JunkReference": {"Something": "SomeValue"}}, {"DoB": "2000-02-02T00:00:00"}]}',1) """); - protected override void SeedShadowProperties(MyContextShadowProperties ctx) - => ctx.Database.ExecuteSql( + protected override Task SeedShadowProperties(MyContextShadowProperties ctx) + => ctx.Database.ExecuteSqlAsync( $$""" INSERT INTO "Entities" ("Collection", "CollectionWithCtor", "Reference", "ReferenceWithCtor", "Id", "Name") VALUES( @@ -166,9 +166,9 @@ protected override void SeedShadowProperties(MyContextShadowProperties ctx) 'e1') """); - protected override void SeedNotICollection(MyContextNotICollection ctx) + protected override async Task SeedNotICollection(MyContextNotICollection ctx) { - ctx.Database.ExecuteSql( + await ctx.Database.ExecuteSqlAsync( $$""" INSERT INTO "Entities" ("Json", "Id") VALUES( @@ -176,7 +176,7 @@ protected override void SeedNotICollection(MyContextNotICollection ctx) 1) """); - ctx.Database.ExecuteSql( + await ctx.Database.ExecuteSqlAsync( $$""" INSERT INTO "Entities" ("Json", "Id") VALUES( diff --git a/test/EFCore.Sqlite.FunctionalTests/Query/AdHocMiscellaneousQuerySqliteTest.cs b/test/EFCore.Sqlite.FunctionalTests/Query/AdHocMiscellaneousQuerySqliteTest.cs index 39be2e47903..a8750daf50a 100644 --- a/test/EFCore.Sqlite.FunctionalTests/Query/AdHocMiscellaneousQuerySqliteTest.cs +++ b/test/EFCore.Sqlite.FunctionalTests/Query/AdHocMiscellaneousQuerySqliteTest.cs @@ -12,14 +12,12 @@ public class AdHocMiscellaneousQuerySqliteTest : AdHocMiscellaneousQueryRelation protected override ITestStoreFactory TestStoreFactory => SqliteTestStoreFactory.Instance; - protected override void Seed2951(Context2951 context) - { - context.Database.ExecuteSqlRaw( -""" + protected override Task Seed2951(Context2951 context) + => context.Database.ExecuteSqlRawAsync( + """ CREATE TABLE ZeroKey (Id int); INSERT INTO ZeroKey VALUES (NULL) """); - } public override async Task Average_with_cast() => Assert.Equal( diff --git a/test/EFCore.Sqlite.FunctionalTests/Query/IncompleteMappingInheritanceQuerySqliteTest.cs b/test/EFCore.Sqlite.FunctionalTests/Query/IncompleteMappingInheritanceQuerySqliteTest.cs index 8fbe7321e33..65eda4f58e7 100644 --- a/test/EFCore.Sqlite.FunctionalTests/Query/IncompleteMappingInheritanceQuerySqliteTest.cs +++ b/test/EFCore.Sqlite.FunctionalTests/Query/IncompleteMappingInheritanceQuerySqliteTest.cs @@ -10,8 +10,7 @@ public class IncompleteMappingInheritanceQuerySqliteTest( ITestOutputHelper testOutputHelper) : TPHInheritanceQueryTestBase(fixture, testOutputHelper) { - public override void Can_insert_update_delete() - { + public override Task Can_insert_update_delete() // Test from InheritanceSqliteTest causes transaction failure. We only need to test it once. - } + => Task.CompletedTask; } diff --git a/test/EFCore.Sqlite.FunctionalTests/SqliteDatabaseCreatorTest.cs b/test/EFCore.Sqlite.FunctionalTests/SqliteDatabaseCreatorTest.cs index dcbb4513709..4e4ccb8f3c3 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 = SqliteTestStore.GetOrCreateInitialized("Empty"); + 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 = SqliteTestStore.GetOrCreateInitialized($"HasATable{(async ? 'A' : 'S')}"); + 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 = SqliteTestStore.GetOrCreateInitialized("Empty"); + using var testStore = await SqliteTestStore.GetOrCreateInitializedAsync("Empty"); var context = CreateContext(testStore.ConnectionString); if (useCanConnect) diff --git a/test/EFCore.Sqlite.FunctionalTests/StoreGeneratedSqliteTest.cs b/test/EFCore.Sqlite.FunctionalTests/StoreGeneratedSqliteTest.cs index 5b587735126..f8818922e74 100644 --- a/test/EFCore.Sqlite.FunctionalTests/StoreGeneratedSqliteTest.cs +++ b/test/EFCore.Sqlite.FunctionalTests/StoreGeneratedSqliteTest.cs @@ -5,21 +5,21 @@ namespace Microsoft.EntityFrameworkCore; #nullable disable -public class StoreGeneratedSqliteTest(StoreGeneratedSqliteTest.StoreGeneratedSqliteFixture fixture) : StoreGeneratedTestBase(fixture) +public class StoreGeneratedSqliteTest(StoreGeneratedSqliteTest.StoreGeneratedSqliteFixture fixture) + : StoreGeneratedTestBase(fixture) { - public override void Fields_used_correctly_for_store_generated_values() - { + public override Task Fields_used_correctly_for_store_generated_values() // Computed columns not supported - } + => Task.CompletedTask; [ConditionalFact] - public void Identity_key_works_when_not_aliasing_rowid() - => ExecuteWithStrategyInTransaction( - context => + public Task Identity_key_works_when_not_aliasing_rowid() + => ExecuteWithStrategyInTransactionAsync( + async context => { var entry = context.Add(new Zach()); - context.SaveChanges(); + await context.SaveChangesAsync(); var id = entry.Entity.Id; Assert.Equal(16, id?.Length ?? 0); diff --git a/test/EFCore.Sqlite.FunctionalTests/TestUtilities/SqliteTestStore.cs b/test/EFCore.Sqlite.FunctionalTests/TestUtilities/SqliteTestStore.cs index aa1ecef0700..080d01758c8 100644 --- a/test/EFCore.Sqlite.FunctionalTests/TestUtilities/SqliteTestStore.cs +++ b/test/EFCore.Sqlite.FunctionalTests/TestUtilities/SqliteTestStore.cs @@ -12,8 +12,8 @@ public class SqliteTestStore : RelationalTestStore public static SqliteTestStore GetOrCreate(string name, bool sharedCache = false) => new(name, sharedCache: sharedCache); - public static SqliteTestStore GetOrCreateInitialized(string name) - => new SqliteTestStore(name).InitializeSqlite( + public static async Task GetOrCreateInitializedAsync(string name) + => await new SqliteTestStore(name).InitializeSqliteAsync( new ServiceCollection().AddEntityFrameworkSqlite().BuildServiceProvider(validateScopes: true), (Func?)null, null); @@ -44,16 +44,19 @@ public virtual DbContextOptionsBuilder AddProviderOptions( public override DbContextOptionsBuilder AddProviderOptions(DbContextOptionsBuilder builder) => AddProviderOptions(builder, configureSqlite: null); - public SqliteTestStore InitializeSqlite(IServiceProvider? serviceProvider, Func? createContext, Action? seed) - => (SqliteTestStore)Initialize(serviceProvider, createContext, seed); + public async Task InitializeSqliteAsync( + IServiceProvider? serviceProvider, + Func? createContext, + Func? seed) + => (SqliteTestStore)await InitializeAsync(serviceProvider, createContext, seed); - public SqliteTestStore InitializeSqlite( + public async Task InitializeSqliteAsync( IServiceProvider serviceProvider, Func createContext, - Action seed) - => (SqliteTestStore)Initialize(serviceProvider, () => createContext(this), seed); + Func seed) + => (SqliteTestStore)await InitializeAsync(serviceProvider, () => createContext(this), seed); - protected override void Initialize(Func createContext, Action? seed, Action? clean) + protected override async Task InitializeAsync(Func createContext, Func? seed, Func? clean) { if (!_seed) { @@ -61,17 +64,27 @@ protected override void Initialize(Func createContext, Action context.Database.EnsureClean(); + public override Task CleanAsync(DbContext context) + { + context.Database.EnsureClean(); + return Task.CompletedTask; + } public int ExecuteNonQuery(string sql, params object[] parameters) { diff --git a/test/EFCore.Sqlite.FunctionalTests/TransactionSqliteTest.cs b/test/EFCore.Sqlite.FunctionalTests/TransactionSqliteTest.cs index 1588064d6c4..33b2d68020d 100644 --- a/test/EFCore.Sqlite.FunctionalTests/TransactionSqliteTest.cs +++ b/test/EFCore.Sqlite.FunctionalTests/TransactionSqliteTest.cs @@ -5,7 +5,8 @@ namespace Microsoft.EntityFrameworkCore; #nullable disable -public class TransactionSqliteTest(TransactionSqliteTest.TransactionSqliteFixture fixture) : TransactionTestBase(fixture) +public class TransactionSqliteTest(TransactionSqliteTest.TransactionSqliteFixture fixture) + : TransactionTestBase(fixture) { protected override bool SnapshotSupported => false; @@ -25,14 +26,14 @@ public class TransactionSqliteFixture : TransactionFixtureBase protected override ITestStoreFactory TestStoreFactory => SharedCacheSqliteTestStoreFactory.Instance; - public override void Reseed() + public override async Task ReseedAsync() { using var context = CreateContext(); - context.Set().RemoveRange(context.Set()); - context.Set().RemoveRange(context.Set()); - context.SaveChanges(); + context.Set().RemoveRange(await context.Set().ToListAsync()); + context.Set().RemoveRange(await context.Set().ToListAsync()); + await context.SaveChangesAsync(); - Seed(context); + await SeedAsync(context); } public override DbContextOptionsBuilder AddOptions(DbContextOptionsBuilder builder) diff --git a/test/EFCore.Sqlite.FunctionalTests/Update/UpdatesSqliteTest.cs b/test/EFCore.Sqlite.FunctionalTests/Update/UpdatesSqliteTest.cs index b94e44ceaa2..55553514640 100644 --- a/test/EFCore.Sqlite.FunctionalTests/Update/UpdatesSqliteTest.cs +++ b/test/EFCore.Sqlite.FunctionalTests/Update/UpdatesSqliteTest.cs @@ -7,12 +7,12 @@ namespace Microsoft.EntityFrameworkCore.Update; #nullable disable -public class UpdatesSqliteTest(UpdatesSqliteTest.UpdatesSqliteFixture fixture) : UpdatesRelationalTestBase(fixture) +public class UpdatesSqliteTest(UpdatesSqliteTest.UpdatesSqliteFixture fixture) + : UpdatesRelationalTestBase(fixture) { - public override void Save_with_shared_foreign_key() - { + public override Task Save_with_shared_foreign_key() // Store-generated guids are not supported - } + => Task.CompletedTask; public override void Identifiers_are_generated_correctly() {