From a4f831a8e5f3fbb938017aded61b62aa39bb513e Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Fri, 3 Jan 2025 10:26:18 -0500 Subject: [PATCH] Async conversion for change tracking code samples --- .../core/managing-schemas/ensure-created.md | 22 +-- .../managing-schemas/migrations/applying.md | 10 +- .../miscellaneous/connection-resiliency.md | 4 +- .../miscellaneous/nullable-reference-types.md | 4 +- .../core/modeling/data-seeding.md | 4 +- .../core/performance/efficient-updating.md | 6 +- .../core/providers/cosmos/querying.md | 4 +- .../providers/sql-server/value-generation.md | 2 +- .../core/querying/related-data/eager.md | 4 +- .../core/querying/single-split-queries.md | 16 +- entity-framework/core/querying/sql-queries.md | 64 +++---- entity-framework/core/saving/concurrency.md | 8 +- .../saving/execute-insert-update-delete.md | 42 ++--- entity-framework/core/saving/index.md | 4 +- .../testing/testing-without-the-database.md | 6 +- .../core/what-is-new/ef-core-2.0/upgrade.md | 8 +- .../core/what-is-new/ef-core-2.1.md | 2 +- .../core/what-is-new/ef-core-2.2.md | 10 +- .../ef-core-3.x/breaking-changes.md | 16 +- .../ef-core-5.0/breaking-changes.md | 8 +- .../core/what-is-new/ef-core-5.0/whatsnew.md | 8 +- .../ef-core-6.0/breaking-changes.md | 8 +- .../ef-core-7.0/breaking-changes.md | 4 +- .../core/what-is-new/ef-core-9.0/whatsnew.md | 2 +- samples/core/Benchmarks/AverageBlogRanking.cs | 29 +-- samples/core/Benchmarks/ContextPooling.cs | 21 ++- .../DynamicallyConstructedQueries.cs | 19 +- samples/core/Benchmarks/Inheritance.cs | 41 +++-- .../core/Benchmarks/QueryTrackingBehavior.cs | 21 ++- .../CascadeDeletes/IntroOptionalSamples.cs | 41 +++-- .../CascadeDeletes/IntroRequiredSamples.cs | 51 +++--- .../OptionalDependentsSamples.cs | 33 ++-- samples/core/CascadeDeletes/Program.cs | 29 +-- .../RequiredDependentsSamples.cs | 33 ++-- .../WithDatabaseCycleSamples.cs | 33 ++-- .../AccessingTrackedEntities/Program.cs | 35 ++-- .../AccessingTrackedEntities/Samples.cs | 161 ++++++++-------- .../DefaultValueSamples.cs | 39 ++-- .../Program.cs | 19 +- .../Samples.cs | 37 ++-- .../ChangeTrackingProxiesSamples.cs | 21 ++- .../NotificationEntitiesSamples.cs | 21 ++- .../NotificationWithBaseSamples.cs | 21 ++- .../Program.cs | 13 +- .../SnapshotSamples.cs | 34 ++-- .../ChangeTrackerDebugging/Program.cs | 7 +- .../ChangeTrackerDebugging/Samples.cs | 31 ++-- .../ExplicitKeysRequiredSamples.cs | 27 +-- .../ExplicitKeysSamples.cs | 107 +++++------ .../GeneratedKeysSamples.cs | 83 ++++----- .../ChangeTrackingInEFCore/Program.cs | 39 ++-- .../ExplicitJoinEntityAndSkipsSamples.cs | 43 ++--- .../ExplicitJoinEntitySamples.cs | 37 ++-- .../ExplicitJoinEntityWithPayloadSamples.cs | 25 +-- ...licitJoinEntityWithStringPayloadSamples.cs | 44 ++--- .../OptionalRelationshipsSamples.cs | 137 +++++++------- .../ChangingFKsAndNavigations/Program.cs | 51 +++--- .../RequiredRelationshipsSamples.cs | 67 +++---- .../IdentityResolutionSamples.cs | 101 +++++----- .../IdentityResolutionInEFCore/Program.cs | 27 +-- .../SerializedGraphExamples.cs | 83 ++++----- samples/core/DbContextPooling/Program.cs | 8 +- samples/core/GetStarted/Program.cs | 11 +- samples/core/Intro/Program.cs | 15 +- .../core/Miscellaneous/Collations/Program.cs | 11 +- .../CommandInterception/Program.cs | 13 +- .../Miscellaneous/CompiledModels/Program.cs | 11 +- .../core/Miscellaneous/CompiledModels/Test.cs | 6 +- .../WithContextFactory/MyController.cs | 4 +- .../ConnectionResiliency/Program.cs | 57 +++--- .../DiagnosticListeners/Program.cs | 13 +- samples/core/Miscellaneous/Events/Program.cs | 13 +- .../Miscellaneous/Logging/Logging/Program.cs | 13 +- .../Logging/SimpleLogging/Program.cs | 48 ++--- .../Multitenancy/MultiDb/ContactContext.cs | 8 +- .../Multitenancy/MultiDb/Program.cs | 2 +- .../Data/ContactContext.cs | 7 +- .../SingleDbSingleTable/Program.cs | 2 +- .../NewInEFCore6/ArrayParametersSample.cs | 13 +- .../BoolToStringTranslationSample.cs | 21 ++- .../NewInEFCore6/ColumnOrderSample.cs | 7 +- .../NewInEFCore6/CommandSourceSample.cs | 11 +- .../NewInEFCore6/ContainsFreeTextSample.cs | 21 ++- .../NewInEFCore6/ConvertNullsSample.cs | 27 +-- .../NewInEFCore6/DbContextFactorySample.cs | 11 +- .../EntityTypeConfigurationAttributeSample.cs | 19 +- .../NewInEFCore6/GroupBySample.cs | 68 +++---- .../NewInEFCore6/HasConversionSample.cs | 17 +- .../InMemoryRequiredPropertiesSample.cs | 9 +- .../NewInEFCore6/IsNullOrWhitespaceSample.cs | 21 ++- .../ManyToManyConfigurationSample.cs | 25 +-- .../NewInEFCore6/MathFTranslationSample.cs | 21 ++- .../NewInEFCore6/OptionalDependentsSample.cs | 71 +++---- .../PreConventionModelConfigurationSample.cs | 17 +- .../NewInEFCore6/PrecisionAttributeSample.cs | 19 +- .../Miscellaneous/NewInEFCore6/Program.cs | 86 ++++----- .../NewInEFCore6/RandomFunctionSample.cs | 19 +- .../NewInEFCore6/ScaffoldingSample.cs | 9 +- .../NewInEFCore6/SparseColumnsSample.cs | 19 +- .../NewInEFCore6/SplitQuerySample.cs | 45 ++--- .../NewInEFCore6/SqliteSamples.cs | 75 ++++---- .../NewInEFCore6/StringConcatSample.cs | 21 ++- .../SubstringTranslationSample.cs | 21 ++- .../NewInEFCore6/TagWithFileAndLineSample.cs | 25 +-- .../NewInEFCore6/TemporalTablesSample.cs | 51 +++--- .../NewInEFCore6/TemporaryValuesSample.cs | 19 +- .../NewInEFCore6/ToInMemoryQuerySample.cs | 13 +- .../NewInEFCore6/ToStringTranslationSample.cs | 19 +- .../NewInEFCore6/TrailingUnderscoresSample.cs | 11 +- .../NewInEFCore6/UnicodeAttributeSample.cs | 19 +- .../ModelBuildingConventionsSample.cs | 4 +- .../NewInEFCore7/TpcInheritanceSample.cs | 2 +- .../NewInEFCore9/NewInEFCore9.csproj | 1 + .../NewInEFCore9/NullSemanticsSample.cs | 6 +- .../Miscellaneous/NewInEFCore9/QuerySample.cs | 4 +- .../NullableReferenceTypes/Program.cs | 15 +- .../SaveChangesInterception/Program.cs | 6 +- .../ModelBuildingConventionsSample.cs | 4 +- .../Modeling/BulkConfiguration/Program.cs | 14 +- samples/core/Modeling/DataSeeding/Program.cs | 15 +- samples/core/Modeling/DynamicModel/Program.cs | 14 +- samples/core/Modeling/EntityTypes/Program.cs | 13 +- .../Modeling/KeylessEntityTypes/Program.cs | 15 +- .../core/Modeling/OwnedEntities/Program.cs | 14 +- .../core/Modeling/Relationships/ManyToMany.cs | 13 +- .../core/Modeling/Relationships/Program.cs | 8 +- .../core/Modeling/TableSplitting/Program.cs | 16 +- .../CaseInsensitiveStrings.cs | 9 +- .../ValueConversions/CompositeValueObject.cs | 11 +- .../ValueConversions/EncryptPropertyValues.cs | 9 +- .../EnumToStringConversions.cs | 59 +++--- .../ValueConversions/FixedLengthStrings.cs | 9 +- .../ValueConversions/KeyValueObjects.cs | 11 +- .../MappingImmutableClassProperty.cs | 13 +- .../MappingImmutableStructProperty.cs | 13 +- .../ValueConversions/MappingListProperty.cs | 13 +- .../MappingListPropertyOld.cs | 13 +- .../OverridingByteArrayComparisons.cs | 13 +- .../ValueConversions/PreserveDateTimeKind.cs | 11 +- .../ValueConversions/PrimitiveCollection.cs | 13 +- .../core/Modeling/ValueConversions/Program.cs | 45 ++--- .../ValueConversions/SimpleValueObject.cs | 17 +- .../ValueConversions/ULongConcurrency.cs | 19 +- .../ValueConversions/ValueObjectCollection.cs | 13 +- .../ValueConversions/WithMappingHints.cs | 11 +- .../Controllers/WeatherForecastController.cs | 7 +- .../Controllers/WeatherForecastController.cs | 7 +- samples/core/Performance/Other/Other.csproj | 1 + samples/core/Performance/Other/Program.cs | 70 +++---- .../ClientEvaluation/ClientEvaluation.csproj | 1 + .../core/Querying/ClientEvaluation/Program.cs | 22 ++- .../core/Querying/NullSemantics/Program.cs | 40 ++-- samples/core/Querying/Overview/Program.cs | 20 +- samples/core/Querying/Pagination/Program.cs | 21 ++- .../Querying/QueryFilters/BloggingContext.cs | 6 +- samples/core/Querying/QueryFilters/Program.cs | 77 ++++---- samples/core/Querying/RelatedData/Program.cs | 99 +++++----- samples/core/Querying/SqlQueries/Program.cs | 59 +++--- samples/core/Querying/Tags/Program.cs | 19 +- samples/core/Querying/Tracking/Program.cs | 29 +-- .../UserDefinedFunctionMapping/Program.cs | 25 +-- samples/core/Saving/Basics/Sample.cs | 26 +-- .../Saving/CascadeDelete/BloggingContext.cs | 6 +- samples/core/Saving/CascadeDelete/Sample.cs | 67 +++---- .../core/Saving/Concurrency/BasicSample.cs | 29 +-- .../Concurrency/ConflictResolutionSample.cs | 17 +- samples/core/Saving/Disconnected/Sample.cs | 173 +++++++++--------- samples/core/Saving/Program.cs | 25 +-- samples/core/Saving/RelatedData/Sample.cs | 21 ++- .../Saving/Transactions/AmbientTransaction.cs | 13 +- .../Transactions/CommitableTransaction.cs | 15 +- .../Transactions/ControllingTransaction.cs | 19 +- .../Transactions/ExternalDbTransaction.cs | 17 +- .../Saving/Transactions/ManagingSavepoints.cs | 19 +- .../Saving/Transactions/SharingTransaction.cs | 21 ++- samples/core/Spatial/SqlServer/Program.cs | 19 +- .../ValueGeneration/ExplicitIdentityValues.cs | 19 +- .../Controllers/BloggingController.cs | 28 +-- .../BloggingControllerWithRepository.cs | 24 +-- .../BusinessLogic/BloggingRepository.cs | 16 +- .../BusinessLogic/IBloggingRepository.cs | 9 +- .../BloggingControllerTest.cs | 18 +- .../TestingWithTheDatabase.csproj | 1 + .../TransactionalBloggingControllerTest.cs | 10 +- .../InMemoryBloggingControllerTest.cs | 23 +-- .../RepositoryBloggingControllerTest.cs | 42 +++-- .../SqliteInMemoryBloggingControllerTest.cs | 23 +-- .../TestingWithoutTheDatabase.csproj | 1 + 188 files changed, 2422 insertions(+), 2267 deletions(-) diff --git a/entity-framework/core/managing-schemas/ensure-created.md b/entity-framework/core/managing-schemas/ensure-created.md index d5c2a07c7c..7e332b9f1c 100644 --- a/entity-framework/core/managing-schemas/ensure-created.md +++ b/entity-framework/core/managing-schemas/ensure-created.md @@ -8,31 +8,31 @@ uid: core/managing-schemas/ensure-created --- # Create and Drop APIs -The and methods provide a lightweight alternative to [Migrations](xref:core/managing-schemas/migrations/index) for managing the database schema. These methods are useful in scenarios when the data is transient and can be dropped when the schema changes. For example during prototyping, in tests, or for local caches. +The and methods provide a lightweight alternative to [Migrations](xref:core/managing-schemas/migrations/index) for managing the database schema. These methods are useful in scenarios when the data is transient and can be dropped when the schema changes. For example during prototyping, in tests, or for local caches. -Some providers (especially non-relational ones) don't support Migrations. For these providers, `EnsureCreated` is often the easiest way to initialize the database schema. +Some providers (especially non-relational ones) don't support Migrations. For these providers, `EnsureCreatedAsync` is often the easiest way to initialize the database schema. > [!WARNING] -> `EnsureCreated` and Migrations don't work well together. If you're using Migrations, don't use `EnsureCreated` to initialize the schema. +> `EnsureCreatedAsync` and Migrations don't work well together. If you're using Migrations, don't use `EnsureCreatedAsync` to initialize the schema. -Transitioning from `EnsureCreated` to Migrations is not a seamless experience. The simplest way to do it is to drop the database and re-create it using Migrations. If you anticipate using migrations in the future, it's best to just start with Migrations instead of using `EnsureCreated`. +Transitioning from `EnsureCreatedAsync` to Migrations is not a seamless experience. The simplest way to do it is to drop the database and re-create it using Migrations. If you anticipate using migrations in the future, it's best to just start with Migrations instead of using `EnsureCreatedAsync`. -## EnsureDeleted +## EnsureDeletedAsync -The `EnsureDeleted` method will drop the database if it exists. If you don't have the appropriate permissions, an exception is thrown. +The `EnsureDeletedAsync` method will drop the database if it exists. If you don't have the appropriate permissions, an exception is thrown. ```csharp // Drop the database if it exists -dbContext.Database.EnsureDeleted(); +await dbContext.Database.EnsureDeletedAsync(); ``` -## EnsureCreated +## EnsureCreatedAsync -`EnsureCreated` will create the database if it doesn't exist and initialize the database schema. If any tables exist (including tables for another `DbContext` class), the schema won't be initialized. +`EnsureCreatedAsync` will create the database if it doesn't exist and initialize the database schema. If any tables exist (including tables for another `DbContext` class), the schema won't be initialized. ```csharp // Create the database if it doesn't exist -dbContext.Database.EnsureCreated(); +dbContext.Database.EnsureCreatedAsync(); ``` > [!TIP] @@ -40,7 +40,7 @@ dbContext.Database.EnsureCreated(); ## SQL Script -To get the SQL used by `EnsureCreated`, you can use the method. +To get the SQL used by `EnsureCreatedAsync`, you can use the method. ```csharp var sql = dbContext.Database.GenerateCreateScript(); diff --git a/entity-framework/core/managing-schemas/migrations/applying.md b/entity-framework/core/managing-schemas/migrations/applying.md index 4ff1d478d8..b05fa4f460 100644 --- a/entity-framework/core/managing-schemas/migrations/applying.md +++ b/entity-framework/core/managing-schemas/migrations/applying.md @@ -317,26 +317,26 @@ It's possible for the application itself to apply migrations programmatically, t * It's important to be able to roll back an applied migration in case of an issue. The other strategies provide this easily and out of the box. * The SQL commands are applied directly by the program, without giving the developer a chance to inspect or modify them. This can be dangerous in a production environment. -To apply migrations programmatically, call `context.Database.Migrate()`. For example, a typical ASP.NET application can do the following: +To apply migrations programmatically, call `context.Database.MigrateAsync()`. For example, a typical ASP.NET application can do the following: ```csharp -public static void Main(string[] args) +public static async Task Main(string[] args) { var host = CreateHostBuilder(args).Build(); using (var scope = host.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); - db.Database.Migrate(); + await db.Database.MigrateAsync(); } host.Run(); } ``` -Note that `Migrate()` builds on top of the `IMigrator` service, which can be used for more advanced scenarios. Use `myDbContext.GetInfrastructure().GetService()` to access it. +Note that `MigrateAsync()` builds on top of the `IMigrator` service, which can be used for more advanced scenarios. Use `myDbContext.GetInfrastructure().GetService()` to access it. > [!WARNING] > > * Carefully consider before using this approach in production. Experience has shown that the simplicity of this deployment strategy is outweighed by the issues it creates. Consider generating SQL scripts from migrations instead. -> * Don't call `EnsureCreated()` before `Migrate()`. `EnsureCreated()` bypasses Migrations to create the schema, which causes `Migrate()` to fail. +> * Don't call `EnsureCreatedAsync()` before `MigrateAsync()`. `EnsureCreatedAsync()` bypasses Migrations to create the schema, which causes `MigrateAsync()` to fail. diff --git a/entity-framework/core/miscellaneous/connection-resiliency.md b/entity-framework/core/miscellaneous/connection-resiliency.md index 219bc39797..31cf6420b3 100644 --- a/entity-framework/core/miscellaneous/connection-resiliency.md +++ b/entity-framework/core/miscellaneous/connection-resiliency.md @@ -47,9 +47,9 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) ## Execution strategies and transactions -An execution strategy that automatically retries on failures needs to be able to play back each operation in a retry block that fails. When retries are enabled, each operation you perform via EF Core becomes its own retriable operation. That is, each query and each call to `SaveChanges()` will be retried as a unit if a transient failure occurs. +An execution strategy that automatically retries on failures needs to be able to play back each operation in a retry block that fails. When retries are enabled, each operation you perform via EF Core becomes its own retriable operation. That is, each query and each call to `SaveChangesAsync()` will be retried as a unit if a transient failure occurs. -However, if your code initiates a transaction using `BeginTransaction()` you are defining your own group of operations that need to be treated as a unit, and everything inside the transaction would need to be played back shall a failure occur. You will receive an exception like the following if you attempt to do this when using an execution strategy: +However, if your code initiates a transaction using `BeginTransactionAsync()` you are defining your own group of operations that need to be treated as a unit, and everything inside the transaction would need to be played back shall a failure occur. You will receive an exception like the following if you attempt to do this when using an execution strategy: > InvalidOperationException: The configured execution strategy 'SqlServerRetryingExecutionStrategy' does not support user-initiated transactions. Use the execution strategy returned by 'DbContext.Database.CreateExecutionStrategy()' to execute all the operations in the transaction as a retriable unit. diff --git a/entity-framework/core/miscellaneous/nullable-reference-types.md b/entity-framework/core/miscellaneous/nullable-reference-types.md index 019cb2f7ea..361b84fdb9 100644 --- a/entity-framework/core/miscellaneous/nullable-reference-types.md +++ b/entity-framework/core/miscellaneous/nullable-reference-types.md @@ -95,9 +95,9 @@ Another strategy is to use non-nullable auto-properties, but to initialize them When dealing with optional relationships, it's possible to encounter compiler warnings where an actual `null` reference exception would be impossible. When translating and executing your LINQ queries, EF Core guarantees that if an optional related entity does not exist, any navigation to it will simply be ignored, rather than throwing. However, the compiler is unaware of this EF Core guarantee, and produces warnings as if the LINQ query were executed in memory, with LINQ to Objects. As a result, it is necessary to use the null-forgiving operator (!) to inform the compiler that an actual `null` value isn't possible: ```csharp -var order = context.Orders +var order = await context.Orders .Where(o => o.OptionalInfo!.SomeProperty == "foo") - .ToList(); + .ToListAsync(); ``` A similar issue occurs when including multiple levels of relationships across optional navigations: diff --git a/entity-framework/core/modeling/data-seeding.md b/entity-framework/core/modeling/data-seeding.md index 2d6fe7b2f5..22759ad633 100644 --- a/entity-framework/core/modeling/data-seeding.md +++ b/entity-framework/core/modeling/data-seeding.md @@ -39,7 +39,7 @@ These methods can be set up in the [options configuration step](/ef/core/dbconte ## Custom initialization logic -A straightforward and powerful way to perform data seeding is to use [`DbContext.SaveChanges()`](xref:core/saving/index) before the main application logic begins execution. It is recommended to use `UseSeeding` and `UseAsyncSeeding` for that purpose, however sometimes using these methods is not a good solution. An example scenario is when seeding requires using two different contexts in one transaction. Below is a code sample performing custom initialization in the application directly: +A straightforward and powerful way to perform data seeding is to use [`DbContext.SaveChangesAsync()`](xref:core/saving/index) before the main application logic begins execution. It is recommended to use `UseSeeding` and `UseAsyncSeeding` for that purpose, however sometimes using these methods is not a good solution. An example scenario is when seeding requires using two different contexts in one transaction. Below is a code sample performing custom initialization in the application directly: [!code-csharp[Main](../../../samples/core/Modeling/DataSeeding/Program.cs?name=CustomSeeding)] @@ -85,7 +85,7 @@ Once the data has been added to the model, [migrations](xref:core/managing-schem > [!TIP] > If you need to apply migrations as part of an automated deployment you can [create a SQL script](xref:core/managing-schemas/migrations/applying#sql-scripts) that can be previewed before execution. -Alternatively, you can use `context.Database.EnsureCreated()` to create a new database containing the managed data, for example for a test database or when using the in-memory provider or any non-relational database. Note that if the database already exists, `EnsureCreated()` will neither update the schema nor managed data in the database. For relational databases you shouldn't call `EnsureCreated()` if you plan to use Migrations. +Alternatively, you can use `context.Database.EnsureCreatedAsync()` to create a new database containing the managed data, for example for a test database or when using the in-memory provider or any non-relational database. Note that if the database already exists, `EnsureCreatedAsync()` will neither update the schema nor managed data in the database. For relational databases you shouldn't call `EnsureCreatedAsync()` if you plan to use Migrations. > [!NOTE] > Populating the database using the `HasData` method used to be referred to as "data seeding". This naming sets incorrect expectations, as the feature has a number of limitations and is only appropriate for specific types of data. That is why we decided to rename it to "model managed data". `UseSeeding` and `UseAsyncSeeding` methods should be used for general purpose data seeding. diff --git a/entity-framework/core/performance/efficient-updating.md b/entity-framework/core/performance/efficient-updating.md index 842aab9b1d..7a2a6c4f81 100644 --- a/entity-framework/core/performance/efficient-updating.md +++ b/entity-framework/core/performance/efficient-updating.md @@ -30,7 +30,7 @@ foreach (var employee in context.Employees) { employee.Salary += 1000; } -context.SaveChanges(); +await context.SaveChangesAsync(); ``` While this is perfectly valid code, let's analyze what it does from a performance perspective: @@ -39,10 +39,10 @@ While this is perfectly valid code, let's analyze what it does from a performanc * EF Core's change tracking creates snapshots when loading the entities, and then compares those snapshots to the instances to find out which properties changed. * Typically, a second database roundtrip is performed to save all the changes (note that some database providers split the changes into multiples roundtrips). Although this batching behavior is far better than doing a roundtrip for each update, EF Core still sends an UPDATE statement per employee, and the database must execute each statement separately. -Starting with EF Core 7.0, you can use the `ExecuteUpdate` and `ExecuteDelete` methods to do the same thing far more efficiently: +Starting with EF Core 7.0, you can use the `ExecuteUpdateAsync` and `ExecuteDeleteAsync` methods to do the same thing far more efficiently: ```c# -context.Employees.ExecuteUpdate(s => s.SetProperty(e => e.Salary, e => e.Salary + 1000)); +await context.Employees.ExecuteUpdateAsync(s => s.SetProperty(e => e.Salary, e => e.Salary + 1000)); ``` This sends the following SQL statement to the database: diff --git a/entity-framework/core/providers/cosmos/querying.md b/entity-framework/core/providers/cosmos/querying.md index 3e49e8d88d..4d583614c5 100644 --- a/entity-framework/core/providers/cosmos/querying.md +++ b/entity-framework/core/providers/cosmos/querying.md @@ -123,11 +123,11 @@ A common way to implement pagination with databases is to use the `Skip` and `Ta ```csharp var position = 20; -var nextPage = context.Session +var nextPage = await context.Session .OrderBy(s => s.Id) .Skip(position) .Take(10) - .ToList(); + .ToListAsync(); ``` Unfortunately, this technique is quite inefficient and can considerably increase querying costs. Azure Cosmos DB provides a special mechanism for paginating through the result of a query, via the use of _continuation tokens_: diff --git a/entity-framework/core/providers/sql-server/value-generation.md b/entity-framework/core/providers/sql-server/value-generation.md index 1d0df4d48e..e564e736d0 100644 --- a/entity-framework/core/providers/sql-server/value-generation.md +++ b/entity-framework/core/providers/sql-server/value-generation.md @@ -21,7 +21,7 @@ By default, IDENTITY columns start off at 1 (the seed), and increment by 1 each ### Inserting explicit values into IDENTITY columns -By default, SQL Server doesn't allow inserting explicit values into IDENTITY columns. To do so, you must manually enable `IDENTITY_INSERT` before calling `SaveChanges()`, as follows: +By default, SQL Server doesn't allow inserting explicit values into IDENTITY columns. To do so, you must manually enable `IDENTITY_INSERT` before calling `SaveChangesAsync()`, as follows: [!code-csharp[Main](../../../../samples/core/SqlServer/ValueGeneration/ExplicitIdentityValues.cs?name=ExplicitIdentityValues)] diff --git a/entity-framework/core/querying/related-data/eager.md b/entity-framework/core/querying/related-data/eager.md index 59f6e9552f..49886b9a89 100644 --- a/entity-framework/core/querying/related-data/eager.md +++ b/entity-framework/core/querying/related-data/eager.md @@ -70,10 +70,10 @@ Alternatively, identical operations can be applied for each navigation that is i Example: ```csharp -var orders = context.Orders.Where(o => o.Id > 1000).ToList(); +var orders = await context.Orders.Where(o => o.Id > 1000).ToListAsync(); // customer entities will have references to all orders where Id > 1000, rather than > 5000 -var filtered = context.Customers.Include(c => c.Orders.Where(o => o.Id > 5000)).ToList(); +var filtered = await context.Customers.Include(c => c.Orders.Where(o => o.Id > 5000)).ToListAsync(); ``` > [!NOTE] diff --git a/entity-framework/core/querying/single-split-queries.md b/entity-framework/core/querying/single-split-queries.md index a1a618ab4c..99ca263204 100644 --- a/entity-framework/core/querying/single-split-queries.md +++ b/entity-framework/core/querying/single-split-queries.md @@ -16,10 +16,10 @@ When working against relational databases, EF loads related entities by introduc Let's examine the following LINQ query and its translated SQL equivalent: ```c# -var blogs = ctx.Blogs +var blogs = await ctx.Blogs .Include(b => b.Posts) .Include(b => b.Contributors) - .ToList(); + .ToListAsync(); ``` ```sql @@ -35,10 +35,10 @@ In this example, since both `Posts` and `Contributors` are collection navigation Note that cartesian explosion does not occur when the two JOINs aren't at the same level: ```c# -var blogs = ctx.Blogs +var blogs = await ctx.Blogs .Include(b => b.Posts) .ThenInclude(p => p.Comments) - .ToList(); + .ToListAsync(); ``` ```sql @@ -56,9 +56,9 @@ In this query, `Comments` is a collection navigation of `Post`, unlike `Contribu JOINs can create another type of performance issue. Let's examine the following query, which only loads a single collection navigation: ```c# -var blogs = ctx.Blogs +var blogs = await ctx.Blogs .Include(b => b.Posts) - .ToList(); + .ToListAsync(); ``` ```sql @@ -73,14 +73,14 @@ Examining at the projected columns, each row returned by this query contains pro If you don't actually need the huge column, it's easy to simply not query for it: ```c# -var blogs = ctx.Blogs +var blogs = await ctx.Blogs .Select(b => new { b.Id, b.Name, b.Posts }) - .ToList(); + .ToListAsync(); ``` By using a projection to explicitly choose which columns you want, you can omit big columns and improve performance; note that this is a good idea regardless of data duplication, so consider doing it even when not loading a collection navigation. However, since this projects the blog to an anonymous type, the blog isn't tracked by EF and changes to it can't be saved back as usual. diff --git a/entity-framework/core/querying/sql-queries.md b/entity-framework/core/querying/sql-queries.md index 7bc0f3a75f..a3c59fc00e 100644 --- a/entity-framework/core/querying/sql-queries.md +++ b/entity-framework/core/querying/sql-queries.md @@ -17,9 +17,9 @@ Entity Framework Core allows you to drop down to SQL queries when working with a You can use to begin a LINQ query based on a SQL query: ```csharp -var blogs = context.Blogs +var blogs = await context.Blogs .FromSql($"SELECT * FROM dbo.Blogs") - .ToList(); + .ToListAsync(); ``` > [!NOTE] @@ -29,9 +29,9 @@ var blogs = context.Blogs SQL queries can be used to execute a stored procedure which returns entity data: ```csharp -var blogs = context.Blogs +var blogs = await context.Blogs .FromSql($"EXECUTE dbo.GetMostPopularBlogs") - .ToList(); + .ToListAsync(); ``` > [!NOTE] @@ -52,9 +52,9 @@ The following example passes a single parameter to a stored procedure by includi ```csharp var user = "johndoe"; -var blogs = context.Blogs +var blogs = await context.Blogs .FromSql($"EXECUTE dbo.GetMostPopularBlogsForUser {user}") - .ToList(); + .ToListAsync(); ``` While this syntax may look like regular C# [string interpolation](/dotnet/csharp/language-reference/tokens/interpolated), the supplied value is wrapped in a `DbParameter` and the generated parameter name inserted where the `{0}` placeholder was specified. This makes safe from SQL injection attacks, and sends the value efficiently and correctly to the database. @@ -64,9 +64,9 @@ When executing stored procedures, it can be useful to use named parameters in th ```csharp var user = new SqlParameter("user", "johndoe"); -var blogs = context.Blogs +var blogs = await context.Blogs .FromSql($"EXECUTE dbo.GetMostPopularBlogsForUser @filterByUser={user}") - .ToList(); + .ToListAsync(); ``` If you need more control over the database parameter being sent, you can also construct a `DbParameter` and supply it as a parameter value. This allows you to set the precise database type of the parameter, or facets such as its size, precision or length: @@ -74,9 +74,9 @@ If you need more control over the database parameter being sent, you can also co ```csharp var user = new SqlParameter("user", "johndoe"); -var blogs = context.Blogs +var blogs = await context.Blogs .FromSql($"EXECUTE dbo.GetMostPopularBlogsForUser {user}") - .ToList(); + .ToListAsync(); ``` > [!NOTE] @@ -91,9 +91,9 @@ var blogs = context.Blogs var propertyName = "User"; var propertyValue = "johndoe"; -var blogs = context.Blogs +var blogs = await context.Blogs .FromSql($"SELECT * FROM [Blogs] WHERE {propertyName} = {propertyValue}") - .ToList(); + .ToListAsync(); ``` This code doesn't work, since databases do not allow parameterizing column names (or any other part of the schema). @@ -106,9 +106,9 @@ If you've decided you do want to dynamically construct your SQL, you'll have to var columnName = "Url"; var columnValue = new SqlParameter("columnValue", "http://SomeURL"); -var blogs = context.Blogs +var blogs = await context.Blogs .FromSqlRaw($"SELECT * FROM [Blogs] WHERE {columnName} = @columnValue", columnValue) - .ToList(); + .ToListAsync(); ``` In the above code, the column name is inserted directly into the SQL, using C# string interpolation. It is your responsibility to make sure this string value is safe, sanitizing it if it comes from an unsafe origin; this means detecting special characters such as semicolons, comments, and other SQL constructs, and either escaping them properly or rejecting such inputs. @@ -126,11 +126,11 @@ You can compose on top of the initial SQL query using LINQ operators; EF Core wi ```csharp var searchTerm = "Lorem ipsum"; -var blogs = context.Blogs +var blogs = await context.Blogs .FromSql($"SELECT * FROM dbo.SearchBlogs({searchTerm})") .Where(b => b.Rating > 3) .OrderByDescending(b => b.Rating) - .ToList(); + .ToListAsync(); ``` The above query generates the following SQL: @@ -151,10 +151,10 @@ The [`Include`](xref:core/querying/related-data/eager) operator can be used to l ```csharp var searchTerm = "Lorem ipsum"; -var blogs = context.Blogs +var blogs = await context.Blogs .FromSql($"SELECT * FROM dbo.SearchBlogs({searchTerm})") .Include(b => b.Posts) - .ToList(); + .ToListAsync(); ``` Composing with LINQ requires your SQL query to be composable, since EF Core will treat the supplied SQL as a subquery. Composable SQL queries generally begin with the `SELECT` keyword, and cannot contain SQL features that aren't valid in a subquery, such as: @@ -174,10 +174,10 @@ The following example uses a SQL query that selects from a Table-Valued Function ```csharp var searchTerm = "Lorem ipsum"; -var blogs = context.Blogs +var blogs = await context.Blogs .FromSql($"SELECT * FROM dbo.SearchBlogs({searchTerm})") .AsNoTracking() - .ToList(); + .ToListAsync(); ``` ## Querying scalar (non-entity) types @@ -190,29 +190,29 @@ While ($"SELECT [BlogId] FROM [Blogs]") - .ToList(); + .ToListAsync(); ``` ### [SQLite](#tab/sqlite) ```c# -var ids = context.Database +var ids = await context.Database .SqlQuery($""" SELECT "BlogId" FROM "Blogs" """) - .ToList(); + .ToListAsync(); ``` ### [PostgreSQL](#tab/postgres) ```c# -var ids = context.Database +var ids = await context.Database .SqlQuery($""" SELECT "BlogId" FROM "Blogs" """) - .ToList(); + .ToListAsync(); ``` *** @@ -222,32 +222,32 @@ You can also compose LINQ operators over your SQL query. However, since your SQL ### [SQL Server](#tab/sqlserver) ```c# -var overAverageIds = context.Database +var overAverageIds = await context.Database .SqlQuery($"SELECT [BlogId] AS [Value] FROM [Blogs]") .Where(id => id > context.Blogs.Average(b => b.BlogId)) - .ToList(); + .ToListAsync(); ``` ### [SQLite](#tab/sqlite) ```c# -var overAverageIds = context.Database +var overAverageIds = await context.Database .SqlQuery($""" SELECT "BlogId" AS "Value" FROM "Blogs" """) .Where(id => id > context.Blogs.Average(b => b.BlogId)) - .ToList(); + .ToListAsync(); ``` ### [PostgreSQL](#tab/postgres) ```c# -var overAverageIds = context.Database +var overAverageIds = await context.Database .SqlQuery($""" SELECT "BlogId" AS "Value" FROM "Blogs" """) .Where(id => id > context.Blogs.Average(b => b.BlogId)) - .ToList(); + .ToListAsync(); ``` *** diff --git a/entity-framework/core/saving/concurrency.md b/entity-framework/core/saving/concurrency.md index e187b3a8c4..304003d956 100644 --- a/entity-framework/core/saving/concurrency.md +++ b/entity-framework/core/saving/concurrency.md @@ -35,9 +35,9 @@ public class Person In SQL Server, this configures a concurrency token that automatically changes in the database every time the row is changed (more details are available below). With this configuration in place, let's examine what happens with a simple update operation: ```csharp -var person = context.People.Single(b => b.FirstName == "John"); +var person = await context.People.SingleAsync(b => b.FirstName == "John"); person.FirstName = "Paul"; -context.SaveChanges(); +await context.SaveChangesAsync(); ``` 1. In the first step, a Person is loaded from the database; this includes the concurrency token, which is now tracked as usual by EF along with the rest of the properties. @@ -123,10 +123,10 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) Since this property isn't database-generated, you must assign it in application whenever persisting changes: ```c# -var person = context.People.Single(b => b.FirstName == "John"); +var person = await context.People.SingleAsync(b => b.FirstName == "John"); person.FirstName = "Paul"; person.Version = Guid.NewGuid(); -context.SaveChanges(); +await context.SaveChangesAsync(); ``` If you want a new GUID value to always be assigned, you can do this via a [`SaveChanges` interceptor](xref:core/logging-events-diagnostics/interceptors#savechanges-interception). However, one advantage of manually managing the concurrency token is that you can control precisely when it gets regenerated, to avoid needless concurrency conflicts. diff --git a/entity-framework/core/saving/execute-insert-update-delete.md b/entity-framework/core/saving/execute-insert-update-delete.md index 29c7cb6b35..1cb676071e 100644 --- a/entity-framework/core/saving/execute-insert-update-delete.md +++ b/entity-framework/core/saving/execute-insert-update-delete.md @@ -17,12 +17,12 @@ uid: core/saving/execute-insert-update-delete Let's assume that you need to delete all Blogs with a rating below a certain threshold. The traditional approach requires you to do the following: ```c# -foreach (var blog in context.Blogs.Where(b => b.Rating < 3)) +await foreach (var blog in context.Blogs.Where(b => b.Rating < 3).AsAsyncEnumerable()) { context.Blogs.Remove(blog); } -context.SaveChanges(); +await context.SaveChangesAsync(); ``` This is quite an inefficient way to perform this task: we query the database for all Blogs matching our filter, and then we query, materialize and track all those instances; the number of matching entities could be huge. We then tell EF's change tracker that each Blog needs to be removed, and apply those changes by calling , which generates a `DELETE` statement for each and every one of them. @@ -30,7 +30,7 @@ This is quite an inefficient way to perform this task: we query the database for Here is the same task performed via the API: ```c# -context.Blogs.Where(b => b.Rating < 3).ExecuteDelete(); +await context.Blogs.Where(b => b.Rating < 3).ExecuteDeleteAsync(); ``` This uses the familiar LINQ operators to determine which Blogs should be affected - just as if we were querying them - and then tells EF to execute a SQL `DELETE` against the database: @@ -48,9 +48,9 @@ Aside from being simpler and shorter, this executes very efficiently in the data Rather than deleting these Blogs, what if we wanted to change a property to indicate that they should be hidden instead? provides a similar way to express a SQL `UPDATE` statement: ```c# -context.Blogs +await context.Blogs .Where(b => b.Rating < 3) - .ExecuteUpdate(setters => setters.SetProperty(b => b.IsVisible, false)); + .ExecuteUpdateAsync(setters => setters.SetProperty(b => b.IsVisible, false)); ``` Like with `ExecuteDelete`, we first use LINQ to determine which Blogs should be affected; but with `ExecuteUpdate` we also need to express the change to be applied to the matching Blogs. This is done by calling `SetProperty` within the `ExecuteUpdate` call, and providing it with two arguments: the property to be changed (`IsVisible`), and the new value it should have (`false`). This causes the following SQL to be executed: @@ -67,9 +67,9 @@ WHERE [b].[Rating] < 3 `ExecuteUpdate` allows updating multiple properties in a single invocation. For example, to both set `IsVisible` to false and to set `Rating` to zero, simply chain additional `SetProperty` calls together: ```c# -context.Blogs +await context.Blogs .Where(b => b.Rating < 3) - .ExecuteUpdate(setters => setters + .ExecuteUpdateAsync(setters => setters .SetProperty(b => b.IsVisible, false) .SetProperty(b => b.Rating, 0)); ``` @@ -89,9 +89,9 @@ WHERE [b].[Rating] < 3 The above examples updated the property to a new constant value. `ExecuteUpdate` also allows referencing the existing property value when calculating the new value; for example, to increase the rating of all matching Blogs by one, use the following: ```c# -context.Blogs +await context.Blogs .Where(b => b.Rating < 3) - .ExecuteUpdate(setters => setters.SetProperty(b => b.Rating, b => b.Rating + 1)); + .ExecuteUpdateAsync(setters => setters.SetProperty(b => b.Rating, b => b.Rating + 1)); ``` Note that the second argument to `SetProperty` is now a lambda function, and not a constant as before. Its `b` parameter represents the Blog being updated; within that lambda, `b.Rating` thus contains the rating before any change occurred. This executes the following SQL: @@ -108,16 +108,16 @@ WHERE [b].[Rating] < 3 `ExecuteUpdate` does not currently support referencing navigations within the `SetProperty` lambda. For example, let's say we want to update all the Blogs' ratings so that each Blog's new rating is the average of all its Posts' ratings. We may try to use `ExecuteUpdate` as follows: ```c# -context.Blogs.ExecuteUpdate( +await context.Blogs.ExecuteUpdateAsync( setters => setters.SetProperty(b => b.Rating, b => b.Posts.Average(p => p.Rating))); ``` However, EF does allow performing this operation by first using `Select` to calculate the average rating and project it to an anonymous type, and then using `ExecuteUpdate` over that: ```c# -context.Blogs +await context.Blogs .Select(b => new { Blog = b, NewRating = b.Posts.Average(p => p.Rating) }) - .ExecuteUpdate(setters => setters.SetProperty(b => b.Blog.Rating, b => b.NewRating)); + .ExecuteUpdateAsync(setters => setters.SetProperty(b => b.Blog.Rating, b => b.NewRating)); ``` This executes the following SQL: @@ -141,16 +141,16 @@ Consider the following code: ```c# // 1. Query the blog with the name `SomeBlog`. Since EF queries are tracking by default, the Blog is now tracked by EF's change tracker. -var blog = context.Blogs.Single(b => b.Name == "SomeBlog"); +var blog = await context.Blogs.SingleAsync(b => b.Name == "SomeBlog"); // 2. Increase the rating of all blogs in the database by one. This executes immediately. -context.Blogs.ExecuteUpdate(setters => setters.SetProperty(b => b.Rating, b => b.Rating + 1)); +await context.Blogs.ExecuteUpdateAsync(setters => setters.SetProperty(b => b.Rating, b => b.Rating + 1)); // 3. Increase the rating of `SomeBlog` by two. This modifies the .NET `Rating` property and is not yet persisted to the database. blog.Rating += 2; // 4. Persist tracked changes to the database. -context.SaveChanges(); +await context.SaveChangesAsync(); ``` Crucially, when `ExecuteUpdate` is invoked and all Blogs are updated in the database, EF's change tracker is **not** updated, and the tracked .NET instance still has its original rating value, from the point at which it was queried. Let's assume that the Blog's rating was originally 5; after the 3rd line executes, the rating in the database is now 6 (because of the `ExecuteUpdate`), whereas the rating in the tracked .NET instance is 7. When `SaveChanges` is called, EF detects that the new value 7 is different from the original value 5, and persists that change. The change performed by `ExecuteUpdate` is overwritten and not taken into account. @@ -162,12 +162,12 @@ As a result, it is usually a good idea to avoid mixing both tracked `SaveChanges Continuing on the above, it's important to understand that `ExecuteUpdate` and `ExecuteDelete` do not implicitly start a transaction they're invoked. Consider the following code: ```c# -context.Blogs.ExecuteUpdate(/* some update */); -context.Blogs.ExecuteUpdate(/* another update */); +await context.Blogs.ExecuteUpdateAsync(/* some update */); +await context.Blogs.ExecuteUpdateAsync(/* another update */); -var blog = context.Blogs.Single(b => b.Name == "SomeBlog"); +var blog = await context.Blogs.SingleAsync(b => b.Name == "SomeBlog"); blog.Rating += 2; -context.SaveChanges(); +await context.SaveChangesAsync(); ``` Each `ExecuteUpdate` call causes a single SQL `UPDATE` to be sent to the database. Since no transaction is created, if any sort of failure prevents the second `ExecuteUpdate` from completing successfully, the effects of the first one are still persisted to the database. In fact, the four operations above - two invocations of `ExecuteUpdate`, a query and `SaveChanges` - each executes within its own transaction. To wrap multiple operations in a single transaction, explicitly start a transaction with : @@ -193,9 +193,9 @@ However, both these methods do return the number of rows that were affected by t ```c# // (load the ID and concurrency token for a Blog in the database) -var numUpdated = context.Blogs +var numUpdated = await context.Blogs .Where(b => b.Id == id && b.ConcurrencyToken == concurrencyToken) - .ExecuteUpdate(/* ... */); + .ExecuteUpdateAsync(/* ... */); if (numUpdated == 0) { throw new Exception("Update failed!"); diff --git a/entity-framework/core/saving/index.md b/entity-framework/core/saving/index.md index 267149d5c6..5df7264018 100644 --- a/entity-framework/core/saving/index.md +++ b/entity-framework/core/saving/index.md @@ -16,9 +16,9 @@ In many scenarios, your program needs to query some data from the database, perf ```c# using (var context = new BloggingContext()) { - var blog = context.Blogs.Single(b => b.Url == "http://example.com"); + var blog = await context.Blogs.SingleAsync(b => b.Url == "http://example.com"); blog.Url = "http://example.com/blog"; - context.SaveChanges(); + await context.SaveChangesAsync(); } ``` diff --git a/entity-framework/core/testing/testing-without-the-database.md b/entity-framework/core/testing/testing-without-the-database.md index 3cd8c24f44..6910b69cda 100644 --- a/entity-framework/core/testing/testing-without-the-database.md +++ b/entity-framework/core/testing/testing-without-the-database.md @@ -28,14 +28,14 @@ public class BloggingRepository : IBloggingRepository public BloggingRepository(BloggingContext context) => _context = context; - public Blog GetBlogByName(string name) - => _context.Blogs.FirstOrDefault(b => b.Name == name); + public async Task GetBlogByNameAsync(string name) + => await _context.Blogs.FirstOrDefaultAsync(b => b.Name == name); // Other code... } ``` -There's not much to it: the repository simply wraps an EF Core context, and exposes methods which execute the database queries and updates on it. A key point to note is that our `GetAllBlogs` method returns `IEnumerable`, and not `IQueryable`. Returning the latter would mean that query operators can still be composed over the result, requiring that EF Core still be involved in translating the query; this would defeat the purpose of having a repository in the first place. `IEnumerable` allows us to easily stub or mock what the repository returns. +There's not much to it: the repository simply wraps an EF Core context, and exposes methods which execute the database queries and updates on it. A key point to note is that our `GetAllBlogs` method returns `IAsyncEnumerable` (or `IEnumerable`), and not `IQueryable`. Returning the latter would mean that query operators can still be composed over the result, requiring that EF Core still be involved in translating the query; this would defeat the purpose of having a repository in the first place. `IAsyncEnumerable` allows us to easily stub or mock what the repository returns. For an ASP.NET Core application, we need to register the repository as a service in dependency injection by adding the following to the application's `ConfigureServices`: diff --git a/entity-framework/core/what-is-new/ef-core-2.0/upgrade.md b/entity-framework/core/what-is-new/ef-core-2.0/upgrade.md index f9855312b4..1332ebf0a9 100644 --- a/entity-framework/core/what-is-new/ef-core-2.0/upgrade.md +++ b/entity-framework/core/what-is-new/ef-core-2.0/upgrade.md @@ -152,17 +152,17 @@ public class Person ... var person = new Person(); context.People.Add(person); -context.SaveChanges(); +await context.SaveChangesAsync(); ... // returns one result -context.People.ToList(); +await context.People.ToListAsync(); // returns no results because 'NativeLanguage' navigation is required but has not been provided -context.People.Include(p => p.NativeLanguage).ToList(); +await context.People.Include(p => p.NativeLanguage).ToListAsync(); // returns one result because 'Sibling' navigation is optional so it doesn't have to be provided -context.People.Include(p => p.Sibling).ToList(); +await context.People.Include(p => p.Sibling).ToListAsync(); ``` ## Read-only API changes diff --git a/entity-framework/core/what-is-new/ef-core-2.1.md b/entity-framework/core/what-is-new/ef-core-2.1.md index 3a3464dfb2..3fa73195e8 100644 --- a/entity-framework/core/what-is-new/ef-core-2.1.md +++ b/entity-framework/core/what-is-new/ef-core-2.1.md @@ -117,7 +117,7 @@ var query = context.Customers.Select( c => c.Orders.Where(o => o.Amount > 100).Select(o => o.Amount)); ``` -By including `ToList()` in the right place, you indicate that buffering is appropriate for the Orders, which enable the optimization: +By including `ToListAsync()` in the right place, you indicate that buffering is appropriate for the Orders, which enable the optimization: ```csharp var query = context.Customers.Select( diff --git a/entity-framework/core/what-is-new/ef-core-2.2.md b/entity-framework/core/what-is-new/ef-core-2.2.md index 94e4711721..0b92c1fa56 100644 --- a/entity-framework/core/what-is-new/ef-core-2.2.md +++ b/entity-framework/core/what-is-new/ef-core-2.2.md @@ -49,7 +49,7 @@ using (var context = new MyDbContext()) Name = "Bill", Location = new Point(-122.34877, 47.6233355) {SRID = 4326 } }); - context.SaveChanges(); + await context.SaveChangesAsync(); } ``` @@ -57,9 +57,9 @@ And you can execute database queries based on spatial data and operations: ```csharp var nearestFriends = - (from f in context.Friends + await (from f in context.Friends orderby f.Location.Distance(myLocation) descending - select f).Take(5).ToList(); + select f).Take(5).ToListAsync(); ``` For more information on this feature, see the [spatial types documentation](xref:core/modeling/spatial). @@ -95,9 +95,9 @@ Using the spatial query from a previous example: ```csharp var nearestFriends = - (from f in context.Friends.TagWith(@"This is my spatial query!") + await (from f in context.Friends.TagWith(@"This is my spatial query!") orderby f.Location.Distance(myLocation) descending - select f).Take(5).ToList(); + select f).Take(5).ToListAsync(); ``` This LINQ query will produce the following SQL output: diff --git a/entity-framework/core/what-is-new/ef-core-3.x/breaking-changes.md b/entity-framework/core/what-is-new/ef-core-3.x/breaking-changes.md index 87c84b8790..af069a4078 100644 --- a/entity-framework/core/what-is-new/ef-core-3.x/breaking-changes.md +++ b/entity-framework/core/what-is-new/ef-core-3.x/breaking-changes.md @@ -100,7 +100,7 @@ Besides this, automatic client evaluation can lead to issues in which improving #### Mitigations -If a query can't be fully translated, then either rewrite the query in a form that can be translated, or use `AsEnumerable()`, `ToList()`, or similar to explicitly bring data back to the client where it can then be further processed using LINQ-to-Objects. +If a query can't be fully translated, then either rewrite the query in a form that can be translated, or use `AsEnumerableAsync()`, `ToListAsync()`, or similar to explicitly bring data back to the client where it can then be further processed using LINQ-to-Objects. @@ -266,7 +266,7 @@ Specifying `FromSql` anywhere other than on a `DbSet` had no added meaning or ad Before EF Core 3.0, the same entity instance would be used for every occurrence of an entity with a given type and ID. This matches the behavior of tracking queries. For example, this query: ```csharp -var results = context.Products.Include(e => e.Category).AsNoTracking().ToList(); +var results = await context.Products.Include(e => e.Category).AsNoTracking().ToListAsync(); ``` would return the same `Category` instance for each `Product` that is associated with the given category. @@ -792,11 +792,11 @@ using (new TransactionScope()) using (AdventureWorks context = new AdventureWorks()) { context.ProductCategories.Add(new ProductCategory()); - context.SaveChanges(); + await context.SaveChangesAsync(); // Old behavior: Connection is still open at this point - var categories = context.ProductCategories().ToList(); + var categories = await context.ProductCategories().ToListAsync(); } } ``` @@ -818,12 +818,12 @@ using (new TransactionScope()) { using (AdventureWorks context = new AdventureWorks()) { - context.Database.OpenConnection(); + await context.Database.OpenConnectionAsync(); context.ProductCategories.Add(new ProductCategory()); - context.SaveChanges(); + await context.SaveChangesAsync(); - var categories = context.ProductCategories().ToList(); - context.Database.CloseConnection(); + var categories = await context.ProductCategories().ToListAsync(); + await context.Database.CloseConnectionAsync(); } } ``` diff --git a/entity-framework/core/what-is-new/ef-core-5.0/breaking-changes.md b/entity-framework/core/what-is-new/ef-core-5.0/breaking-changes.md index 0ce31c6d78..122e9a3c2c 100644 --- a/entity-framework/core/what-is-new/ef-core-5.0/breaking-changes.md +++ b/entity-framework/core/what-is-new/ef-core-5.0/breaking-changes.md @@ -656,16 +656,16 @@ For correlated collection scenarios we need to know entity's primary key in orde Rewrite the query to not use `GroupBy` or `Distinct` operations on the inner collection, and perform these operations on the client instead. ```csharp -context.Parents +(await context.Parents .Select(p => p.Children.Select(c => c.School)) - .ToList() + .ToListAsync()) .Select(x => x.GroupBy(c => c).Select(g => g.Key)) ``` ```csharp -context.Parents +(await context.Parents .Select(p => p.Children.Select(c => c.School)) - .ToList() + .ToListAsync()) .Select(x => x.Distinct()) ``` diff --git a/entity-framework/core/what-is-new/ef-core-5.0/whatsnew.md b/entity-framework/core/what-is-new/ef-core-5.0/whatsnew.md index 07ee518023..f8e730b7ab 100644 --- a/entity-framework/core/what-is-new/ef-core-5.0/whatsnew.md +++ b/entity-framework/core/what-is-new/ef-core-5.0/whatsnew.md @@ -47,9 +47,9 @@ EF Core 5.0 now allows a single LINQ query including related collections to be s For example, consider a query that pulls in two levels of related collections using `Include`: ```csharp -var artists = context.Artists +var artists = await context.Artists .Include(e => e.Albums) - .ToList(); + .ToListAsync(); ``` By default, EF Core will generate the following SQL when using the SQLite provider: @@ -103,9 +103,9 @@ For further information, [see the documentation on logging and interception](xre The `Include` method now supports filtering of the entities included: ```csharp -var blogs = context.Blogs +var blogs = await context.Blogs .Include(e => e.Posts.Where(p => p.Title.Contains("Cheese"))) - .ToList(); + .ToListAsync(); ``` This query will return blogs together with each associated post, but only when the post title contains "Cheese". diff --git a/entity-framework/core/what-is-new/ef-core-6.0/breaking-changes.md b/entity-framework/core/what-is-new/ef-core-6.0/breaking-changes.md index f8e0df12f0..a63f95e9e0 100644 --- a/entity-framework/core/what-is-new/ef-core-6.0/breaking-changes.md +++ b/entity-framework/core/what-is-new/ef-core-6.0/breaking-changes.md @@ -770,7 +770,7 @@ public class Bar A no-tracking query for `Foo` including `Bar` set `Foo.Bar` to the entity queried from the database. For example, this code: ```csharp -var foo = context.Foos.AsNoTracking().Include(e => e.Bar).Single(); +var foo = await context.Foos.AsNoTracking().Include(e => e.Bar).SingleAsync(); Console.WriteLine($"Foo.Bar.Id = {foo.Bar.Id}"); ``` @@ -779,7 +779,7 @@ Printed `Foo.Bar.Id = 1`. However, the same query run for tracking didn't overwrite `Foo.Bar` with the entity queried from the database. For example, this code: ```csharp -var foo = context.Foos.Include(e => e.Bar).Single(); +var foo = await context.Foos.Include(e => e.Bar).SingleAsync(); Console.WriteLine($"Foo.Bar.Id = {foo.Bar.Id}"); ``` @@ -790,14 +790,14 @@ Printed `Foo.Bar.Id = 0`. In EF Core 6.0, the behavior of tracking queries now matches that of no-tracking queries. This means that both this code: ```csharp -var foo = context.Foos.AsNoTracking().Include(e => e.Bar).Single(); +var foo = await context.Foos.AsNoTracking().Include(e => e.Bar).SingleAsync(); Console.WriteLine($"Foo.Bar.Id = {foo.Bar.Id}"); ``` And this code: ```csharp -var foo = context.Foos.Include(e => e.Bar).Single(); +var foo = await context.Foos.Include(e => e.Bar).SingleAsync(); Console.WriteLine($"Foo.Bar.Id = {foo.Bar.Id}"); ``` diff --git a/entity-framework/core/what-is-new/ef-core-7.0/breaking-changes.md b/entity-framework/core/what-is-new/ef-core-7.0/breaking-changes.md index 4acec59b5b..0327f47c58 100644 --- a/entity-framework/core/what-is-new/ef-core-7.0/breaking-changes.md +++ b/entity-framework/core/what-is-new/ef-core-7.0/breaking-changes.md @@ -528,13 +528,13 @@ The correct extension method must be used for it to function correctly in all si Use the correct extension method for the provider being used. If multiple providers are referenced, then call the extension method as a static method. For example: ```csharp -var result = CosmosQueryableExtensions.FromSqlRaw(context.Blogs, "SELECT ...").ToList(); +var result = await CosmosQueryableExtensions.FromSqlRaw(context.Blogs, "SELECT ...").ToListAsync(); ``` Or: ```csharp -var result = RelationalQueryableExtensions.FromSqlRaw(context.Blogs, "SELECT ...").ToList(); +var result = await RelationalQueryableExtensions.FromSqlRaw(context.Blogs, "SELECT ...").ToListAsync(); ``` diff --git a/entity-framework/core/what-is-new/ef-core-9.0/whatsnew.md b/entity-framework/core/what-is-new/ef-core-9.0/whatsnew.md index 36c45ce656..36dde31e0f 100644 --- a/entity-framework/core/what-is-new/ef-core-9.0/whatsnew.md +++ b/entity-framework/core/what-is-new/ef-core-9.0/whatsnew.md @@ -1086,7 +1086,7 @@ The above were only some of the more important query improvements in EF9; see [t ### Protection against concurrent migrations -EF9 introduces a locking mechanism to protect against multiple migration executions happening simultaneously, as that could leave the database in a corrupted state. This doesn't happen when migrations are deployed to the production environment using [recommended methods](/ef/core/managing-schemas/migrations/applying#sql-scripts), but can happen if migrations are applied at runtime using the [`DbContext.Database.Migrate()`](/dotnet/api/microsoft.entityframeworkcore.relationaldatabasefacadeextensions.migrate) method. We recommend applying migrations at deployment, rather than as part of application startup, but that can result in more complicated application architectures (e.g. [when using .NET Aspire projects](/dotnet/aspire/database/ef-core-migrations)). +EF9 introduces a locking mechanism to protect against multiple migration executions happening simultaneously, as that could leave the database in a corrupted state. This doesn't happen when migrations are deployed to the production environment using [recommended methods](/ef/core/managing-schemas/migrations/applying#sql-scripts), but can happen if migrations are applied at runtime using the [`DbContext.Database.MigrateAsync()`](/dotnet/api/microsoft.entityframeworkcore.relationaldatabasefacadeextensions.migrate) method. We recommend applying migrations at deployment, rather than as part of application startup, but that can result in more complicated application architectures (e.g. [when using .NET Aspire projects](/dotnet/aspire/database/ef-core-migrations)). > [!NOTE] > If you are using Sqlite database, see [potential issues associated with this feature](/ef/core/providers/sqlite/limitations#concurrent-migrations-protection). diff --git a/samples/core/Benchmarks/AverageBlogRanking.cs b/samples/core/Benchmarks/AverageBlogRanking.cs index 19dc70bf8b..08ee415350 100644 --- a/samples/core/Benchmarks/AverageBlogRanking.cs +++ b/samples/core/Benchmarks/AverageBlogRanking.cs @@ -1,5 +1,6 @@ using System; using System.Linq; +using System.Threading.Tasks; using BenchmarkDotNet.Attributes; using Microsoft.EntityFrameworkCore; @@ -10,22 +11,22 @@ public class AverageBlogRanking public int NumBlogs; // number of records to write [once], and read [each pass] [GlobalSetup] - public void Setup() + public async Task Setup() { using var context = new BloggingContext(); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); - context.SeedData(NumBlogs); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); + await context.SeedData(NumBlogs); } #region LoadEntities [Benchmark] - public double LoadEntities() + public async Task LoadEntities() { var sum = 0; var count = 0; using var ctx = new BloggingContext(); - foreach (var blog in ctx.Blogs) + await foreach (var blog in ctx.Blogs.AsAsyncEnumerable()) { sum += blog.Rating; count++; @@ -37,12 +38,12 @@ public double LoadEntities() #region LoadEntitiesNoTracking [Benchmark] - public double LoadEntitiesNoTracking() + public async Task LoadEntitiesNoTracking() { var sum = 0; var count = 0; using var ctx = new BloggingContext(); - foreach (var blog in ctx.Blogs.AsNoTracking()) + await foreach (var blog in ctx.Blogs.AsNoTracking().AsAsyncEnumerable()) { sum += blog.Rating; count++; @@ -54,12 +55,12 @@ public double LoadEntitiesNoTracking() #region ProjectOnlyRanking [Benchmark] - public double ProjectOnlyRanking() + public async Task ProjectOnlyRanking() { var sum = 0; var count = 0; using var ctx = new BloggingContext(); - foreach (var rating in ctx.Blogs.Select(b => b.Rating)) + await foreach (var rating in ctx.Blogs.Select(b => b.Rating).AsAsyncEnumerable()) { sum += rating; count++; @@ -71,10 +72,10 @@ public double ProjectOnlyRanking() #region CalculateInDatabase [Benchmark(Baseline = true)] - public double CalculateInDatabase() + public async Task CalculateInDatabase() { using var ctx = new BloggingContext(); - return ctx.Blogs.Average(b => b.Rating); + return await ctx.Blogs.AverageAsync(b => b.Rating); } #endregion @@ -85,7 +86,7 @@ public class BloggingContext : DbContext protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;ConnectRetryCount=0"); - public void SeedData(int numblogs) + public async Task SeedData(int numblogs) { Blogs.AddRange( Enumerable.Range(0, numblogs).Select( @@ -93,7 +94,7 @@ public void SeedData(int numblogs) { Name = $"Blog{i}", Url = $"blog{i}.blogs.net", CreationTime = new DateTime(2020, 1, 1), Rating = i % 5 })); - SaveChanges(); + await SaveChangesAsync(); } } diff --git a/samples/core/Benchmarks/ContextPooling.cs b/samples/core/Benchmarks/ContextPooling.cs index 68ae552a12..a03605780f 100644 --- a/samples/core/Benchmarks/ContextPooling.cs +++ b/samples/core/Benchmarks/ContextPooling.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; using BenchmarkDotNet.Attributes; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; @@ -14,34 +15,34 @@ public class ContextPooling public int NumBlogs { get; set; } [GlobalSetup] - public void Setup() + public async Task Setup() { _options = new DbContextOptionsBuilder() .UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;ConnectRetryCount=0") .Options; using var context = new BloggingContext(_options); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); - context.SeedData(NumBlogs); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); + await context.SeedData(NumBlogs); _poolingFactory = new PooledDbContextFactory(_options); } [Benchmark] - public List WithoutContextPooling() + public async Task> WithoutContextPooling() { using var context = new BloggingContext(_options); - return context.Blogs.ToList(); + return await context.Blogs.ToListAsync(); } [Benchmark] - public List WithContextPooling() + public async Task> WithContextPooling() { using var context = _poolingFactory.CreateDbContext(); - return context.Blogs.ToList(); + return await context.Blogs.ToListAsync(); } public class BloggingContext : DbContext @@ -50,10 +51,10 @@ public class BloggingContext : DbContext public BloggingContext(DbContextOptions options) : base(options) {} - public void SeedData(int numBlogs) + public async Task SeedData(int numBlogs) { Blogs.AddRange(Enumerable.Range(0, numBlogs).Select(i => new Blog { Url = $"http://www.someblog{i}.com"})); - SaveChanges(); + await SaveChangesAsync(); } } diff --git a/samples/core/Benchmarks/DynamicallyConstructedQueries.cs b/samples/core/Benchmarks/DynamicallyConstructedQueries.cs index a6cfa4dde9..c969e9a5e3 100644 --- a/samples/core/Benchmarks/DynamicallyConstructedQueries.cs +++ b/samples/core/Benchmarks/DynamicallyConstructedQueries.cs @@ -3,6 +3,7 @@ using System.Linq; using System.Linq.Expressions; using System.Threading; +using System.Threading.Tasks; using BenchmarkDotNet.Attributes; using Microsoft.EntityFrameworkCore; @@ -13,16 +14,16 @@ public class DynamicallyConstructedQueries private bool _addWhereClause = true; [GlobalSetup] - public static void GlobalSetup() + public static async Task GlobalSetup() { using var context = new BloggingContext(); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } #region ExpressionApiWithConstant [Benchmark] - public int ExpressionApiWithConstant() + public async Task ExpressionApiWithConstant() { var url = "blog" + Interlocked.Increment(ref _blogNumber); using var context = new BloggingContext(); @@ -43,13 +44,13 @@ public int ExpressionApiWithConstant() query = query.Where(whereLambda); } - return query.Count(); + return await query.CountAsync(); } #endregion #region ExpressionApiWithParameter [Benchmark] - public int ExpressionApiWithParameter() + public async Task ExpressionApiWithParameter() { var url = "blog" + Interlocked.Increment(ref _blogNumber); using var context = new BloggingContext(); @@ -78,13 +79,13 @@ public int ExpressionApiWithParameter() query = query.Where(whereLambda); } - return query.Count(); + return await query.CountAsync(); } #endregion #region SimpleWithParameter [Benchmark] - public int SimpleWithParameter() + public async Task SimpleWithParameter() { var url = "blog" + Interlocked.Increment(ref _blogNumber); @@ -99,7 +100,7 @@ public int SimpleWithParameter() query = query.Where(whereLambda); } - return query.Count(); + return await query.CountAsync(); } #endregion diff --git a/samples/core/Benchmarks/Inheritance.cs b/samples/core/Benchmarks/Inheritance.cs index 40f864bf57..42e97b84e0 100644 --- a/samples/core/Benchmarks/Inheritance.cs +++ b/samples/core/Benchmarks/Inheritance.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; using BenchmarkDotNet.Attributes; using Microsoft.EntityFrameworkCore; @@ -11,60 +12,60 @@ public class Inheritance public int RowsPerEntityType { get; set; } [GlobalSetup(Target = nameof(TPH))] - public void SetupTPH() + public async Task SetupTPH() { Console.WriteLine("Setting up database..."); using var context = new TPHContext(); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); - context.SeedData(RowsPerEntityType); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); + await context.SeedData(RowsPerEntityType); Console.WriteLine("Setup complete."); } [GlobalSetup(Target = nameof(TPT))] - public void SetupTPT() + public async Task SetupTPT() { Console.WriteLine("Setting up database..."); using var context = new TPTContext(); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); - context.SeedData(RowsPerEntityType); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); + await context.SeedData(RowsPerEntityType); Console.WriteLine("Setup complete."); } [GlobalSetup(Target = nameof(TPC))] - public void SetupTPC() + public async Task SetupTPC() { Console.WriteLine("Setting up database..."); using var context = new TPCContext(); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); - context.SeedData(RowsPerEntityType); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); + await context.SeedData(RowsPerEntityType); Console.WriteLine("Setup complete."); } [Benchmark] - public List TPH() + public async Task> TPH() { using var context = new TPHContext(); - return context.Roots.ToList(); + return await context.Roots.ToListAsync(); } [Benchmark] - public List TPT() + public async Task> TPT() { using var context = new TPTContext(); - return context.Roots.ToList(); + return await context.Roots.ToListAsync(); } [Benchmark] - public List TPC() + public async Task> TPC() { using var context = new TPCContext(); - return context.Roots.ToList(); + return await context.Roots.ToListAsync(); } public abstract class InheritanceContext : DbContext @@ -84,7 +85,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) modelBuilder.Entity(); } - public void SeedData(int rowsPerEntityType) + public async Task SeedData(int rowsPerEntityType) { Set().AddRange(Enumerable.Range(0, rowsPerEntityType).Select(i => new Root { RootProperty = i })); Set().AddRange(Enumerable.Range(0, rowsPerEntityType).Select(i => new Child1 { Child1Property = i })); @@ -93,7 +94,7 @@ public void SeedData(int rowsPerEntityType) Set().AddRange(Enumerable.Range(0, rowsPerEntityType).Select(i => new Child2 { Child2Property = i })); Set().AddRange(Enumerable.Range(0, rowsPerEntityType).Select(i => new Child2A { Child2AProperty = i })); Set().AddRange(Enumerable.Range(0, rowsPerEntityType).Select(i => new Child2B { Child2BProperty = i })); - SaveChanges(); + await SaveChangesAsync(); } } diff --git a/samples/core/Benchmarks/QueryTrackingBehavior.cs b/samples/core/Benchmarks/QueryTrackingBehavior.cs index 0ecb8cc1a9..e7f303a53e 100644 --- a/samples/core/Benchmarks/QueryTrackingBehavior.cs +++ b/samples/core/Benchmarks/QueryTrackingBehavior.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; using BenchmarkDotNet.Attributes; using Microsoft.EntityFrameworkCore; @@ -16,30 +17,30 @@ public class QueryTrackingBehavior public int NumPostsPerBlog { get; set; } [GlobalSetup] - public void Setup() + public async Task Setup() { Console.WriteLine("Setting up database..."); using var context = new BloggingContext(); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); - BloggingContext.SeedData(NumBlogs, NumPostsPerBlog); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); + await BloggingContext.SeedData(NumBlogs, NumPostsPerBlog); Console.WriteLine("Setup complete."); } [Benchmark(Baseline = true)] - public List AsTracking() + public async Task> AsTracking() { using var context = new BloggingContext(); - return context.Posts.AsTracking().Include(p => p.Blog).ToList(); + return await context.Posts.AsTracking().Include(p => p.Blog).ToListAsync(); } [Benchmark] - public List AsNoTracking() + public async Task> AsNoTracking() { using var context = new BloggingContext(); - return context.Posts.AsNoTracking().Include(p => p.Blog).ToList(); + return await context.Posts.AsNoTracking().Include(p => p.Blog).ToListAsync(); } public class BloggingContext : DbContext @@ -50,14 +51,14 @@ public class BloggingContext : DbContext protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;ConnectRetryCount=0"); - public static void SeedData(int numBlogs, int numPostsPerBlog) + public static async Task SeedData(int numBlogs, int numPostsPerBlog) { using var context = new BloggingContext(); context.AddRange( Enumerable.Range(0, numBlogs) .Select(_ => new Blog { Url = "Some URL", Posts = Enumerable.Range(0, numPostsPerBlog) .Select(_ => new Post() { Title = "Some Title", Content = "Some Content"}).ToList() })); - context.SaveChanges(); + await context.SaveChangesAsync(); } } diff --git a/samples/core/CascadeDeletes/IntroOptionalSamples.cs b/samples/core/CascadeDeletes/IntroOptionalSamples.cs index 302c0c0bb0..04717d76a5 100644 --- a/samples/core/CascadeDeletes/IntroOptionalSamples.cs +++ b/samples/core/CascadeDeletes/IntroOptionalSamples.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; @@ -8,67 +9,67 @@ namespace IntroOptional; public static class IntroOptionalSamples { - public static void Deleting_principal_parent_1b() + public static async Task Deleting_principal_parent_1b() { Console.WriteLine($">>>> Sample: {nameof(Deleting_principal_parent_1b)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); #region Deleting_principal_parent_1b using var context = new BlogsContext(); - var blog = context.Blogs.OrderBy(e => e.Name).Include(e => e.Posts).First(); + var blog = await context.Blogs.OrderBy(e => e.Name).Include(e => e.Posts).FirstAsync(); context.Remove(blog); - context.SaveChanges(); + await context.SaveChangesAsync(); #endregion Console.WriteLine(); } - public static void Severing_a_relationship_1b() + public static async Task Severing_a_relationship_1b() { Console.WriteLine($">>>> Sample: {nameof(Severing_a_relationship_1b)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); #region Severing_a_relationship_1b using var context = new BlogsContext(); - var blog = context.Blogs.OrderBy(e => e.Name).Include(e => e.Posts).First(); + var blog = await context.Blogs.OrderBy(e => e.Name).Include(e => e.Posts).FirstAsync(); foreach (var post in blog.Posts) { post.Blog = null; } - context.SaveChanges(); + await context.SaveChangesAsync(); #endregion Console.WriteLine(); } - public static void Severing_a_relationship_2b() + public static async Task Severing_a_relationship_2b() { Console.WriteLine($">>>> Sample: {nameof(Severing_a_relationship_2b)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); #region Severing_a_relationship_2b using var context = new BlogsContext(); - var blog = context.Blogs.OrderBy(e => e.Name).Include(e => e.Posts).First(); + var blog = await context.Blogs.OrderBy(e => e.Name).Include(e => e.Posts).FirstAsync(); blog.Posts.Clear(); - context.SaveChanges(); + await context.SaveChangesAsync(); #endregion Console.WriteLine(); @@ -77,15 +78,15 @@ public static void Severing_a_relationship_2b() public static class Helpers { - public static void RecreateCleanDatabase() + public static async Task RecreateCleanDatabase() { using var context = new BlogsContext(quiet: true); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } - public static void PopulateDatabase() + public static async Task PopulateDatabase() { using var context = new BlogsContext(quiet: true); @@ -108,7 +109,7 @@ public static void PopulateDatabase() } }); - context.SaveChanges(); + await context.SaveChangesAsync(); } } diff --git a/samples/core/CascadeDeletes/IntroRequiredSamples.cs b/samples/core/CascadeDeletes/IntroRequiredSamples.cs index 73a1873da5..2ccf07c516 100644 --- a/samples/core/CascadeDeletes/IntroRequiredSamples.cs +++ b/samples/core/CascadeDeletes/IntroRequiredSamples.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; @@ -8,88 +9,88 @@ namespace IntroRequired; public static class IntroRequiredSamples { - public static void Deleting_principal_parent_1() + public static async Task Deleting_principal_parent_1() { Console.WriteLine($">>>> Sample: {nameof(Deleting_principal_parent_1)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); #region Deleting_principal_parent_1 using var context = new BlogsContext(); - var blog = context.Blogs.OrderBy(e => e.Name).Include(e => e.Posts).First(); + var blog = await context.Blogs.OrderBy(e => e.Name).Include(e => e.Posts).FirstAsync(); context.Remove(blog); - context.SaveChanges(); + await context.SaveChangesAsync(); #endregion Console.WriteLine(); } - public static void Severing_a_relationship_1() + public static async Task Severing_a_relationship_1() { Console.WriteLine($">>>> Sample: {nameof(Severing_a_relationship_1)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); #region Severing_a_relationship_1 using var context = new BlogsContext(); - var blog = context.Blogs.OrderBy(e => e.Name).Include(e => e.Posts).First(); + var blog = await context.Blogs.OrderBy(e => e.Name).Include(e => e.Posts).FirstAsync(); foreach (var post in blog.Posts) { post.Blog = null; } - context.SaveChanges(); + await context.SaveChangesAsync(); #endregion Console.WriteLine(); } - public static void Severing_a_relationship_2() + public static async Task Severing_a_relationship_2() { Console.WriteLine($">>>> Sample: {nameof(Severing_a_relationship_2)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); #region Severing_a_relationship_2 using var context = new BlogsContext(); - var blog = context.Blogs.OrderBy(e => e.Name).Include(e => e.Posts).First(); + var blog = await context.Blogs.OrderBy(e => e.Name).Include(e => e.Posts).FirstAsync(); blog.Posts.Clear(); - context.SaveChanges(); + await context.SaveChangesAsync(); #endregion Console.WriteLine(); } - public static void Where_cascading_behaviors_happen_1() + public static async Task Where_cascading_behaviors_happen_1() { Console.WriteLine($">>>> Sample: {nameof(Where_cascading_behaviors_happen_1)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); #region Where_cascading_behaviors_happen_1 using var context = new BlogsContext(); - var blog = context.Blogs.OrderBy(e => e.Name).First(); + var blog = await context.Blogs.OrderBy(e => e.Name).FirstAsync(); context.Remove(blog); - context.SaveChanges(); + await context.SaveChangesAsync(); #endregion Console.WriteLine(); @@ -98,15 +99,15 @@ public static void Where_cascading_behaviors_happen_1() public static class Helpers { - public static void RecreateCleanDatabase() + public static async Task RecreateCleanDatabase() { using var context = new BlogsContext(quiet: true); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } - public static void PopulateDatabase() + public static async Task PopulateDatabase() { using var context = new BlogsContext(quiet: true); @@ -129,7 +130,7 @@ public static void PopulateDatabase() } }); - context.SaveChanges(); + await context.SaveChangesAsync(); } } diff --git a/samples/core/CascadeDeletes/OptionalDependentsSamples.cs b/samples/core/CascadeDeletes/OptionalDependentsSamples.cs index b6ee4c779b..4b8d9d55c7 100644 --- a/samples/core/CascadeDeletes/OptionalDependentsSamples.cs +++ b/samples/core/CascadeDeletes/OptionalDependentsSamples.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; @@ -8,13 +9,13 @@ namespace Optional; public static class OptionalDependentsSamples { - public static void Optional_relationship_with_dependents_children_loaded() + public static async Task Optional_relationship_with_dependents_children_loaded() { Console.WriteLine("#### Optional relationship with dependents/children loaded"); Console.WriteLine(); - var deleteResults = Helpers.GatherData(c => c.Remove(c.Blogs.Include(e => e.Posts).Single())); - var severResults = Helpers.GatherData(c => c.Blogs.Include(e => e.Posts).Single().Posts.Clear()); + var deleteResults = await Helpers.GatherData(async c => c.Remove(await c.Blogs.Include(e => e.Posts).SingleAsync())); + var severResults = await Helpers.GatherData(async c => (await c.Blogs.Include(e => e.Posts).SingleAsync()).Posts.Clear()); Console.WriteLine( $"| `{"DeleteBehavior".PadRight(16)} | {"On deleting principal/parent".PadRight(40)} | On severing from principal/parent"); @@ -28,12 +29,12 @@ public static void Optional_relationship_with_dependents_children_loaded() Console.WriteLine(); } - public static void Optional_relationship_with_dependents_children_not_loaded() + public static async Task Optional_relationship_with_dependents_children_not_loaded() { Console.WriteLine("#### Optional relationship with dependents/children not loaded"); Console.WriteLine(); - var deleteResults = Helpers.GatherData(c => c.Remove(c.Blogs.Single())); + var deleteResults = await Helpers.GatherData(async c => c.Remove(await c.Blogs.SingleAsync())); Console.WriteLine( $"| `{"DeleteBehavior".PadRight(16)} | {"On deleting principal/parent".PadRight(40)} | On severing from principal/parent"); @@ -80,16 +81,16 @@ public class Post public static class Helpers { - public static void RecreateCleanDatabase(OptionalBlogsContext context) + public static async Task RecreateCleanDatabase(OptionalBlogsContext context) { using (context) { - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } } - public static void PopulateDatabase(OptionalBlogsContext context) + public static async Task PopulateDatabase(OptionalBlogsContext context) { using (context) { @@ -112,33 +113,33 @@ public static void PopulateDatabase(OptionalBlogsContext context) } }); - context.SaveChanges(); + await context.SaveChangesAsync(); } } - public static Dictionary GatherData(Action action) + public static async Task> GatherData(Func action) { var results = new Dictionary(); foreach (var deleteBehavior in DeleteBehaviors) { - RecreateCleanDatabase(new OptionalBlogsContext(deleteBehavior)); - PopulateDatabase(new OptionalBlogsContext(deleteBehavior)); + await RecreateCleanDatabase(new OptionalBlogsContext(deleteBehavior)); + await PopulateDatabase(new OptionalBlogsContext(deleteBehavior)); try { using var context = new OptionalBlogsContext(deleteBehavior); - action(context); + await action(context); context.ChangeTracker.DetectChanges(); var deletingPosts = context.ChangeTracker.Entries().Any(e => e.State == EntityState.Deleted); var settingFksToNull = context.ChangeTracker.Entries().Any(e => e.State == EntityState.Modified); - context.SaveChanges(); + await context.SaveChangesAsync(); - var deletedPosts = !context.Posts.AsNoTracking().Any(); + var deletedPosts = !(await context.Posts.AsNoTracking().AnyAsync()); results[deleteBehavior] = deletingPosts diff --git a/samples/core/CascadeDeletes/Program.cs b/samples/core/CascadeDeletes/Program.cs index 9623a16faa..3237432b46 100644 --- a/samples/core/CascadeDeletes/Program.cs +++ b/samples/core/CascadeDeletes/Program.cs @@ -1,4 +1,5 @@ using System; +using System.Threading.Tasks; using DatabaseCycles; using IntroOptional; using IntroRequired; @@ -7,26 +8,26 @@ public class Program { - public static void Main() + public static async Task Main() { Console.WriteLine("Samples for _Cascade Delete_"); Console.WriteLine(); - IntroRequiredSamples.Deleting_principal_parent_1(); - IntroRequiredSamples.Severing_a_relationship_1(); - IntroRequiredSamples.Severing_a_relationship_2(); - IntroRequiredSamples.Where_cascading_behaviors_happen_1(); + await IntroRequiredSamples.Deleting_principal_parent_1(); + await IntroRequiredSamples.Severing_a_relationship_1(); + await IntroRequiredSamples.Severing_a_relationship_2(); + await IntroRequiredSamples.Where_cascading_behaviors_happen_1(); - WithDatabaseCycleSamples.Database_cascade_limitations_1(); - WithDatabaseCycleSamples.Database_cascade_limitations_2(); + await WithDatabaseCycleSamples.Database_cascade_limitations_1(); + await WithDatabaseCycleSamples.Database_cascade_limitations_2(); - IntroOptionalSamples.Deleting_principal_parent_1b(); - IntroOptionalSamples.Severing_a_relationship_1b(); - IntroOptionalSamples.Severing_a_relationship_2b(); + await IntroOptionalSamples.Deleting_principal_parent_1b(); + await IntroOptionalSamples.Severing_a_relationship_1b(); + await IntroOptionalSamples.Severing_a_relationship_2b(); - RequiredDependentsSamples.Required_relationship_with_dependents_children_loaded(); - RequiredDependentsSamples.Required_relationship_with_dependents_children_not_loaded(); - OptionalDependentsSamples.Optional_relationship_with_dependents_children_loaded(); - OptionalDependentsSamples.Optional_relationship_with_dependents_children_not_loaded(); + await RequiredDependentsSamples.Required_relationship_with_dependents_children_loaded(); + await RequiredDependentsSamples.Required_relationship_with_dependents_children_not_loaded(); + await OptionalDependentsSamples.Optional_relationship_with_dependents_children_loaded(); + await OptionalDependentsSamples.Optional_relationship_with_dependents_children_not_loaded(); } } diff --git a/samples/core/CascadeDeletes/RequiredDependentsSamples.cs b/samples/core/CascadeDeletes/RequiredDependentsSamples.cs index 2ec40840bb..d7f4bf0352 100644 --- a/samples/core/CascadeDeletes/RequiredDependentsSamples.cs +++ b/samples/core/CascadeDeletes/RequiredDependentsSamples.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; @@ -8,13 +9,13 @@ namespace Required; public static class RequiredDependentsSamples { - public static void Required_relationship_with_dependents_children_loaded() + public static async Task Required_relationship_with_dependents_children_loaded() { Console.WriteLine("#### Required relationship with dependents/children loaded"); Console.WriteLine(); - var deleteResults = Helpers.GatherData(c => c.Remove(c.Blogs.Include(e => e.Posts).Single())); - var severResults = Helpers.GatherData(c => c.Blogs.Include(e => e.Posts).Single().Posts.Clear()); + var deleteResults = await Helpers.GatherData(async c => c.Remove(await c.Blogs.Include(e => e.Posts).SingleAsync())); + var severResults = await Helpers.GatherData(async c => (await c.Blogs.Include(e => e.Posts).SingleAsync()).Posts.Clear()); Console.WriteLine( $"| `{"DeleteBehavior".PadRight(16)} | {"On deleting principal/parent".PadRight(40)} | On severing from principal/parent"); @@ -28,12 +29,12 @@ public static void Required_relationship_with_dependents_children_loaded() Console.WriteLine(); } - public static void Required_relationship_with_dependents_children_not_loaded() + public static async Task Required_relationship_with_dependents_children_not_loaded() { Console.WriteLine("#### Required relationship with dependents/children not loaded"); Console.WriteLine(); - var deleteResults = Helpers.GatherData(c => c.Remove(c.Blogs.Single())); + var deleteResults = await Helpers.GatherData(async c => c.Remove(await c.Blogs.SingleAsync())); Console.WriteLine( $"| `{"DeleteBehavior".PadRight(16)} | {"On deleting principal/parent".PadRight(40)} | On severing from principal/parent"); @@ -77,16 +78,16 @@ public class Post public static class Helpers { - public static void RecreateCleanDatabase(RequiredBlogsContext context) + public static async Task RecreateCleanDatabase(RequiredBlogsContext context) { using (context) { - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } } - public static void PopulateDatabase(RequiredBlogsContext context) + public static async Task PopulateDatabase(RequiredBlogsContext context) { using (context) { @@ -109,11 +110,11 @@ public static void PopulateDatabase(RequiredBlogsContext context) } }); - context.SaveChanges(); + await context.SaveChangesAsync(); } } - public static Dictionary GatherData(Action action) + public static async Task> GatherData(Func action) { var results = new Dictionary(); @@ -121,8 +122,8 @@ public static Dictionary GatherData(Action GatherData(Action().Any(e => e.State == EntityState.Deleted); var settingFksToNull = context.ChangeTracker.Entries().Any(e => e.State == EntityState.Modified); - context.SaveChanges(); + await context.SaveChangesAsync(); - var deletedPosts = !context.Posts.AsNoTracking().Any(); + var deletedPosts = !(await context.Posts.AsNoTracking().AnyAsync()); results[deleteBehavior] = deletingPosts diff --git a/samples/core/CascadeDeletes/WithDatabaseCycleSamples.cs b/samples/core/CascadeDeletes/WithDatabaseCycleSamples.cs index 70c4d39f88..76c59babd5 100644 --- a/samples/core/CascadeDeletes/WithDatabaseCycleSamples.cs +++ b/samples/core/CascadeDeletes/WithDatabaseCycleSamples.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; @@ -8,46 +9,46 @@ namespace DatabaseCycles; public static class WithDatabaseCycleSamples { - public static void Database_cascade_limitations_1() + public static async Task Database_cascade_limitations_1() { Console.WriteLine($">>>> Sample: {nameof(Database_cascade_limitations_1)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); #region Database_cascade_limitations_1 using var context = new BlogsContext(); - var owner = context.People.Single(e => e.Name == "ajcvickers"); - var blog = context.Blogs.Single(e => e.Owner == owner); + var owner = await context.People.SingleAsync(e => e.Name == "ajcvickers"); + var blog = await context.Blogs.SingleAsync(e => e.Owner == owner); context.Remove(owner); - context.SaveChanges(); + await context.SaveChangesAsync(); #endregion Console.WriteLine(); } - public static void Database_cascade_limitations_2() + public static async Task Database_cascade_limitations_2() { Console.WriteLine($">>>> Sample: {nameof(Database_cascade_limitations_2)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); try { #region Database_cascade_limitations_2 using var context = new BlogsContext(); - var owner = context.People.Single(e => e.Name == "ajcvickers"); + var owner = await context.People.SingleAsync(e => e.Name == "ajcvickers"); context.Remove(owner); - context.SaveChanges(); + await context.SaveChangesAsync(); #endregion } catch (Exception e) @@ -65,15 +66,15 @@ public static void Database_cascade_limitations_2() public static class Helpers { - public static void RecreateCleanDatabase() + public static async Task RecreateCleanDatabase() { using var context = new BlogsContext(quiet: true); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } - public static void PopulateDatabase() + public static async Task PopulateDatabase() { using var context = new BlogsContext(quiet: true); @@ -101,7 +102,7 @@ public static void PopulateDatabase() } }); - context.SaveChanges(); + await context.SaveChangesAsync(); } } diff --git a/samples/core/ChangeTracking/AccessingTrackedEntities/Program.cs b/samples/core/ChangeTracking/AccessingTrackedEntities/Program.cs index 45bbb28d45..ff72565641 100644 --- a/samples/core/ChangeTracking/AccessingTrackedEntities/Program.cs +++ b/samples/core/ChangeTracking/AccessingTrackedEntities/Program.cs @@ -1,30 +1,31 @@ using System; +using System.Threading.Tasks; public class Program { - public static void Main() + public static async Task Main() { Console.WriteLine("Samples for _Accessing Tracked Entities_"); Console.WriteLine(); - Samples.Using_DbContext_Entry_and_EntityEntry_instances_1(); - Samples.Work_with_the_entity_1(); - Samples.Work_with_the_entity_2(); - Samples.Work_with_a_single_property_1(); - Samples.Work_with_a_single_navigation_1(); - Samples.Work_with_a_single_navigation_2(); - Samples.Work_with_all_properties_of_an_entity_1(); - Samples.Work_with_all_navigations_of_an_entity_1(); - Samples.Work_with_all_members_of_an_entity_1(); + await Samples.Using_DbContext_Entry_and_EntityEntry_instances_1(); + await Samples.Work_with_the_entity_1(); + await Samples.Work_with_the_entity_2(); + await Samples.Work_with_a_single_property_1(); + await Samples.Work_with_a_single_navigation_1(); + await Samples.Work_with_a_single_navigation_2(); + await Samples.Work_with_all_properties_of_an_entity_1(); + await Samples.Work_with_all_navigations_of_an_entity_1(); + await Samples.Work_with_all_members_of_an_entity_1(); - Samples.Find_and_FindAsync_1(); - Samples.Find_and_FindAsync_2(); + await Samples.Find_and_FindAsync_1(); + await Samples.Find_and_FindAsync_2(); - Samples.Using_ChangeTracker_Entries_to_access_all_tracked_entities_1(); + await Samples.Using_ChangeTracker_Entries_to_access_all_tracked_entities_1(); - Samples.Using_DbSet_Local_to_query_tracked_entities_1(); - Samples.Using_DbSet_Local_to_query_tracked_entities_2(); - Samples.Using_DbSet_Local_to_query_tracked_entities_3(); - Samples.Using_DbSet_Local_to_query_tracked_entities_4(); + await Samples.Using_DbSet_Local_to_query_tracked_entities_1(); + await Samples.Using_DbSet_Local_to_query_tracked_entities_2(); + await Samples.Using_DbSet_Local_to_query_tracked_entities_3(); + await Samples.Using_DbSet_Local_to_query_tracked_entities_4(); } } diff --git a/samples/core/ChangeTracking/AccessingTrackedEntities/Samples.cs b/samples/core/ChangeTracking/AccessingTrackedEntities/Samples.cs index 23b4871696..527c58944d 100644 --- a/samples/core/ChangeTracking/AccessingTrackedEntities/Samples.cs +++ b/samples/core/ChangeTracking/AccessingTrackedEntities/Samples.cs @@ -4,6 +4,7 @@ using System.ComponentModel; using System.Diagnostics; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Diagnostics; @@ -11,35 +12,35 @@ public static class Samples { - public static void Using_DbContext_Entry_and_EntityEntry_instances_1() + public static async Task Using_DbContext_Entry_and_EntityEntry_instances_1() { Console.WriteLine($">>>> Sample: {nameof(Using_DbContext_Entry_and_EntityEntry_instances_1)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); #region Using_DbContext_Entry_and_EntityEntry_instances_1 using var context = new BlogsContext(); - var blog = context.Blogs.Single(e => e.Id == 1); + var blog = await context.Blogs.SingleAsync(e => e.Id == 1); var entityEntry = context.Entry(blog); #endregion Console.WriteLine(); } - public static void Work_with_the_entity_1() + public static async Task Work_with_the_entity_1() { Console.WriteLine($">>>> Sample: {nameof(Work_with_the_entity_1)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BlogsContext(); - var blog = context.Blogs.Single(e => e.Id == 1); + var blog = await context.Blogs.SingleAsync(e => e.Id == 1); #region Work_with_the_entity_1 var currentState = context.Entry(blog).State; @@ -52,13 +53,13 @@ public static void Work_with_the_entity_1() Console.WriteLine(); } - public static void Work_with_the_entity_2() + public static async Task Work_with_the_entity_2() { Console.WriteLine($">>>> Sample: {nameof(Work_with_the_entity_2)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BlogsContext(); @@ -73,18 +74,18 @@ public static void Work_with_the_entity_2() Console.WriteLine(); } - public static void Work_with_a_single_property_1() + public static async Task Work_with_a_single_property_1() { Console.WriteLine($">>>> Sample: {nameof(Work_with_a_single_property_1)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BlogsContext(); { - var blog = context.Blogs.Single(e => e.Id == 1); + var blog = await context.Blogs.SingleAsync(e => e.Id == 1); #region Work_with_a_single_property_1a PropertyEntry propertyEntry = context.Entry(blog).Property(e => e.Name); @@ -92,7 +93,7 @@ public static void Work_with_a_single_property_1() } { - var blog = context.Blogs.Single(e => e.Id == 1); + var blog = await context.Blogs.SingleAsync(e => e.Id == 1); #region Work_with_a_single_property_1b PropertyEntry propertyEntry = context.Entry(blog).Property("Name"); @@ -100,7 +101,7 @@ public static void Work_with_a_single_property_1() } { - var blog = context.Blogs.Single(e => e.Id == 1); + var blog = await context.Blogs.SingleAsync(e => e.Id == 1); #region Work_with_a_single_property_1c PropertyEntry propertyEntry = context.Entry(blog).Property("Name"); @@ -108,7 +109,7 @@ public static void Work_with_a_single_property_1() } { - var blog = context.Blogs.Single(e => e.Id == 1); + var blog = await context.Blogs.SingleAsync(e => e.Id == 1); #region Work_with_a_single_property_1d string currentValue = context.Entry(blog).Property(e => e.Name).CurrentValue; @@ -118,7 +119,7 @@ public static void Work_with_a_single_property_1() { #region Work_with_a_single_property_1e - object blog = context.Blogs.Single(e => e.Id == 1); + object blog = await context.Blogs.SingleAsync(e => e.Id == 1); object currentValue = context.Entry(blog).Property("Name").CurrentValue; context.Entry(blog).Property("Name").CurrentValue = "1unicorn2"; @@ -128,17 +129,17 @@ public static void Work_with_a_single_property_1() Console.WriteLine(); } - public static void Work_with_a_single_navigation_1() + public static async Task Work_with_a_single_navigation_1() { Console.WriteLine($">>>> Sample: {nameof(Work_with_a_single_navigation_1)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BlogsContext(); - var post = context.Posts.Include(e => e.Blog).Single(e => e.Id == 1); + var post = await context.Posts.Include(e => e.Blog).SingleAsync(e => e.Id == 1); #region Work_with_a_single_navigation_1 ReferenceEntry referenceEntry1 = context.Entry(post).Reference(e => e.Blog); @@ -149,17 +150,17 @@ public static void Work_with_a_single_navigation_1() Console.WriteLine(); } - public static void Work_with_a_single_navigation_2() + public static async Task Work_with_a_single_navigation_2() { Console.WriteLine($">>>> Sample: {nameof(Work_with_a_single_navigation_2)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BlogsContext(); - var blog = context.Blogs.Include(e => e.Posts).Single(e => e.Id == 1); + var blog = await context.Blogs.Include(e => e.Posts).SingleAsync(e => e.Id == 1); #region Work_with_a_single_navigation_2a CollectionEntry collectionEntry1 = context.Entry(blog).Collection(e => e.Posts); @@ -174,17 +175,17 @@ public static void Work_with_a_single_navigation_2() Console.WriteLine(); } - public static void Work_with_all_properties_of_an_entity_1() + public static async Task Work_with_all_properties_of_an_entity_1() { Console.WriteLine($">>>> Sample: {nameof(Work_with_all_properties_of_an_entity_1)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BlogsContext(); - var blog = context.Blogs.Include(e => e.Posts).Single(e => e.Id == 1); + var blog = await context.Blogs.Include(e => e.Posts).SingleAsync(e => e.Id == 1); #region Work_with_all_properties_of_an_entity_1 foreach (var propertyEntry in context.Entry(blog).Properties) @@ -199,23 +200,23 @@ public static void Work_with_all_properties_of_an_entity_1() Console.WriteLine(); } - public static void Work_with_all_properties_of_an_entity_2() + public static async Task Work_with_all_properties_of_an_entity_2() { Console.WriteLine($">>>> Sample: {nameof(Work_with_all_properties_of_an_entity_2)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BlogsContext(); - var blog = context.Blogs.Include(e => e.Posts).Single(e => e.Id == 1); + var blog = await context.Blogs.Include(e => e.Posts).SingleAsync(e => e.Id == 1); { #region Work_with_all_properties_of_an_entity_2a var currentValues = context.Entry(blog).CurrentValues; var originalValues = context.Entry(blog).OriginalValues; - var databaseValues = context.Entry(blog).GetDatabaseValues(); + var databaseValues = await context.Entry(blog).GetDatabaseValuesAsync(); #endregion } @@ -229,7 +230,7 @@ public static void Work_with_all_properties_of_an_entity_2() { #region Work_with_all_properties_of_an_entity_2c - var databaseValues = context.Entry(blog).GetDatabaseValues(); + var databaseValues = await context.Entry(blog).GetDatabaseValuesAsync(); context.Entry(blog).CurrentValues.SetValues(databaseValues); context.Entry(blog).OriginalValues.SetValues(databaseValues); #endregion @@ -245,24 +246,24 @@ public static void Work_with_all_properties_of_an_entity_2() { #region Work_with_all_properties_of_an_entity_2e - var clonedBlog = context.Entry(blog).GetDatabaseValues().ToObject(); + var clonedBlog = (await context.Entry(blog).GetDatabaseValuesAsync()).ToObject(); #endregion } Console.WriteLine(); } - public static void Work_with_all_navigations_of_an_entity_1() + public static async Task Work_with_all_navigations_of_an_entity_1() { Console.WriteLine($">>>> Sample: {nameof(Work_with_all_navigations_of_an_entity_1)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BlogsContext(); - var blog = context.Blogs.Single(e => e.Id == 1); + var blog = await context.Blogs.SingleAsync(e => e.Id == 1); #region Work_with_all_navigations_of_an_entity_1 foreach (var navigationEntry in context.Entry(blog).Navigations) @@ -274,17 +275,17 @@ public static void Work_with_all_navigations_of_an_entity_1() Console.WriteLine(); } - public static void Work_with_all_members_of_an_entity_1() + public static async Task Work_with_all_members_of_an_entity_1() { Console.WriteLine($">>>> Sample: {nameof(Work_with_all_members_of_an_entity_1)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BlogsContext(); - var blog = context.Blogs.Single(e => e.Id == 1); + var blog = await context.Blogs.SingleAsync(e => e.Id == 1); #region Work_with_all_members_of_an_entity_1 foreach (var memberEntry in context.Entry(blog).Members) @@ -297,25 +298,25 @@ public static void Work_with_all_members_of_an_entity_1() Console.WriteLine(); } - public static void Find_and_FindAsync_1() + public static async Task Find_and_FindAsync_1() { Console.WriteLine($">>>> Sample: {nameof(Find_and_FindAsync_1)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); #region Find_and_FindAsync_1 using var context = new BlogsContext(); Console.WriteLine("First call to Find..."); - var blog1 = context.Blogs.Find(1); + var blog1 = await context.Blogs.FindAsync(1); Console.WriteLine($"...found blog {blog1.Name}"); Console.WriteLine(); Console.WriteLine("Second call to Find..."); - var blog2 = context.Blogs.Find(1); + var blog2 = await context.Blogs.FindAsync(1); Debug.Assert(blog1 == blog2); Console.WriteLine("...returned the same instance without executing a query."); @@ -324,36 +325,36 @@ public static void Find_and_FindAsync_1() Console.WriteLine(); } - public static void Find_and_FindAsync_2() + public static async Task Find_and_FindAsync_2() { Console.WriteLine($">>>> Sample: {nameof(Find_and_FindAsync_2)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BlogsContext(); var orderId = 1; var productId = 2; #region Find_and_FindAsync_2 - var orderline = context.OrderLines.Find(orderId, productId); + var orderline = await context.OrderLines.FindAsync(orderId, productId); #endregion Console.WriteLine(); } - public static void Using_ChangeTracker_Entries_to_access_all_tracked_entities_1() + public static async Task Using_ChangeTracker_Entries_to_access_all_tracked_entities_1() { Console.WriteLine($">>>> Sample: {nameof(Using_ChangeTracker_Entries_to_access_all_tracked_entities_1)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); #region Using_ChangeTracker_Entries_to_access_all_tracked_entities_1a using var context = new BlogsContext(); - var blogs = context.Blogs.Include(e => e.Posts).ToList(); + var blogs = await context.Blogs.Include(e => e.Posts).ToListAsync(); foreach (var entityEntry in context.ChangeTracker.Entries()) { @@ -384,18 +385,18 @@ public static void Using_ChangeTracker_Entries_to_access_all_tracked_entities_1( Console.WriteLine(); } - public static void Using_DbSet_Local_to_query_tracked_entities_1() + public static async Task Using_DbSet_Local_to_query_tracked_entities_1() { Console.WriteLine($">>>> Sample: {nameof(Using_DbSet_Local_to_query_tracked_entities_1)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); #region Using_DbSet_Local_to_query_tracked_entities_1 using var context = new BlogsContext(); - context.Blogs.Include(e => e.Posts).Load(); + await context.Blogs.Include(e => e.Posts).LoadAsync(); foreach (var blog in context.Blogs.Local) { @@ -411,18 +412,18 @@ public static void Using_DbSet_Local_to_query_tracked_entities_1() Console.WriteLine(); } - public static void Using_DbSet_Local_to_query_tracked_entities_2() + public static async Task Using_DbSet_Local_to_query_tracked_entities_2() { Console.WriteLine($">>>> Sample: {nameof(Using_DbSet_Local_to_query_tracked_entities_2)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); #region Using_DbSet_Local_to_query_tracked_entities_2 using var context = new BlogsContext(); - var posts = context.Posts.Include(e => e.Blog).ToList(); + var posts = await context.Posts.Include(e => e.Blog).ToListAsync(); Console.WriteLine("Local view after loading posts:"); @@ -452,18 +453,18 @@ public static void Using_DbSet_Local_to_query_tracked_entities_2() Console.WriteLine(); } - public static void Using_DbSet_Local_to_query_tracked_entities_3() + public static async Task Using_DbSet_Local_to_query_tracked_entities_3() { Console.WriteLine($">>>> Sample: {nameof(Using_DbSet_Local_to_query_tracked_entities_3)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); #region Using_DbSet_Local_to_query_tracked_entities_3 using var context = new BlogsContext(); - var posts = context.Posts.Include(e => e.Blog).ToList(); + var posts = await context.Posts.Include(e => e.Blog).ToListAsync(); Console.WriteLine("Local view after loading posts:"); @@ -493,17 +494,17 @@ public static void Using_DbSet_Local_to_query_tracked_entities_3() Console.WriteLine(); } - public static void Using_DbSet_Local_to_query_tracked_entities_4() + public static async Task Using_DbSet_Local_to_query_tracked_entities_4() { Console.WriteLine($">>>> Sample: {nameof(Using_DbSet_Local_to_query_tracked_entities_4)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BlogsContext(); - context.Posts.Include(e => e.Blog).Load(); + await context.Posts.Include(e => e.Blog).LoadAsync(); #region Using_DbSet_Local_to_query_tracked_entities_4 ObservableCollection observableCollection = context.Posts.Local.ToObservableCollection(); @@ -516,15 +517,15 @@ public static void Using_DbSet_Local_to_query_tracked_entities_4() public static class Helpers { - public static void RecreateCleanDatabase() + public static async Task RecreateCleanDatabase() { using var context = new BlogsContext(quiet: true); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } - public static void PopulateDatabase() + public static async Task PopulateDatabase() { using var context = new BlogsContext(quiet: true); @@ -547,7 +548,7 @@ public static void PopulateDatabase() } }); - context.SaveChanges(); + await context.SaveChangesAsync(); } } diff --git a/samples/core/ChangeTracking/AdditionalChangeTrackingFeatures/DefaultValueSamples.cs b/samples/core/ChangeTracking/AdditionalChangeTrackingFeatures/DefaultValueSamples.cs index 607fff9e2f..ed1fa5ec04 100644 --- a/samples/core/ChangeTracking/AdditionalChangeTrackingFeatures/DefaultValueSamples.cs +++ b/samples/core/ChangeTracking/AdditionalChangeTrackingFeatures/DefaultValueSamples.cs @@ -1,5 +1,6 @@ using System; using System.Diagnostics; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; @@ -7,12 +8,12 @@ namespace DefaultValues; public class DefaultValueSamples { - public static void Working_with_default_values_1() + public static async Task Working_with_default_values_1() { Console.WriteLine($">>>> Sample: {nameof(Working_with_default_values_1)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); + await Helpers.RecreateCleanDatabase(); #region Working_with_default_values_1 using var context = new BlogsContext(); @@ -21,7 +22,7 @@ public static void Working_with_default_values_1() new Token { Name = "A" }, new Token { Name = "B", ValidFrom = new DateTime(1111, 11, 11, 11, 11, 11) }); - context.SaveChanges(); + await context.SaveChangesAsync(); Console.WriteLine(context.ChangeTracker.DebugView.LongView); #endregion @@ -29,12 +30,12 @@ public static void Working_with_default_values_1() Console.WriteLine(); } - public static void Working_with_default_values_2() + public static async Task Working_with_default_values_2() { Console.WriteLine($">>>> Sample: {nameof(Working_with_default_values_2)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); + await Helpers.RecreateCleanDatabase(); #region Working_with_default_values_2 using var context = new BlogsContext(); @@ -44,7 +45,7 @@ public static void Working_with_default_values_2() var fooC = new Foo1(); context.AddRange(fooA, fooB, fooC); - context.SaveChanges(); + await context.SaveChangesAsync(); Debug.Assert(fooA.Count == 10); Debug.Assert(fooB.Count == -1); // Not what we want! @@ -54,12 +55,12 @@ public static void Working_with_default_values_2() Console.WriteLine(); } - public static void Working_with_default_values_3() + public static async Task Working_with_default_values_3() { Console.WriteLine($">>>> Sample: {nameof(Working_with_default_values_3)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); + await Helpers.RecreateCleanDatabase(); #region Working_with_default_values_3 using var context = new BlogsContext(); @@ -69,7 +70,7 @@ public static void Working_with_default_values_3() var fooC = new Foo2(); context.AddRange(fooA, fooB, fooC); - context.SaveChanges(); + await context.SaveChangesAsync(); Debug.Assert(fooA.Count == 10); Debug.Assert(fooB.Count == 0); @@ -79,12 +80,12 @@ public static void Working_with_default_values_3() Console.WriteLine(); } - public static void Working_with_default_values_4() + public static async Task Working_with_default_values_4() { Console.WriteLine($">>>> Sample: {nameof(Working_with_default_values_4)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); + await Helpers.RecreateCleanDatabase(); #region Working_with_default_values_4 using var context = new BlogsContext(); @@ -94,7 +95,7 @@ public static void Working_with_default_values_4() var fooC = new Foo3(); context.AddRange(fooA, fooB, fooC); - context.SaveChanges(); + await context.SaveChangesAsync(); Debug.Assert(fooA.Count == 10); Debug.Assert(fooB.Count == 0); @@ -104,12 +105,12 @@ public static void Working_with_default_values_4() Console.WriteLine(); } - public static void Working_with_default_values_5() + public static async Task Working_with_default_values_5() { Console.WriteLine($">>>> Sample: {nameof(Working_with_default_values_5)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); + await Helpers.RecreateCleanDatabase(); #region Working_with_default_values_5 using var context = new BlogsContext(); @@ -120,7 +121,7 @@ public static void Working_with_default_values_5() context.AddRange(userA, userB, userC); - context.SaveChanges(); + await context.SaveChangesAsync(); #endregion Console.WriteLine(); @@ -129,12 +130,12 @@ public static void Working_with_default_values_5() public static class Helpers { - public static void RecreateCleanDatabase() + public static async Task RecreateCleanDatabase() { using var context = new BlogsContext(quiet: true); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } } @@ -268,4 +269,4 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .ValueGeneratedNever(); #endregion } -} \ No newline at end of file +} diff --git a/samples/core/ChangeTracking/AdditionalChangeTrackingFeatures/Program.cs b/samples/core/ChangeTracking/AdditionalChangeTrackingFeatures/Program.cs index 41ff74e4c0..9ab29ed7e0 100644 --- a/samples/core/ChangeTracking/AdditionalChangeTrackingFeatures/Program.cs +++ b/samples/core/ChangeTracking/AdditionalChangeTrackingFeatures/Program.cs @@ -1,22 +1,23 @@ using System; +using System.Threading.Tasks; using DefaultValues; using Optional; public class Program { - public static void Main() + public static async Task Main() { Console.WriteLine("Samples for _Identity Resolution in EF Core_"); Console.WriteLine(); - Samples.DbContext_versus_DbSet_methods_1(); - Samples.Temporary_values_1(); - Samples.Temporary_values_2(); + await Samples.DbContext_versus_DbSet_methods_1(); + await Samples.Temporary_values_1(); + await Samples.Temporary_values_2(); - DefaultValueSamples.Working_with_default_values_1(); - DefaultValueSamples.Working_with_default_values_2(); - DefaultValueSamples.Working_with_default_values_3(); - DefaultValueSamples.Working_with_default_values_4(); - DefaultValueSamples.Working_with_default_values_5(); + await DefaultValueSamples.Working_with_default_values_1(); + await DefaultValueSamples.Working_with_default_values_2(); + await DefaultValueSamples.Working_with_default_values_3(); + await DefaultValueSamples.Working_with_default_values_4(); + await DefaultValueSamples.Working_with_default_values_5(); } } diff --git a/samples/core/ChangeTracking/AdditionalChangeTrackingFeatures/Samples.cs b/samples/core/ChangeTracking/AdditionalChangeTrackingFeatures/Samples.cs index bbb09127bf..696969296f 100644 --- a/samples/core/ChangeTracking/AdditionalChangeTrackingFeatures/Samples.cs +++ b/samples/core/ChangeTracking/AdditionalChangeTrackingFeatures/Samples.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; @@ -8,19 +9,19 @@ namespace Optional; public class Samples { - public static void DbContext_versus_DbSet_methods_1() + public static async Task DbContext_versus_DbSet_methods_1() { Console.WriteLine($">>>> Sample: {nameof(DbContext_versus_DbSet_methods_1)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); #region DbContext_versus_DbSet_methods_1 using var context = new BlogsContext(); - var post = context.Posts.Single(e => e.Id == 3); - var tag = context.Tags.Single(e => e.Id == 1); + var post = await context.Posts.SingleAsync(e => e.Id == 3); + var tag = await context.Tags.SingleAsync(e => e.Id == 1); var joinEntitySet = context.Set>("PostTag"); var joinEntity = new Dictionary { ["PostId"] = post.Id, ["TagId"] = tag.Id }; @@ -28,19 +29,19 @@ public static void DbContext_versus_DbSet_methods_1() Console.WriteLine(context.ChangeTracker.DebugView.LongView); - context.SaveChanges(); + await context.SaveChangesAsync(); #endregion Console.WriteLine(); } - public static void Temporary_values_1() + public static async Task Temporary_values_1() { Console.WriteLine($">>>> Sample: {nameof(Temporary_values_1)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); #region Temporary_values_1 using var context = new BlogsContext(); @@ -56,12 +57,12 @@ public static void Temporary_values_1() Console.WriteLine(); } - public static void Temporary_values_2() + public static async Task Temporary_values_2() { Console.WriteLine($">>>> Sample: {nameof(Temporary_values_2)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); + await Helpers.RecreateCleanDatabase(); #region Temporary_values_2 var blogs = new List { new Blog { Id = -1, Name = ".NET Blog" }, new Blog { Id = -2, Name = "Visual Studio Blog" } }; @@ -98,7 +99,7 @@ public static void Temporary_values_2() Console.WriteLine(context.ChangeTracker.DebugView.LongView); - context.SaveChanges(); + await context.SaveChangesAsync(); Console.WriteLine(context.ChangeTracker.DebugView.LongView); #endregion @@ -109,15 +110,15 @@ public static void Temporary_values_2() public static class Helpers { - public static void RecreateCleanDatabase() + public static async Task RecreateCleanDatabase() { using var context = new BlogsContext(quiet: true); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } - public static void PopulateDatabase() + public static async Task PopulateDatabase() { using var context = new BlogsContext(quiet: true); @@ -161,7 +162,7 @@ public static void PopulateDatabase() new Tag { Text = "Visual Studio" }, new Tag { Text = "EF Core" }); - context.SaveChanges(); + await context.SaveChangesAsync(); } } @@ -241,4 +242,4 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) j => j.HasOne().WithMany()); } #endregion -} \ No newline at end of file +} diff --git a/samples/core/ChangeTracking/ChangeDetectionAndNotifications/ChangeTrackingProxiesSamples.cs b/samples/core/ChangeTracking/ChangeDetectionAndNotifications/ChangeTrackingProxiesSamples.cs index a1ab530e6d..548717fc87 100644 --- a/samples/core/ChangeTracking/ChangeDetectionAndNotifications/ChangeTrackingProxiesSamples.cs +++ b/samples/core/ChangeTracking/ChangeDetectionAndNotifications/ChangeTrackingProxiesSamples.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; @@ -9,17 +10,17 @@ namespace Proxies; public class ChangeTrackingProxiesSamples { - public static void Change_tracking_proxies_1() + public static async Task Change_tracking_proxies_1() { Console.WriteLine($">>>> Sample: {nameof(Change_tracking_proxies_1)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); #region Change_tracking_proxies_1 using var context = new BlogsContext(); - var blog = context.Blogs.Include(e => e.Posts).First(e => e.Name == ".NET Blog"); + var blog = await context.Blogs.Include(e => e.Posts).FirstAsync(e => e.Name == ".NET Blog"); // Change a property value blog.Name = ".NET Blog (Updated!)"; @@ -42,15 +43,15 @@ public static void Change_tracking_proxies_1() public static class Helpers { - public static void RecreateCleanDatabase() + public static async Task RecreateCleanDatabase() { using var context = new BlogsContext(quiet: true); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } - public static void PopulateDatabase() + public static async Task PopulateDatabase() { using var context = new BlogsContext(quiet: true); @@ -95,7 +96,7 @@ public static void PopulateDatabase() })); })); - context.SaveChanges(); + await context.SaveChangesAsync(); } } @@ -152,4 +153,4 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) base.OnConfiguring(optionsBuilder); } -} \ No newline at end of file +} diff --git a/samples/core/ChangeTracking/ChangeDetectionAndNotifications/NotificationEntitiesSamples.cs b/samples/core/ChangeTracking/ChangeDetectionAndNotifications/NotificationEntitiesSamples.cs index 349c884455..61091f861f 100644 --- a/samples/core/ChangeTracking/ChangeDetectionAndNotifications/NotificationEntitiesSamples.cs +++ b/samples/core/ChangeTracking/ChangeDetectionAndNotifications/NotificationEntitiesSamples.cs @@ -3,6 +3,7 @@ using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; @@ -10,17 +11,17 @@ namespace Notification; public class NotificationEntitiesSamples { - public static void Notification_entities_1() + public static async Task Notification_entities_1() { Console.WriteLine($">>>> Sample: {nameof(Notification_entities_1)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); #region Notification_entities_1 using var context = new BlogsContext(); - var blog = context.Blogs.Include(e => e.Posts).First(e => e.Name == ".NET Blog"); + var blog = await context.Blogs.Include(e => e.Posts).FirstAsync(e => e.Name == ".NET Blog"); // Change a property value blog.Name = ".NET Blog (Updated!)"; @@ -41,15 +42,15 @@ public static void Notification_entities_1() public static class Helpers { - public static void RecreateCleanDatabase() + public static async Task RecreateCleanDatabase() { using var context = new BlogsContext(quiet: true); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } - public static void PopulateDatabase() + public static async Task PopulateDatabase() { using var context = new BlogsContext(quiet: true); @@ -90,7 +91,7 @@ public static void PopulateDatabase() } }); - context.SaveChanges(); + await context.SaveChangesAsync(); } } @@ -229,4 +230,4 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.HasChangeTrackingStrategy(ChangeTrackingStrategy.ChangingAndChangedNotifications); } -} \ No newline at end of file +} diff --git a/samples/core/ChangeTracking/ChangeDetectionAndNotifications/NotificationWithBaseSamples.cs b/samples/core/ChangeTracking/ChangeDetectionAndNotifications/NotificationWithBaseSamples.cs index f1b1ac1c8f..5eb2c6aa97 100644 --- a/samples/core/ChangeTracking/ChangeDetectionAndNotifications/NotificationWithBaseSamples.cs +++ b/samples/core/ChangeTracking/ChangeDetectionAndNotifications/NotificationWithBaseSamples.cs @@ -4,6 +4,7 @@ using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; @@ -11,17 +12,17 @@ namespace NotificationWithBase; public class NotificationWithBaseSamples { - public static void Notification_entities_2() + public static async Task Notification_entities_2() { Console.WriteLine($">>>> Sample: {nameof(Notification_entities_2)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); #region Notification_entities_2 using var context = new BlogsContext(); - var blog = context.Blogs.Include(e => e.Posts).First(e => e.Name == ".NET Blog"); + var blog = await context.Blogs.Include(e => e.Posts).FirstAsync(e => e.Name == ".NET Blog"); // Change a property value blog.Name = ".NET Blog (Updated!)"; @@ -42,15 +43,15 @@ public static void Notification_entities_2() public static class Helpers { - public static void RecreateCleanDatabase() + public static async Task RecreateCleanDatabase() { using var context = new BlogsContext(quiet: true); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } - public static void PopulateDatabase() + public static async Task PopulateDatabase() { using var context = new BlogsContext(quiet: true); @@ -91,7 +92,7 @@ public static void PopulateDatabase() } }); - context.SaveChanges(); + await context.SaveChangesAsync(); } } @@ -206,4 +207,4 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) modelBuilder.HasChangeTrackingStrategy(ChangeTrackingStrategy.ChangingAndChangedNotifications); } #endregion -} \ No newline at end of file +} diff --git a/samples/core/ChangeTracking/ChangeDetectionAndNotifications/Program.cs b/samples/core/ChangeTracking/ChangeDetectionAndNotifications/Program.cs index 09fd03249e..dbb789642b 100644 --- a/samples/core/ChangeTracking/ChangeDetectionAndNotifications/Program.cs +++ b/samples/core/ChangeTracking/ChangeDetectionAndNotifications/Program.cs @@ -1,4 +1,5 @@ using System; +using System.Threading.Tasks; using Notification; using NotificationWithBase; using Proxies; @@ -6,17 +7,17 @@ public class Program { - public static void Main() + public static async Task Main() { Console.WriteLine("Samples for _Change Detection and Notifications_"); Console.WriteLine(); - SnapshotSamples.Snapshot_change_tracking_1(); - SnapshotSamples.Snapshot_change_tracking_2(); + await SnapshotSamples.Snapshot_change_tracking_1(); + await SnapshotSamples.Snapshot_change_tracking_2(); - NotificationEntitiesSamples.Notification_entities_1(); - NotificationWithBaseSamples.Notification_entities_2(); + await NotificationEntitiesSamples.Notification_entities_1(); + await NotificationWithBaseSamples.Notification_entities_2(); - ChangeTrackingProxiesSamples.Change_tracking_proxies_1(); + await ChangeTrackingProxiesSamples.Change_tracking_proxies_1(); } } diff --git a/samples/core/ChangeTracking/ChangeDetectionAndNotifications/SnapshotSamples.cs b/samples/core/ChangeTracking/ChangeDetectionAndNotifications/SnapshotSamples.cs index e3d63659cf..f7f49ad910 100644 --- a/samples/core/ChangeTracking/ChangeDetectionAndNotifications/SnapshotSamples.cs +++ b/samples/core/ChangeTracking/ChangeDetectionAndNotifications/SnapshotSamples.cs @@ -1,6 +1,8 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; @@ -8,17 +10,17 @@ namespace Snapshot; public class SnapshotSamples { - public static void Snapshot_change_tracking_1() + public static async Task Snapshot_change_tracking_1() { Console.WriteLine($">>>> Sample: {nameof(Snapshot_change_tracking_1)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); #region Snapshot_change_tracking_1 using var context = new BlogsContext(); - var blog = context.Blogs.Include(e => e.Posts).First(e => e.Name == ".NET Blog"); + var blog = await context.Blogs.Include(e => e.Posts).FirstAsync(e => e.Name == ".NET Blog"); // Change a property value blog.Name = ".NET Blog (Updated!)"; @@ -38,17 +40,17 @@ public static void Snapshot_change_tracking_1() Console.WriteLine(); } - public static void Snapshot_change_tracking_2() + public static async Task Snapshot_change_tracking_2() { Console.WriteLine($">>>> Sample: {nameof(Snapshot_change_tracking_2)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); #region Snapshot_change_tracking_2 using var context = new BlogsContext(); - var blog = context.Blogs.Include(e => e.Posts).First(e => e.Name == ".NET Blog"); + var blog = await context.Blogs.Include(e => e.Posts).FirstAsync(e => e.Name == ".NET Blog"); // Change a property value context.Entry(blog).Property(e => e.Name).CurrentValue = ".NET Blog (Updated!)"; @@ -71,15 +73,15 @@ public static void Snapshot_change_tracking_2() public static class Helpers { - public static void RecreateCleanDatabase() + public static async Task RecreateCleanDatabase() { using var context = new BlogsContext(quiet: true); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } - public static void PopulateDatabase() + public static async Task PopulateDatabase() { using var context = new BlogsContext(quiet: true); @@ -120,7 +122,7 @@ public static void PopulateDatabase() } }); - context.SaveChanges(); + await context.SaveChangesAsync(); } } @@ -181,7 +183,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) } #region SaveChanges - public override int SaveChanges() + public override async Task SaveChangesAsync(CancellationToken cancellationToken = default) { foreach (var entityEntry in ChangeTracker.Entries()) // Detects changes automatically { @@ -195,7 +197,7 @@ public override int SaveChanges() try { ChangeTracker.AutoDetectChangesEnabled = false; - return base.SaveChanges(); // Avoid automatically detecting changes again here + return await base.SaveChangesAsync(cancellationToken); // Avoid automatically detecting changes again here } finally { @@ -203,4 +205,4 @@ public override int SaveChanges() } } #endregion -} \ No newline at end of file +} diff --git a/samples/core/ChangeTracking/ChangeTrackerDebugging/Program.cs b/samples/core/ChangeTracking/ChangeTrackerDebugging/Program.cs index b878822988..1d6eeb0533 100644 --- a/samples/core/ChangeTracking/ChangeTrackerDebugging/Program.cs +++ b/samples/core/ChangeTracking/ChangeTrackerDebugging/Program.cs @@ -1,13 +1,14 @@ using System; +using System.Threading.Tasks; public class Program { - public static void Main() + public static async Task Main() { Console.WriteLine("Samples for _Change Tracker Debugging_"); Console.WriteLine(); - Samples.Change_tracker_debug_view_1(); - Samples.Change_tracker_logging_1(); + await Samples.Change_tracker_debug_view_1(); + await Samples.Change_tracker_logging_1(); } } diff --git a/samples/core/ChangeTracking/ChangeTrackerDebugging/Samples.cs b/samples/core/ChangeTracking/ChangeTrackerDebugging/Samples.cs index e9f16413be..4c2950281e 100644 --- a/samples/core/ChangeTracking/ChangeTrackerDebugging/Samples.cs +++ b/samples/core/ChangeTracking/ChangeTrackerDebugging/Samples.cs @@ -1,27 +1,28 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.Extensions.Logging; public class Samples { - public static void Change_tracker_debug_view_1() + public static async Task Change_tracker_debug_view_1() { Console.WriteLine($">>>> Sample: {nameof(Change_tracker_debug_view_1)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); #region Change_tracker_debug_view_1a using var context = new BlogsContext(); - var blogs = context.Blogs + var blogs = await context.Blogs .Include(e => e.Posts).ThenInclude(e => e.Tags) .Include(e => e.Assets) - .ToList(); + .ToListAsync(); // Mark something Added blogs[0].Posts.Add( @@ -55,20 +56,20 @@ public static void Change_tracker_debug_view_1() Console.WriteLine(); } - public static void Change_tracker_logging_1() + public static async Task Change_tracker_logging_1() { Console.WriteLine($">>>> Sample: {nameof(Change_tracker_logging_1)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BlogsContext(LogLevel.Debug); - var blogs = context.Blogs + var blogs = await context.Blogs .Include(e => e.Posts).ThenInclude(e => e.Tags) .Include(e => e.Assets) - .ToList(); + .ToListAsync(); // Mark something Added blogs[0].Posts.Add( @@ -92,15 +93,15 @@ public static void Change_tracker_logging_1() public static class Helpers { - public static void RecreateCleanDatabase() + public static async Task RecreateCleanDatabase() { using var context = new BlogsContext(LogLevel.Error); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } - public static void PopulateDatabase() + public static async Task PopulateDatabase() { using var context = new BlogsContext(LogLevel.Error); @@ -155,7 +156,7 @@ public static void PopulateDatabase() context.AddRange(blogs); context.AddRange(tags); - context.SaveChanges(); + await context.SaveChangesAsync(); } } diff --git a/samples/core/ChangeTracking/ChangeTrackingInEFCore/ExplicitKeysRequiredSamples.cs b/samples/core/ChangeTracking/ChangeTrackingInEFCore/ExplicitKeysRequiredSamples.cs index 11d4aedbfd..425e2ec130 100644 --- a/samples/core/ChangeTracking/ChangeTrackingInEFCore/ExplicitKeysRequiredSamples.cs +++ b/samples/core/ChangeTracking/ChangeTrackingInEFCore/ExplicitKeysRequiredSamples.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; @@ -9,17 +10,17 @@ namespace ExplicitKeysRequired; public static class ExplicitKeysRequiredSamples { - public static void Deleting_principal_parent_entities_1() + public static async Task Deleting_principal_parent_entities_1() { Console.WriteLine($">>>> Sample: {nameof(Deleting_principal_parent_entities_1)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BlogsContext(); - var blog = GetDisconnectedBlogAndPosts(); + var blog = await GetDisconnectedBlogAndPosts(); #region Deleting_principal_parent_entities_1 // Attach a blog and associated posts @@ -32,32 +33,32 @@ public static void Deleting_principal_parent_entities_1() Console.WriteLine("Before SaveChanges:"); Console.WriteLine(context.ChangeTracker.DebugView.LongView); - context.SaveChanges(); + await context.SaveChangesAsync(); Console.WriteLine("After SaveChanges:"); Console.WriteLine(context.ChangeTracker.DebugView.LongView); Console.WriteLine(); - Blog GetDisconnectedBlogAndPosts() + async Task GetDisconnectedBlogAndPosts() { using var tempContext = new BlogsContext(); - return tempContext.Blogs.Include(e => e.Posts).Single(); + return await tempContext.Blogs.Include(e => e.Posts).SingleAsync(); } } } public static class Helpers { - public static void RecreateCleanDatabase() + public static async Task RecreateCleanDatabase() { using var context = new BlogsContext(quiet: true); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } - public static void PopulateDatabase() + public static async Task PopulateDatabase() { using var context = new BlogsContext(quiet: true); @@ -83,7 +84,7 @@ public static void PopulateDatabase() } }); - context.SaveChanges(); + await context.SaveChangesAsync(); } } @@ -134,4 +135,4 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) optionsBuilder.LogTo(Console.WriteLine, new[] { RelationalEventId.CommandExecuted }); } } -} \ No newline at end of file +} diff --git a/samples/core/ChangeTracking/ChangeTrackingInEFCore/ExplicitKeysSamples.cs b/samples/core/ChangeTracking/ChangeTrackingInEFCore/ExplicitKeysSamples.cs index 50ff569cb6..254ecebe2f 100644 --- a/samples/core/ChangeTracking/ChangeTrackingInEFCore/ExplicitKeysSamples.cs +++ b/samples/core/ChangeTracking/ChangeTrackingInEFCore/ExplicitKeysSamples.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; @@ -9,12 +10,12 @@ namespace ExplicitKeys; public static class ExplicitKeysSamples { - public static void Inserting_new_entities_1() + public static async Task Inserting_new_entities_1() { Console.WriteLine($">>>> Sample: {nameof(Inserting_new_entities_1)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); + await Helpers.RecreateCleanDatabase(); using var context = new BlogsContext(); @@ -26,7 +27,7 @@ public static void Inserting_new_entities_1() Console.WriteLine("Before SaveChanges:"); Console.WriteLine(context.ChangeTracker.DebugView.LongView); - context.SaveChanges(); + await context.SaveChangesAsync(); Console.WriteLine("After SaveChanges:"); Console.WriteLine(context.ChangeTracker.DebugView.LongView); @@ -34,12 +35,12 @@ public static void Inserting_new_entities_1() Console.WriteLine(); } - public static void Inserting_new_entities_2() + public static async Task Inserting_new_entities_2() { Console.WriteLine($">>>> Sample: {nameof(Inserting_new_entities_2)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); + await Helpers.RecreateCleanDatabase(); using var context = new BlogsContext(); @@ -70,7 +71,7 @@ public static void Inserting_new_entities_2() Console.WriteLine("Before SaveChanges:"); Console.WriteLine(context.ChangeTracker.DebugView.LongView); - context.SaveChanges(); + await context.SaveChangesAsync(); Console.WriteLine("After SaveChanges:"); Console.WriteLine(context.ChangeTracker.DebugView.LongView); @@ -78,13 +79,13 @@ public static void Inserting_new_entities_2() Console.WriteLine(); } - public static void Attaching_existing_entities_1() + public static async Task Attaching_existing_entities_1() { Console.WriteLine($">>>> Sample: {nameof(Attaching_existing_entities_1)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BlogsContext(); @@ -96,7 +97,7 @@ public static void Attaching_existing_entities_1() Console.WriteLine("Before SaveChanges:"); Console.WriteLine(context.ChangeTracker.DebugView.LongView); - context.SaveChanges(); + await context.SaveChangesAsync(); Console.WriteLine("After SaveChanges:"); Console.WriteLine(context.ChangeTracker.DebugView.LongView); @@ -104,13 +105,13 @@ public static void Attaching_existing_entities_1() Console.WriteLine(); } - public static void Attaching_existing_entities_2() + public static async Task Attaching_existing_entities_2() { Console.WriteLine($">>>> Sample: {nameof(Attaching_existing_entities_2)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BlogsContext(); @@ -141,7 +142,7 @@ public static void Attaching_existing_entities_2() Console.WriteLine("Before SaveChanges:"); Console.WriteLine(context.ChangeTracker.DebugView.LongView); - context.SaveChanges(); + await context.SaveChangesAsync(); Console.WriteLine("After SaveChanges:"); Console.WriteLine(context.ChangeTracker.DebugView.LongView); @@ -149,13 +150,13 @@ public static void Attaching_existing_entities_2() Console.WriteLine(); } - public static void Updating_existing_entities_1() + public static async Task Updating_existing_entities_1() { Console.WriteLine($">>>> Sample: {nameof(Updating_existing_entities_1)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BlogsContext(); @@ -167,7 +168,7 @@ public static void Updating_existing_entities_1() Console.WriteLine("Before SaveChanges:"); Console.WriteLine(context.ChangeTracker.DebugView.LongView); - context.SaveChanges(); + await context.SaveChangesAsync(); Console.WriteLine("After SaveChanges:"); Console.WriteLine(context.ChangeTracker.DebugView.LongView); @@ -175,13 +176,13 @@ public static void Updating_existing_entities_1() Console.WriteLine(); } - public static void Updating_existing_entities_2() + public static async Task Updating_existing_entities_2() { Console.WriteLine($">>>> Sample: {nameof(Updating_existing_entities_2)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BlogsContext(); @@ -212,7 +213,7 @@ public static void Updating_existing_entities_2() Console.WriteLine("Before SaveChanges:"); Console.WriteLine(context.ChangeTracker.DebugView.LongView); - context.SaveChanges(); + await context.SaveChangesAsync(); Console.WriteLine("After SaveChanges:"); Console.WriteLine(context.ChangeTracker.DebugView.LongView); @@ -220,13 +221,13 @@ public static void Updating_existing_entities_2() Console.WriteLine(); } - public static void Deleting_existing_entities_1() + public static async Task Deleting_existing_entities_1() { Console.WriteLine($">>>> Sample: {nameof(Deleting_existing_entities_1)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BlogsContext(); @@ -238,7 +239,7 @@ public static void Deleting_existing_entities_1() Console.WriteLine("Before SaveChanges:"); Console.WriteLine(context.ChangeTracker.DebugView.LongView); - context.SaveChanges(); + await context.SaveChangesAsync(); Console.WriteLine("After SaveChanges:"); Console.WriteLine(context.ChangeTracker.DebugView.LongView); @@ -246,17 +247,17 @@ public static void Deleting_existing_entities_1() Console.WriteLine(); } - public static void Deleting_dependent_child_entities_1() + public static async Task Deleting_dependent_child_entities_1() { Console.WriteLine($">>>> Sample: {nameof(Deleting_dependent_child_entities_1)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BlogsContext(); - var post = GetDisconnectedPost(); + var post = await GetDisconnectedPost(); #region Deleting_dependent_child_entities_1 context.Attach(post); @@ -266,31 +267,31 @@ public static void Deleting_dependent_child_entities_1() Console.WriteLine("Before SaveChanges:"); Console.WriteLine(context.ChangeTracker.DebugView.LongView); - context.SaveChanges(); + await context.SaveChangesAsync(); Console.WriteLine("After SaveChanges:"); Console.WriteLine(context.ChangeTracker.DebugView.LongView); Console.WriteLine(); - Post GetDisconnectedPost() + async Task GetDisconnectedPost() { using var tempContext = new BlogsContext(); - return tempContext.Posts.Find(2); + return await tempContext.Posts.FindAsync(2); } } - public static void Deleting_dependent_child_entities_2() + public static async Task Deleting_dependent_child_entities_2() { Console.WriteLine($">>>> Sample: {nameof(Deleting_dependent_child_entities_2)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BlogsContext(); - var blog = GetDisconnectedBlogAndPosts(); + var blog = await GetDisconnectedBlogAndPosts(); #region Deleting_dependent_child_entities_2 // Attach a blog and associated posts @@ -303,31 +304,31 @@ public static void Deleting_dependent_child_entities_2() Console.WriteLine("Before SaveChanges:"); Console.WriteLine(context.ChangeTracker.DebugView.LongView); - context.SaveChanges(); + await context.SaveChangesAsync(); Console.WriteLine("After SaveChanges:"); Console.WriteLine(context.ChangeTracker.DebugView.LongView); Console.WriteLine(); - Blog GetDisconnectedBlogAndPosts() + async Task GetDisconnectedBlogAndPosts() { using var tempContext = new BlogsContext(); - return tempContext.Blogs.Include(e => e.Posts).Single(); + return await tempContext.Blogs.Include(e => e.Posts).SingleAsync(); } } - public static void Deleting_principal_parent_entities_1() + public static async Task Deleting_principal_parent_entities_1() { Console.WriteLine($">>>> Sample: {nameof(Deleting_principal_parent_entities_1)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BlogsContext(); - var blog = GetDisconnectedBlogAndPosts(); + var blog = await GetDisconnectedBlogAndPosts(); #region Deleting_principal_parent_entities_1 // Attach a blog and associated posts @@ -340,32 +341,32 @@ public static void Deleting_principal_parent_entities_1() Console.WriteLine("Before SaveChanges:"); Console.WriteLine(context.ChangeTracker.DebugView.LongView); - context.SaveChanges(); + await context.SaveChangesAsync(); Console.WriteLine("After SaveChanges:"); Console.WriteLine(context.ChangeTracker.DebugView.LongView); Console.WriteLine(); - Blog GetDisconnectedBlogAndPosts() + async Task GetDisconnectedBlogAndPosts() { using var tempContext = new BlogsContext(); - return tempContext.Blogs.Include(e => e.Posts).Single(); + return await tempContext.Blogs.Include(e => e.Posts).SingleAsync(); } } } public static class Helpers { - public static void RecreateCleanDatabase() + public static async Task RecreateCleanDatabase() { using var context = new BlogsContext(quiet: true); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } - public static void PopulateDatabase() + public static async Task PopulateDatabase() { using var context = new BlogsContext(quiet: true); @@ -391,7 +392,7 @@ public static void PopulateDatabase() } }); - context.SaveChanges(); + await context.SaveChangesAsync(); } } @@ -442,4 +443,4 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) optionsBuilder.LogTo(Console.WriteLine, new[] { RelationalEventId.CommandExecuted }); } } -} \ No newline at end of file +} diff --git a/samples/core/ChangeTracking/ChangeTrackingInEFCore/GeneratedKeysSamples.cs b/samples/core/ChangeTracking/ChangeTrackingInEFCore/GeneratedKeysSamples.cs index 0d2771fae2..7653d775e6 100644 --- a/samples/core/ChangeTracking/ChangeTrackingInEFCore/GeneratedKeysSamples.cs +++ b/samples/core/ChangeTracking/ChangeTrackingInEFCore/GeneratedKeysSamples.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; @@ -8,47 +9,47 @@ namespace GeneratedKeys; public static class GeneratedKeysSamples { - public static void Simple_query_and_update_1() + public static async Task Simple_query_and_update_1() { Console.WriteLine($">>>> Sample: {nameof(Simple_query_and_update_1)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); #region Simple_query_and_update_1 using var context = new BlogsContext(); - var blog = context.Blogs.Include(e => e.Posts).First(e => e.Name == ".NET Blog"); + var blog = await context.Blogs.Include(e => e.Posts).FirstAsync(e => e.Name == ".NET Blog"); blog.Name = ".NET Blog (Updated!)"; - foreach (var post in blog.Posts.Where(e => !e.Title.Contains("5.0"))) + await foreach (var post in blog.Posts.AsQueryable().Where(e => !e.Title.Contains("5.0")).AsAsyncEnumerable()) { post.Title = post.Title.Replace("5", "5.0"); } - context.SaveChanges(); + await context.SaveChangesAsync(); #endregion Console.WriteLine(); } - public static void Simple_query_and_update_2() + public static async Task Simple_query_and_update_2() { Console.WriteLine($">>>> Sample: {nameof(Simple_query_and_update_2)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BlogsContext(); - var blog = context.Blogs.Include(e => e.Posts).First(e => e.Name == ".NET Blog"); + var blog = await context.Blogs.Include(e => e.Posts).FirstAsync(e => e.Name == ".NET Blog"); blog.Name = ".NET Blog (Updated!)"; - foreach (var post in blog.Posts.Where(e => !e.Title.Contains("5.0"))) + await foreach (var post in blog.Posts.AsQueryable().Where(e => !e.Title.Contains("5.0")).AsAsyncEnumerable()) { post.Title = post.Title.Replace("5", "5.0"); } @@ -58,23 +59,23 @@ public static void Simple_query_and_update_2() Console.WriteLine(context.ChangeTracker.DebugView.LongView); #endregion - context.SaveChanges(); + await context.SaveChangesAsync(); Console.WriteLine(); } - public static void Query_then_insert_update_and_delete_1() + public static async Task Query_then_insert_update_and_delete_1() { Console.WriteLine($">>>> Sample: {nameof(Query_then_insert_update_and_delete_1)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); #region Query_then_insert_update_and_delete_1 using var context = new BlogsContext(); - var blog = context.Blogs.Include(e => e.Posts).First(e => e.Name == ".NET Blog"); + var blog = await context.Blogs.Include(e => e.Posts).FirstAsync(e => e.Name == ".NET Blog"); // Modify property values blog.Name = ".NET Blog (Updated!)"; @@ -93,16 +94,16 @@ public static void Query_then_insert_update_and_delete_1() context.ChangeTracker.DetectChanges(); Console.WriteLine(context.ChangeTracker.DebugView.LongView); - context.SaveChanges(); + await context.SaveChangesAsync(); #endregion } - public static void Inserting_new_entities_3() + public static async Task Inserting_new_entities_3() { Console.WriteLine($">>>> Sample: {nameof(Inserting_new_entities_3)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); + await Helpers.RecreateCleanDatabase(); using var context = new BlogsContext(); @@ -130,7 +131,7 @@ public static void Inserting_new_entities_3() Console.WriteLine("Before SaveChanges:"); Console.WriteLine(context.ChangeTracker.DebugView.LongView); - context.SaveChanges(); + await context.SaveChangesAsync(); Console.WriteLine("After SaveChanges:"); Console.WriteLine(context.ChangeTracker.DebugView.LongView); @@ -138,13 +139,13 @@ public static void Inserting_new_entities_3() Console.WriteLine(); } - public static void Attaching_existing_entities_3() + public static async Task Attaching_existing_entities_3() { Console.WriteLine($">>>> Sample: {nameof(Attaching_existing_entities_3)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BlogsContext(); @@ -180,7 +181,7 @@ public static void Attaching_existing_entities_3() Console.WriteLine("Before SaveChanges:"); Console.WriteLine(context.ChangeTracker.DebugView.LongView); - context.SaveChanges(); + await context.SaveChangesAsync(); Console.WriteLine("After SaveChanges:"); Console.WriteLine(context.ChangeTracker.DebugView.LongView); @@ -188,13 +189,13 @@ public static void Attaching_existing_entities_3() Console.WriteLine(); } - public static void Updating_existing_entities_3() + public static async Task Updating_existing_entities_3() { Console.WriteLine($">>>> Sample: {nameof(Updating_existing_entities_3)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BlogsContext(); @@ -230,7 +231,7 @@ public static void Updating_existing_entities_3() Console.WriteLine("Before SaveChanges:"); Console.WriteLine(context.ChangeTracker.DebugView.LongView); - context.SaveChanges(); + await context.SaveChangesAsync(); Console.WriteLine("After SaveChanges:"); Console.WriteLine(context.ChangeTracker.DebugView.LongView); @@ -238,17 +239,17 @@ public static void Updating_existing_entities_3() Console.WriteLine(); } - public static void Custom_tracking_with_TrackGraph_1() + public static async Task Custom_tracking_with_TrackGraph_1() { Console.WriteLine($">>>> Sample: {nameof(Custom_tracking_with_TrackGraph_1)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BlogsContext(); - var blog = context.Blogs.AsNoTracking().Include(e => e.Posts).Single(e => e.Name == ".NET Blog"); + var blog = await context.Blogs.AsNoTracking().Include(e => e.Posts).SingleAsync(e => e.Name == ".NET Blog"); #region Custom_tracking_with_TrackGraph_1a blog.Posts.Add( @@ -263,13 +264,13 @@ public static void Custom_tracking_with_TrackGraph_1() toDelete.Id = -toDelete.Id; #endregion - UpdateBlog(blog); + await UpdateBlog(blog); Console.WriteLine(); } #region Custom_tracking_with_TrackGraph_1b - public static void UpdateBlog(Blog blog) + public static async Task UpdateBlog(Blog blog) { using var context = new BlogsContext(); @@ -296,22 +297,22 @@ public static void UpdateBlog(Blog blog) Console.WriteLine($"Tracking {node.Entry.Metadata.DisplayName()} with key value {keyValue} as {node.Entry.State}"); }); - context.SaveChanges(); + await context.SaveChangesAsync(); } #endregion } public static class Helpers { - public static void RecreateCleanDatabase() + public static async Task RecreateCleanDatabase() { using var context = new BlogsContext(quiet: true); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } - public static void PopulateDatabase() + public static async Task PopulateDatabase() { using var context = new BlogsContext(quiet: true); @@ -334,7 +335,7 @@ public static void PopulateDatabase() } }); - context.SaveChanges(); + await context.SaveChangesAsync(); } } @@ -381,4 +382,4 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) optionsBuilder.LogTo(Console.WriteLine, new[] { RelationalEventId.CommandExecuted }); } } -} \ No newline at end of file +} diff --git a/samples/core/ChangeTracking/ChangeTrackingInEFCore/Program.cs b/samples/core/ChangeTracking/ChangeTrackingInEFCore/Program.cs index 4460eb108b..f705025b5a 100644 --- a/samples/core/ChangeTracking/ChangeTrackingInEFCore/Program.cs +++ b/samples/core/ChangeTracking/ChangeTrackingInEFCore/Program.cs @@ -1,37 +1,38 @@ using System; +using System.Threading.Tasks; using ExplicitKeys; using ExplicitKeysRequired; using GeneratedKeys; public class Program { - public static void Main() + public static async Task Main() { Console.WriteLine("Samples for _Change Tracking in EF Core_"); Console.WriteLine(); - GeneratedKeysSamples.Simple_query_and_update_1(); - GeneratedKeysSamples.Simple_query_and_update_2(); - GeneratedKeysSamples.Query_then_insert_update_and_delete_1(); + await GeneratedKeysSamples.Simple_query_and_update_1(); + await GeneratedKeysSamples.Simple_query_and_update_2(); + await GeneratedKeysSamples.Query_then_insert_update_and_delete_1(); - ExplicitKeysSamples.Inserting_new_entities_1(); - ExplicitKeysSamples.Inserting_new_entities_2(); - GeneratedKeysSamples.Inserting_new_entities_3(); + await ExplicitKeysSamples.Inserting_new_entities_1(); + await ExplicitKeysSamples.Inserting_new_entities_2(); + await GeneratedKeysSamples.Inserting_new_entities_3(); - ExplicitKeysSamples.Attaching_existing_entities_1(); - ExplicitKeysSamples.Attaching_existing_entities_2(); - GeneratedKeysSamples.Attaching_existing_entities_3(); + await ExplicitKeysSamples.Attaching_existing_entities_1(); + await ExplicitKeysSamples.Attaching_existing_entities_2(); + await GeneratedKeysSamples.Attaching_existing_entities_3(); - ExplicitKeysSamples.Updating_existing_entities_1(); - ExplicitKeysSamples.Updating_existing_entities_2(); - GeneratedKeysSamples.Updating_existing_entities_3(); + await ExplicitKeysSamples.Updating_existing_entities_1(); + await ExplicitKeysSamples.Updating_existing_entities_2(); + await GeneratedKeysSamples.Updating_existing_entities_3(); - ExplicitKeysSamples.Deleting_existing_entities_1(); - ExplicitKeysSamples.Deleting_dependent_child_entities_1(); - ExplicitKeysSamples.Deleting_dependent_child_entities_2(); - ExplicitKeysSamples.Deleting_principal_parent_entities_1(); - ExplicitKeysRequiredSamples.Deleting_principal_parent_entities_1(); + await ExplicitKeysSamples.Deleting_existing_entities_1(); + await ExplicitKeysSamples.Deleting_dependent_child_entities_1(); + await ExplicitKeysSamples.Deleting_dependent_child_entities_2(); + await ExplicitKeysSamples.Deleting_principal_parent_entities_1(); + await ExplicitKeysRequiredSamples.Deleting_principal_parent_entities_1(); - GeneratedKeysSamples.Custom_tracking_with_TrackGraph_1(); + await GeneratedKeysSamples.Custom_tracking_with_TrackGraph_1(); } } diff --git a/samples/core/ChangeTracking/ChangingFKsAndNavigations/ExplicitJoinEntityAndSkipsSamples.cs b/samples/core/ChangeTracking/ChangingFKsAndNavigations/ExplicitJoinEntityAndSkipsSamples.cs index e8649f301b..0d34d390bc 100644 --- a/samples/core/ChangeTracking/ChangingFKsAndNavigations/ExplicitJoinEntityAndSkipsSamples.cs +++ b/samples/core/ChangeTracking/ChangingFKsAndNavigations/ExplicitJoinEntityAndSkipsSamples.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; @@ -8,19 +9,19 @@ namespace JoinEntityWithSkips; public class ExplicitJoinEntityWithSkipsSamples { - public static void Many_to_many_relationships_3() + public static async Task Many_to_many_relationships_3() { Console.WriteLine($">>>> Sample: {nameof(Many_to_many_relationships_3)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); #region Many_to_many_relationships_3 using var context = new BlogsContext(); - var post = context.Posts.Single(e => e.Id == 3); - var tag = context.Tags.Single(e => e.Id == 1); + var post = await context.Posts.SingleAsync(e => e.Id == 3); + var tag = await context.Tags.SingleAsync(e => e.Id == 1); post.Tags.Add(tag); @@ -31,18 +32,18 @@ public static void Many_to_many_relationships_3() Console.WriteLine(); } - public static void Many_to_many_relationships_4() + public static async Task Many_to_many_relationships_4() { Console.WriteLine($">>>> Sample: {nameof(Many_to_many_relationships_4)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BlogsContext(); - var post = context.Posts.Single(e => e.Id == 3); - var tag = context.Tags.Single(e => e.Id == 1); + var post = await context.Posts.SingleAsync(e => e.Id == 3); + var tag = await context.Tags.SingleAsync(e => e.Id == 1); #region Many_to_many_relationships_4 context.Add(new PostTag { Post = post, Tag = tag }); @@ -54,18 +55,18 @@ public static void Many_to_many_relationships_4() Console.WriteLine(); } - public static void Many_to_many_relationships_5() + public static async Task Many_to_many_relationships_5() { Console.WriteLine($">>>> Sample: {nameof(Many_to_many_relationships_5)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BlogsContext(); - var post = context.Posts.Single(e => e.Id == 3); - var tag = context.Tags.Single(e => e.Id == 1); + var post = await context.Posts.SingleAsync(e => e.Id == 3); + var tag = await context.Tags.SingleAsync(e => e.Id == 1); #region Many_to_many_relationships_5 context.Add(new PostTag { PostId = post.Id, TagId = tag.Id }); @@ -80,15 +81,15 @@ public static void Many_to_many_relationships_5() public static class Helpers { - public static void RecreateCleanDatabase() + public static async Task RecreateCleanDatabase() { using var context = new BlogsContext(quiet: true); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } - public static void PopulateDatabase() + public static async Task PopulateDatabase() { using var context = new BlogsContext(quiet: true); @@ -132,7 +133,7 @@ public static void PopulateDatabase() new Tag { Text = "Visual Studio" }, new Tag { Text = "EF Core" }); - context.SaveChanges(); + await context.SaveChangesAsync(); } } @@ -213,4 +214,4 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) j => j.HasOne(t => t.Post).WithMany(p => p.PostTags)); } #endregion -} \ No newline at end of file +} diff --git a/samples/core/ChangeTracking/ChangingFKsAndNavigations/ExplicitJoinEntitySamples.cs b/samples/core/ChangeTracking/ChangingFKsAndNavigations/ExplicitJoinEntitySamples.cs index c7e0b748a4..ea86b10a85 100644 --- a/samples/core/ChangeTracking/ChangingFKsAndNavigations/ExplicitJoinEntitySamples.cs +++ b/samples/core/ChangeTracking/ChangingFKsAndNavigations/ExplicitJoinEntitySamples.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; @@ -8,42 +9,42 @@ namespace JoinEntity; public class ExplicitJoinEntitySamples { - public static void Many_to_many_relationships_1() + public static async Task Many_to_many_relationships_1() { Console.WriteLine($">>>> Sample: {nameof(Many_to_many_relationships_1)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); #region Many_to_many_relationships_1 using var context = new BlogsContext(); - var post = context.Posts.Single(e => e.Id == 3); - var tag = context.Tags.Single(e => e.Id == 1); + var post = await context.Posts.SingleAsync(e => e.Id == 3); + var tag = await context.Tags.SingleAsync(e => e.Id == 1); context.Add(new PostTag { PostId = post.Id, TagId = tag.Id }); Console.WriteLine(context.ChangeTracker.DebugView.LongView); #endregion - context.SaveChanges(); + await context.SaveChangesAsync(); Console.WriteLine(); } - public static void Many_to_many_relationships_2() + public static async Task Many_to_many_relationships_2() { Console.WriteLine($">>>> Sample: {nameof(Many_to_many_relationships_2)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BlogsContext(); - var post = context.Posts.Single(e => e.Id == 3); - var tag = context.Tags.Single(e => e.Id == 1); + var post = await context.Posts.SingleAsync(e => e.Id == 3); + var tag = await context.Tags.SingleAsync(e => e.Id == 1); #region Many_to_many_relationships_2 context.Add(new PostTag { Post = post, Tag = tag }); @@ -51,7 +52,7 @@ public static void Many_to_many_relationships_2() Console.WriteLine(context.ChangeTracker.DebugView.LongView); - context.SaveChanges(); + await context.SaveChangesAsync(); Console.WriteLine(); } @@ -59,15 +60,15 @@ public static void Many_to_many_relationships_2() public static class Helpers { - public static void RecreateCleanDatabase() + public static async Task RecreateCleanDatabase() { using var context = new BlogsContext(quiet: true); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } - public static void PopulateDatabase() + public static async Task PopulateDatabase() { using var context = new BlogsContext(quiet: true); @@ -111,7 +112,7 @@ public static void PopulateDatabase() new Tag { Text = "Visual Studio" }, new Tag { Text = "EF Core" }); - context.SaveChanges(); + await context.SaveChangesAsync(); } } @@ -183,4 +184,4 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity().HasKey(e => new { e.PostId, e.TagId }); } -} \ No newline at end of file +} diff --git a/samples/core/ChangeTracking/ChangingFKsAndNavigations/ExplicitJoinEntityWithPayloadSamples.cs b/samples/core/ChangeTracking/ChangingFKsAndNavigations/ExplicitJoinEntityWithPayloadSamples.cs index acbabe54ad..36091c738f 100644 --- a/samples/core/ChangeTracking/ChangingFKsAndNavigations/ExplicitJoinEntityWithPayloadSamples.cs +++ b/samples/core/ChangeTracking/ChangingFKsAndNavigations/ExplicitJoinEntityWithPayloadSamples.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; @@ -8,23 +9,23 @@ namespace JoinEntityWithPayload; public class ExplicitJoinEntityWithPayloadSamples { - public static void Many_to_many_relationships_7() + public static async Task Many_to_many_relationships_7() { Console.WriteLine($">>>> Sample: {nameof(Many_to_many_relationships_7)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); #region Many_to_many_relationships_7 using var context = new BlogsContext(); - var post = context.Posts.Single(e => e.Id == 3); - var tag = context.Tags.Single(e => e.Id == 1); + var post = await context.Posts.SingleAsync(e => e.Id == 3); + var tag = await context.Tags.SingleAsync(e => e.Id == 1); post.Tags.Add(tag); - context.SaveChanges(); + await context.SaveChangesAsync(); Console.WriteLine(context.ChangeTracker.DebugView.LongView); #endregion @@ -35,15 +36,15 @@ public static void Many_to_many_relationships_7() public static class Helpers { - public static void RecreateCleanDatabase() + public static async Task RecreateCleanDatabase() { using var context = new BlogsContext(quiet: true); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } - public static void PopulateDatabase() + public static async Task PopulateDatabase() { using var context = new BlogsContext(quiet: true); @@ -87,7 +88,7 @@ public static void PopulateDatabase() new Tag { Text = "Visual Studio" }, new Tag { Text = "EF Core" }); - context.SaveChanges(); + await context.SaveChangesAsync(); } } @@ -166,4 +167,4 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) j => j.Property(e => e.TaggedOn).HasDefaultValueSql("CURRENT_TIMESTAMP")); } #endregion -} \ No newline at end of file +} diff --git a/samples/core/ChangeTracking/ChangingFKsAndNavigations/ExplicitJoinEntityWithStringPayloadSamples.cs b/samples/core/ChangeTracking/ChangingFKsAndNavigations/ExplicitJoinEntityWithStringPayloadSamples.cs index d635724cd5..ac0d22f45e 100644 --- a/samples/core/ChangeTracking/ChangingFKsAndNavigations/ExplicitJoinEntityWithStringPayloadSamples.cs +++ b/samples/core/ChangeTracking/ChangingFKsAndNavigations/ExplicitJoinEntityWithStringPayloadSamples.cs @@ -1,6 +1,8 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; @@ -8,29 +10,29 @@ namespace JoinEntityWithStringPayload; public class ExplicitJoinEntityWithStringPayloadSamples { - public static void Many_to_many_relationships_8() + public static async Task Many_to_many_relationships_8() { Console.WriteLine($">>>> Sample: {nameof(Many_to_many_relationships_8)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); #region Many_to_many_relationships_8 using var context = new BlogsContext(); - var post = context.Posts.Single(e => e.Id == 3); - var tag = context.Tags.Single(e => e.Id == 1); + var post = await context.Posts.SingleAsync(e => e.Id == 3); + var tag = await context.Tags.SingleAsync(e => e.Id == 1); post.Tags.Add(tag); context.ChangeTracker.DetectChanges(); - var joinEntity = context.Set().Find(post.Id, tag.Id); + var joinEntity = await context.Set().FindAsync(post.Id, tag.Id); joinEntity.TaggedBy = "ajcvickers"; - context.SaveChanges(); + await context.SaveChangesAsync(); Console.WriteLine(context.ChangeTracker.DebugView.LongView); #endregion @@ -38,24 +40,24 @@ public static void Many_to_many_relationships_8() Console.WriteLine(); } - public static void Many_to_many_relationships_9() + public static async Task Many_to_many_relationships_9() { Console.WriteLine($">>>> Sample: {nameof(Many_to_many_relationships_9)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); #region Many_to_many_relationships_9 using var context = new BlogsContext(); - var post = context.Posts.Single(e => e.Id == 3); - var tag = context.Tags.Single(e => e.Id == 1); + var post = context.Posts.SingleAsync(e => e.Id == 3); + var tag = context.Tags.SingleAsync(e => e.Id == 1); context.Add( new PostTag { PostId = post.Id, TagId = tag.Id, TaggedBy = "ajcvickers" }); - context.SaveChanges(); + await context.SaveChangesAsync(); Console.WriteLine(context.ChangeTracker.DebugView.LongView); #endregion @@ -66,15 +68,15 @@ public static void Many_to_many_relationships_9() public static class Helpers { - public static void RecreateCleanDatabase() + public static async Task RecreateCleanDatabase() { using var context = new BlogsContext(quiet: true); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } - public static void PopulateDatabase() + public static async Task PopulateDatabase() { using var context = new BlogsContext(quiet: true); @@ -118,7 +120,7 @@ public static void PopulateDatabase() new Tag { Text = "Visual Studio" }, new Tag { Text = "EF Core" }); - context.SaveChanges(); + await context.SaveChangesAsync(); } } @@ -200,7 +202,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) #endregion #region SaveChanges - public override int SaveChanges() + public override async Task SaveChangesAsync(CancellationToken cancellationToken = default) { foreach (var entityEntry in ChangeTracker.Entries()) { @@ -210,7 +212,7 @@ public override int SaveChanges() } } - return base.SaveChanges(); + return await base.SaveChangesAsync(cancellationToken); } #endregion -} \ No newline at end of file +} diff --git a/samples/core/ChangeTracking/ChangingFKsAndNavigations/OptionalRelationshipsSamples.cs b/samples/core/ChangeTracking/ChangingFKsAndNavigations/OptionalRelationshipsSamples.cs index 94423838c6..39fa02741e 100644 --- a/samples/core/ChangeTracking/ChangingFKsAndNavigations/OptionalRelationshipsSamples.cs +++ b/samples/core/ChangeTracking/ChangingFKsAndNavigations/OptionalRelationshipsSamples.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; @@ -8,21 +9,21 @@ namespace Optional; public class OptionalRelationshipsSamples { - public static void Relationship_fixup_1() + public static async Task Relationship_fixup_1() { Console.WriteLine($">>>> Sample: {nameof(Relationship_fixup_1)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); #region Relationship_fixup_1 using var context = new BlogsContext(); - var blogs = context.Blogs + var blogs = await context.Blogs .Include(e => e.Posts) .Include(e => e.Assets) - .ToList(); + .ToListAsync(); Console.WriteLine(context.ChangeTracker.DebugView.LongView); #endregion @@ -30,43 +31,43 @@ public static void Relationship_fixup_1() Console.WriteLine(); } - public static void Relationship_fixup_2() + public static async Task Relationship_fixup_2() { Console.WriteLine($">>>> Sample: {nameof(Relationship_fixup_2)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); #region Relationship_fixup_2 using var context = new BlogsContext(); - var blogs = context.Blogs.ToList(); + var blogs = await context.Blogs.ToListAsync(); Console.WriteLine(context.ChangeTracker.DebugView.LongView); - var assets = context.Assets.ToList(); + var assets = await context.Assets.ToListAsync(); Console.WriteLine(context.ChangeTracker.DebugView.LongView); - var posts = context.Posts.ToList(); + var posts = await context.Posts.ToListAsync(); Console.WriteLine(context.ChangeTracker.DebugView.LongView); #endregion Console.WriteLine(); } - public static void Changing_relationships_using_navigations_1() + public static async Task Changing_relationships_using_navigations_1() { Console.WriteLine($">>>> Sample: {nameof(Changing_relationships_using_navigations_1)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); #region Changing_relationships_using_navigations_1 using var context = new BlogsContext(); - var dotNetBlog = context.Blogs.Include(e => e.Posts).Single(e => e.Name == ".NET Blog"); - var vsBlog = context.Blogs.Include(e => e.Posts).Single(e => e.Name == "Visual Studio Blog"); + var dotNetBlog = await context.Blogs.Include(e => e.Posts).SingleAsync(e => e.Name == ".NET Blog"); + var vsBlog = await context.Blogs.Include(e => e.Posts).SingleAsync(e => e.Name == "Visual Studio Blog"); Console.WriteLine(context.ChangeTracker.DebugView.LongView); @@ -77,24 +78,24 @@ public static void Changing_relationships_using_navigations_1() context.ChangeTracker.DetectChanges(); Console.WriteLine(context.ChangeTracker.DebugView.LongView); - context.SaveChanges(); + await context.SaveChangesAsync(); #endregion Console.WriteLine(); } - public static void Changing_relationships_using_navigations_2() + public static async Task Changing_relationships_using_navigations_2() { Console.WriteLine($">>>> Sample: {nameof(Changing_relationships_using_navigations_2)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BlogsContext(); - var dotNetBlog = context.Blogs.Include(e => e.Posts).Single(e => e.Name == ".NET Blog"); - var vsBlog = context.Blogs.Include(e => e.Posts).Single(e => e.Name == "Visual Studio Blog"); + var dotNetBlog = await context.Blogs.Include(e => e.Posts).SingleAsync(e => e.Name == ".NET Blog"); + var vsBlog = await context.Blogs.Include(e => e.Posts).SingleAsync(e => e.Name == "Visual Studio Blog"); Console.WriteLine(context.ChangeTracker.DebugView.LongView); @@ -106,23 +107,23 @@ public static void Changing_relationships_using_navigations_2() context.ChangeTracker.DetectChanges(); Console.WriteLine(context.ChangeTracker.DebugView.LongView); - context.SaveChanges(); + await context.SaveChangesAsync(); Console.WriteLine(); } - public static void Changing_relationships_using_foreign_key_values_1() + public static async Task Changing_relationships_using_foreign_key_values_1() { Console.WriteLine($">>>> Sample: {nameof(Changing_relationships_using_foreign_key_values_1)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BlogsContext(); - var dotNetBlog = context.Blogs.Include(e => e.Posts).Single(e => e.Name == ".NET Blog"); - var vsBlog = context.Blogs.Include(e => e.Posts).Single(e => e.Name == "Visual Studio Blog"); + var dotNetBlog = await context.Blogs.Include(e => e.Posts).SingleAsync(e => e.Name == ".NET Blog"); + var vsBlog = await context.Blogs.Include(e => e.Posts).SingleAsync(e => e.Name == "Visual Studio Blog"); Console.WriteLine(context.ChangeTracker.DebugView.LongView); @@ -134,23 +135,23 @@ public static void Changing_relationships_using_foreign_key_values_1() context.ChangeTracker.DetectChanges(); Console.WriteLine(context.ChangeTracker.DebugView.LongView); - context.SaveChanges(); + await context.SaveChangesAsync(); Console.WriteLine(); } - public static void Fixup_for_added_or_deleted_entities_1() + public static async Task Fixup_for_added_or_deleted_entities_1() { Console.WriteLine($">>>> Sample: {nameof(Fixup_for_added_or_deleted_entities_1)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BlogsContext(); - var dotNetBlog = context.Blogs.Include(e => e.Posts).Single(e => e.Name == ".NET Blog"); - var vsBlog = context.Blogs.Include(e => e.Posts).Single(e => e.Name == "Visual Studio Blog"); + var dotNetBlog = await context.Blogs.Include(e => e.Posts).SingleAsync(e => e.Name == ".NET Blog"); + var vsBlog = await context.Blogs.Include(e => e.Posts).SingleAsync(e => e.Name == "Visual Studio Blog"); Console.WriteLine(context.ChangeTracker.DebugView.LongView); @@ -163,23 +164,23 @@ public static void Fixup_for_added_or_deleted_entities_1() context.ChangeTracker.DetectChanges(); Console.WriteLine(context.ChangeTracker.DebugView.LongView); - context.SaveChanges(); + await context.SaveChangesAsync(); Console.WriteLine(); } - public static void Fixup_for_added_or_deleted_entities_2() + public static async Task Fixup_for_added_or_deleted_entities_2() { Console.WriteLine($">>>> Sample: {nameof(Fixup_for_added_or_deleted_entities_2)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BlogsContext(); - var dotNetBlog = context.Blogs.Include(e => e.Posts).Single(e => e.Name == ".NET Blog"); - var vsBlog = context.Blogs.Include(e => e.Posts).Single(e => e.Name == "Visual Studio Blog"); + var dotNetBlog = await context.Blogs.Include(e => e.Posts).SingleAsync(e => e.Name == ".NET Blog"); + var vsBlog = await context.Blogs.Include(e => e.Posts).SingleAsync(e => e.Name == "Visual Studio Blog"); Console.WriteLine(context.ChangeTracker.DebugView.LongView); @@ -191,22 +192,22 @@ public static void Fixup_for_added_or_deleted_entities_2() context.ChangeTracker.DetectChanges(); Console.WriteLine(context.ChangeTracker.DebugView.LongView); - context.SaveChanges(); + await context.SaveChangesAsync(); Console.WriteLine(); } - public static void Fixup_for_added_or_deleted_entities_3() + public static async Task Fixup_for_added_or_deleted_entities_3() { Console.WriteLine($">>>> Sample: {nameof(Fixup_for_added_or_deleted_entities_3)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BlogsContext(); - var dotNetBlog = context.Blogs.Include(e => e.Posts).Single(e => e.Name == ".NET Blog"); + var dotNetBlog = await context.Blogs.Include(e => e.Posts).SingleAsync(e => e.Name == ".NET Blog"); Console.WriteLine(context.ChangeTracker.DebugView.LongView); @@ -218,73 +219,73 @@ public static void Fixup_for_added_or_deleted_entities_3() context.ChangeTracker.DetectChanges(); Console.WriteLine(context.ChangeTracker.DebugView.LongView); - context.SaveChanges(); + await context.SaveChangesAsync(); Console.WriteLine(); } - public static void Fixup_for_added_or_deleted_entities_7() + public static async Task Fixup_for_added_or_deleted_entities_7() { Console.WriteLine($">>>> Sample: {nameof(Fixup_for_added_or_deleted_entities_7)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); #region Fixup_for_added_or_deleted_entities_7 using var context = new BlogsContext(); - var dotNetBlog = context.Blogs.Include(e => e.Assets).Single(e => e.Name == ".NET Blog"); + var dotNetBlog = await context.Blogs.Include(e => e.Assets).SingleAsync(e => e.Name == ".NET Blog"); dotNetBlog.Assets = new BlogAssets(); context.ChangeTracker.DetectChanges(); Console.WriteLine(context.ChangeTracker.DebugView.LongView); - context.SaveChanges(); + await context.SaveChangesAsync(); #endregion Console.WriteLine(); } - public static void Deleting_an_entity_1() + public static async Task Deleting_an_entity_1() { Console.WriteLine($">>>> Sample: {nameof(Deleting_an_entity_1)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); #region Deleting_an_entity_1 using var context = new BlogsContext(); - var vsBlog = context.Blogs + var vsBlog = await context.Blogs .Include(e => e.Posts) .Include(e => e.Assets) - .Single(e => e.Name == "Visual Studio Blog"); + .SingleAsync(e => e.Name == "Visual Studio Blog"); context.Remove(vsBlog); Console.WriteLine(context.ChangeTracker.DebugView.LongView); - context.SaveChanges(); + await context.SaveChangesAsync(); #endregion Console.WriteLine(); } - public static void Many_to_many_relationships_6() + public static async Task Many_to_many_relationships_6() { Console.WriteLine($">>>> Sample: {nameof(Many_to_many_relationships_6)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); #region Many_to_many_relationships_6 using var context = new BlogsContext(); - var post = context.Posts.Single(e => e.Id == 3); - var tag = context.Tags.Single(e => e.Id == 1); + var post = await context.Posts.SingleAsync(e => e.Id == 3); + var tag = await context.Tags.SingleAsync(e => e.Id == 1); post.Tags.Add(tag); @@ -298,15 +299,15 @@ public static void Many_to_many_relationships_6() public static class Helpers { - public static void RecreateCleanDatabase() + public static async Task RecreateCleanDatabase() { using var context = new BlogsContext(quiet: true); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } - public static void PopulateDatabase() + public static async Task PopulateDatabase() { using var context = new BlogsContext(quiet: true); @@ -352,7 +353,7 @@ public static void PopulateDatabase() new Tag { Text = "Visual Studio" }, new Tag { Text = "EF Core" }); - context.SaveChanges(); + await context.SaveChangesAsync(); } } @@ -425,4 +426,4 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) protected override void OnModelCreating(ModelBuilder modelBuilder) { } -} \ No newline at end of file +} diff --git a/samples/core/ChangeTracking/ChangingFKsAndNavigations/Program.cs b/samples/core/ChangeTracking/ChangingFKsAndNavigations/Program.cs index 2abbf78996..3974e2c204 100644 --- a/samples/core/ChangeTracking/ChangingFKsAndNavigations/Program.cs +++ b/samples/core/ChangeTracking/ChangingFKsAndNavigations/Program.cs @@ -1,4 +1,5 @@ using System; +using System.Threading.Tasks; using JoinEntity; using JoinEntityWithPayload; using JoinEntityWithSkips; @@ -8,39 +9,39 @@ public class Program { - public static void Main() + public static async Task Main() { Console.WriteLine("Samples for _Changing Foreign Keys and Navigations_"); Console.WriteLine(); - OptionalRelationshipsSamples.Relationship_fixup_1(); - OptionalRelationshipsSamples.Relationship_fixup_2(); + await OptionalRelationshipsSamples.Relationship_fixup_1(); + await OptionalRelationshipsSamples.Relationship_fixup_2(); - OptionalRelationshipsSamples.Changing_relationships_using_navigations_1(); - OptionalRelationshipsSamples.Changing_relationships_using_navigations_2(); + await OptionalRelationshipsSamples.Changing_relationships_using_navigations_1(); + await OptionalRelationshipsSamples.Changing_relationships_using_navigations_2(); - OptionalRelationshipsSamples.Changing_relationships_using_foreign_key_values_1(); + await OptionalRelationshipsSamples.Changing_relationships_using_foreign_key_values_1(); - OptionalRelationshipsSamples.Fixup_for_added_or_deleted_entities_1(); - OptionalRelationshipsSamples.Fixup_for_added_or_deleted_entities_2(); - OptionalRelationshipsSamples.Fixup_for_added_or_deleted_entities_3(); - RequiredRelationshipsSamples.Fixup_for_added_or_deleted_entities_4(); - RequiredRelationshipsSamples.Fixup_for_added_or_deleted_entities_5(); - RequiredRelationshipsSamples.Fixup_for_added_or_deleted_entities_6(); - OptionalRelationshipsSamples.Fixup_for_added_or_deleted_entities_7(); - RequiredRelationshipsSamples.Fixup_for_added_or_deleted_entities_8(); + await OptionalRelationshipsSamples.Fixup_for_added_or_deleted_entities_1(); + await OptionalRelationshipsSamples.Fixup_for_added_or_deleted_entities_2(); + await OptionalRelationshipsSamples.Fixup_for_added_or_deleted_entities_3(); + await RequiredRelationshipsSamples.Fixup_for_added_or_deleted_entities_4(); + await RequiredRelationshipsSamples.Fixup_for_added_or_deleted_entities_5(); + await RequiredRelationshipsSamples.Fixup_for_added_or_deleted_entities_6(); + await OptionalRelationshipsSamples.Fixup_for_added_or_deleted_entities_7(); + await RequiredRelationshipsSamples.Fixup_for_added_or_deleted_entities_8(); - OptionalRelationshipsSamples.Deleting_an_entity_1(); - RequiredRelationshipsSamples.Deleting_an_entity_2(); + await OptionalRelationshipsSamples.Deleting_an_entity_1(); + await RequiredRelationshipsSamples.Deleting_an_entity_2(); - ExplicitJoinEntitySamples.Many_to_many_relationships_1(); - ExplicitJoinEntitySamples.Many_to_many_relationships_2(); - ExplicitJoinEntityWithSkipsSamples.Many_to_many_relationships_3(); - ExplicitJoinEntityWithSkipsSamples.Many_to_many_relationships_4(); - ExplicitJoinEntityWithSkipsSamples.Many_to_many_relationships_5(); - OptionalRelationshipsSamples.Many_to_many_relationships_6(); - ExplicitJoinEntityWithPayloadSamples.Many_to_many_relationships_7(); - ExplicitJoinEntityWithStringPayloadSamples.Many_to_many_relationships_8(); - ExplicitJoinEntityWithStringPayloadSamples.Many_to_many_relationships_9(); + await ExplicitJoinEntitySamples.Many_to_many_relationships_1(); + await ExplicitJoinEntitySamples.Many_to_many_relationships_2(); + await ExplicitJoinEntityWithSkipsSamples.Many_to_many_relationships_3(); + await ExplicitJoinEntityWithSkipsSamples.Many_to_many_relationships_4(); + await ExplicitJoinEntityWithSkipsSamples.Many_to_many_relationships_5(); + await OptionalRelationshipsSamples.Many_to_many_relationships_6(); + await ExplicitJoinEntityWithPayloadSamples.Many_to_many_relationships_7(); + await ExplicitJoinEntityWithStringPayloadSamples.Many_to_many_relationships_8(); + await ExplicitJoinEntityWithStringPayloadSamples.Many_to_many_relationships_9(); } } diff --git a/samples/core/ChangeTracking/ChangingFKsAndNavigations/RequiredRelationshipsSamples.cs b/samples/core/ChangeTracking/ChangingFKsAndNavigations/RequiredRelationshipsSamples.cs index 66120dac59..37f9c86ffb 100644 --- a/samples/core/ChangeTracking/ChangingFKsAndNavigations/RequiredRelationshipsSamples.cs +++ b/samples/core/ChangeTracking/ChangingFKsAndNavigations/RequiredRelationshipsSamples.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Diagnostics; @@ -9,17 +10,17 @@ namespace Required; public class RequiredRelationshipsSamples { - public static void Fixup_for_added_or_deleted_entities_4() + public static async Task Fixup_for_added_or_deleted_entities_4() { Console.WriteLine($">>>> Sample: {nameof(Fixup_for_added_or_deleted_entities_4)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BlogsContext(); - var dotNetBlog = context.Blogs.Include(e => e.Posts).Single(e => e.Name == ".NET Blog"); + var dotNetBlog = await context.Blogs.Include(e => e.Posts).SingleAsync(e => e.Name == ".NET Blog"); Console.WriteLine(context.ChangeTracker.DebugView.LongView); @@ -31,23 +32,23 @@ public static void Fixup_for_added_or_deleted_entities_4() context.ChangeTracker.DetectChanges(); Console.WriteLine(context.ChangeTracker.DebugView.LongView); - context.SaveChanges(); + await context.SaveChangesAsync(); Console.WriteLine(); } - public static void Fixup_for_added_or_deleted_entities_5() + public static async Task Fixup_for_added_or_deleted_entities_5() { Console.WriteLine($">>>> Sample: {nameof(Fixup_for_added_or_deleted_entities_5)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BlogsContext(); - var dotNetBlog = context.Blogs.Include(e => e.Posts).Single(e => e.Name == ".NET Blog"); - var vsBlog = context.Blogs.Include(e => e.Posts).Single(e => e.Name == "Visual Studio Blog"); + var dotNetBlog = await context.Blogs.Include(e => e.Posts).SingleAsync(e => e.Name == ".NET Blog"); + var vsBlog = await context.Blogs.Include(e => e.Posts).SingleAsync(e => e.Name == "Visual Studio Blog"); #region Fixup_for_added_or_deleted_entities_5 context.ChangeTracker.DeleteOrphansTiming = CascadeTiming.OnSaveChanges; @@ -63,33 +64,33 @@ public static void Fixup_for_added_or_deleted_entities_5() context.ChangeTracker.DetectChanges(); Console.WriteLine(context.ChangeTracker.DebugView.LongView); - context.SaveChanges(); + await context.SaveChangesAsync(); #endregion Console.WriteLine(); } - public static void Fixup_for_added_or_deleted_entities_6() + public static async Task Fixup_for_added_or_deleted_entities_6() { Console.WriteLine($">>>> Sample: {nameof(Fixup_for_added_or_deleted_entities_6)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BlogsContext(); try { #region Fixup_for_added_or_deleted_entities_6 - var dotNetBlog = context.Blogs.Include(e => e.Posts).Single(e => e.Name == ".NET Blog"); + var dotNetBlog = await context.Blogs.Include(e => e.Posts).SingleAsync(e => e.Name == ".NET Blog"); context.ChangeTracker.DeleteOrphansTiming = CascadeTiming.Never; var post = dotNetBlog.Posts.Single(e => e.Title == "Announcing F# 5"); dotNetBlog.Posts.Remove(post); - context.SaveChanges(); // Throws + await context.SaveChangesAsync(); // Throws #endregion } catch (Exception e) @@ -100,50 +101,50 @@ public static void Fixup_for_added_or_deleted_entities_6() Console.WriteLine(); } - public static void Fixup_for_added_or_deleted_entities_8() + public static async Task Fixup_for_added_or_deleted_entities_8() { Console.WriteLine($">>>> Sample: {nameof(Fixup_for_added_or_deleted_entities_8)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); #region Fixup_for_added_or_deleted_entities_8 using var context = new BlogsContext(); - var dotNetBlog = context.Blogs.Include(e => e.Assets).Single(e => e.Name == ".NET Blog"); + var dotNetBlog = await context.Blogs.Include(e => e.Assets).SingleAsync(e => e.Name == ".NET Blog"); dotNetBlog.Assets = new BlogAssets(); context.ChangeTracker.DetectChanges(); Console.WriteLine(context.ChangeTracker.DebugView.LongView); - context.SaveChanges(); + await context.SaveChangesAsync(); #endregion Console.WriteLine(); } - public static void Deleting_an_entity_2() + public static async Task Deleting_an_entity_2() { Console.WriteLine($">>>> Sample: {nameof(Deleting_an_entity_2)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); #region Deleting_an_entity_2 using var context = new BlogsContext(); - var vsBlog = context.Blogs + var vsBlog = await context.Blogs .Include(e => e.Posts) .Include(e => e.Assets) - .Single(e => e.Name == "Visual Studio Blog"); + .SingleAsync(e => e.Name == "Visual Studio Blog"); context.Remove(vsBlog); Console.WriteLine(context.ChangeTracker.DebugView.LongView); - context.SaveChanges(); + await context.SaveChangesAsync(); #endregion Console.WriteLine(); @@ -152,15 +153,15 @@ public static void Deleting_an_entity_2() public static class Helpers { - public static void RecreateCleanDatabase() + public static async Task RecreateCleanDatabase() { using var context = new BlogsContext(quiet: true); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } - public static void PopulateDatabase() + public static async Task PopulateDatabase() { using var context = new BlogsContext(quiet: true); @@ -206,7 +207,7 @@ public static void PopulateDatabase() new Tag { Text = "Visual Studio" }, new Tag { Text = "EF Core" }); - context.SaveChanges(); + await context.SaveChangesAsync(); } } @@ -279,4 +280,4 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) protected override void OnModelCreating(ModelBuilder modelBuilder) { } -} \ No newline at end of file +} diff --git a/samples/core/ChangeTracking/IdentityResolutionInEFCore/IdentityResolutionSamples.cs b/samples/core/ChangeTracking/IdentityResolutionInEFCore/IdentityResolutionSamples.cs index 284f21a328..2d4a85a7c3 100644 --- a/samples/core/ChangeTracking/IdentityResolutionInEFCore/IdentityResolutionSamples.cs +++ b/samples/core/ChangeTracking/IdentityResolutionInEFCore/IdentityResolutionSamples.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; @@ -9,18 +10,18 @@ namespace Updates; public static class IdentityResolutionSamples { - public static void Identity_Resolution_in_EF_Core_1() + public static async Task Identity_Resolution_in_EF_Core_1() { Console.WriteLine($">>>> Sample: {nameof(Identity_Resolution_in_EF_Core_1)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); #region Identity_Resolution_in_EF_Core_1 using var context = new BlogsContext(); - var blogA = context.Blogs.Single(e => e.Id == 1); + var blogA = await context.Blogs.SingleAsync(e => e.Id == 1); var blogB = new Blog { Id = 1, Name = ".NET Blog (All new!)" }; try @@ -36,149 +37,149 @@ public static void Identity_Resolution_in_EF_Core_1() Console.WriteLine(); } - public static void Updating_an_entity_1() + public static async Task Updating_an_entity_1() { Console.WriteLine($">>>> Sample: {nameof(Updating_an_entity_1)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); - UpdateFromHttpPost1( + await UpdateFromHttpPost1( new Blog { Id = 1, Name = ".NET Blog (All new!)", Summary = "Posts about .NET" }); Console.WriteLine(); } #region Updating_an_entity_1 - public static void UpdateFromHttpPost1(Blog blog) + public static async Task UpdateFromHttpPost1(Blog blog) { using var context = new BlogsContext(); context.Update(blog); - context.SaveChanges(); + await context.SaveChangesAsync(); } #endregion - public static void Updating_an_entity_2() + public static async Task Updating_an_entity_2() { Console.WriteLine($">>>> Sample: {nameof(Updating_an_entity_2)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); - UpdateFromHttpPost2( + await UpdateFromHttpPost2( new Blog { Id = 1, Name = ".NET Blog (All new!)", Summary = "Posts about .NET" }); Console.WriteLine(); } #region Updating_an_entity_2 - public static void UpdateFromHttpPost2(Blog blog) + public static async Task UpdateFromHttpPost2(Blog blog) { using var context = new BlogsContext(); - var trackedBlog = context.Blogs.Find(blog.Id); + var trackedBlog = await context.Blogs.FindAsync(blog.Id); trackedBlog.Name = blog.Name; trackedBlog.Summary = blog.Summary; - context.SaveChanges(); + await context.SaveChangesAsync(); } #endregion - public static void Updating_an_entity_3() + public static async Task Updating_an_entity_3() { Console.WriteLine($">>>> Sample: {nameof(Updating_an_entity_3)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); - UpdateFromHttpPost3( + await UpdateFromHttpPost3( new Blog { Id = 1, Name = ".NET Blog (All new!)", Summary = "Posts about .NET" }); Console.WriteLine(); } #region Updating_an_entity_3 - public static void UpdateFromHttpPost3(Blog blog) + public static async Task UpdateFromHttpPost3(Blog blog) { using var context = new BlogsContext(); - var trackedBlog = context.Blogs.Find(blog.Id); + var trackedBlog = await context.Blogs.FindAsync(blog.Id); context.Entry(trackedBlog).CurrentValues.SetValues(blog); - context.SaveChanges(); + await context.SaveChangesAsync(); } #endregion - public static void Updating_an_entity_4() + public static async Task Updating_an_entity_4() { Console.WriteLine($">>>> Sample: {nameof(Updating_an_entity_4)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); - UpdateFromHttpPost4( + await UpdateFromHttpPost4( new BlogDto { Id = 1, Name = ".NET Blog (All new!)", Summary = "Posts about .NET" }); Console.WriteLine(); } #region Updating_an_entity_4 - public static void UpdateFromHttpPost4(BlogDto dto) + public static async Task UpdateFromHttpPost4(BlogDto dto) { using var context = new BlogsContext(); - var trackedBlog = context.Blogs.Find(dto.Id); + var trackedBlog = await context.Blogs.FindAsync(dto.Id); context.Entry(trackedBlog).CurrentValues.SetValues(dto); - context.SaveChanges(); + await context.SaveChangesAsync(); } #endregion - public static void Updating_an_entity_5() + public static async Task Updating_an_entity_5() { Console.WriteLine($">>>> Sample: {nameof(Updating_an_entity_5)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); - UpdateFromHttpPost5( + await UpdateFromHttpPost5( new Dictionary { ["Id"] = 1, ["Name"] = ".NET Blog (All new!)", ["Summary"] = "Posts about .NET" }); Console.WriteLine(); } #region Updating_an_entity_5 - public static void UpdateFromHttpPost5(Dictionary propertyValues) + public static async Task UpdateFromHttpPost5(Dictionary propertyValues) { using var context = new BlogsContext(); - var trackedBlog = context.Blogs.Find(propertyValues["Id"]); + var trackedBlog = await context.Blogs.FindAsync(propertyValues["Id"]); context.Entry(trackedBlog).CurrentValues.SetValues(propertyValues); - context.SaveChanges(); + await context.SaveChangesAsync(); } #endregion - public static void Updating_an_entity_6() + public static async Task Updating_an_entity_6() { Console.WriteLine($">>>> Sample: {nameof(Updating_an_entity_6)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); - UpdateFromHttpPost6( + await UpdateFromHttpPost6( new Blog { Id = 1, Name = ".NET Blog (All new!)", Summary = "Posts about .NET" }, new Dictionary { ["Id"] = 1, ["Name"] = ".NET Blog", ["Summary"] = "Posts about .NET" }); @@ -186,14 +187,14 @@ public static void Updating_an_entity_6() } #region Updating_an_entity_6 - public static void UpdateFromHttpPost6(Blog blog, Dictionary originalValues) + public static async Task UpdateFromHttpPost6(Blog blog, Dictionary originalValues) { using var context = new BlogsContext(); context.Attach(blog); context.Entry(blog).OriginalValues.SetValues(originalValues); - context.SaveChanges(); + await context.SaveChangesAsync(); } #endregion @@ -221,15 +222,15 @@ public static void Failing_to_set_key_values_1() public static class Helpers { - public static void RecreateCleanDatabase() + public static async Task RecreateCleanDatabase() { using var context = new BlogsContext(quiet: true); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } - public static void PopulateDatabase() + public static async Task PopulateDatabase() { using var context = new BlogsContext(quiet: true); @@ -252,7 +253,7 @@ public static void PopulateDatabase() } }); - context.SaveChanges(); + await context.SaveChangesAsync(); } } @@ -328,4 +329,4 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) optionsBuilder.LogTo(Console.WriteLine, new[] { RelationalEventId.CommandExecuted }); } } -} \ No newline at end of file +} diff --git a/samples/core/ChangeTracking/IdentityResolutionInEFCore/Program.cs b/samples/core/ChangeTracking/IdentityResolutionInEFCore/Program.cs index 26ca274cba..c16dc0fe9c 100644 --- a/samples/core/ChangeTracking/IdentityResolutionInEFCore/Program.cs +++ b/samples/core/ChangeTracking/IdentityResolutionInEFCore/Program.cs @@ -1,27 +1,28 @@ using System; +using System.Threading.Tasks; using Graphs; using Updates; public class Program { - public static void Main() + public static async Task Main() { Console.WriteLine("Samples for _Identity Resolution in EF Core_"); Console.WriteLine(); - IdentityResolutionSamples.Identity_Resolution_in_EF_Core_1(); - IdentityResolutionSamples.Updating_an_entity_1(); - IdentityResolutionSamples.Updating_an_entity_2(); - IdentityResolutionSamples.Updating_an_entity_3(); - IdentityResolutionSamples.Updating_an_entity_4(); - IdentityResolutionSamples.Updating_an_entity_5(); - IdentityResolutionSamples.Updating_an_entity_6(); + await IdentityResolutionSamples.Identity_Resolution_in_EF_Core_1(); + await IdentityResolutionSamples.Updating_an_entity_1(); + await IdentityResolutionSamples.Updating_an_entity_2(); + await IdentityResolutionSamples.Updating_an_entity_3(); + await IdentityResolutionSamples.Updating_an_entity_4(); + await IdentityResolutionSamples.Updating_an_entity_5(); + await IdentityResolutionSamples.Updating_an_entity_6(); - SerializedGraphExamples.Attaching_a_serialized_graph_1(); - SerializedGraphExamples.Attaching_a_serialized_graph_2(); - SerializedGraphExamples.Attaching_a_serialized_graph_3(); - SerializedGraphExamples.Attaching_a_serialized_graph_4(); - SerializedGraphExamples.Attaching_a_serialized_graph_5(); + await SerializedGraphExamples.Attaching_a_serialized_graph_1(); + await SerializedGraphExamples.Attaching_a_serialized_graph_2(); + await SerializedGraphExamples.Attaching_a_serialized_graph_3(); + await SerializedGraphExamples.Attaching_a_serialized_graph_4(); + await SerializedGraphExamples.Attaching_a_serialized_graph_5(); IdentityResolutionSamples.Failing_to_set_key_values_1(); } diff --git a/samples/core/ChangeTracking/IdentityResolutionInEFCore/SerializedGraphExamples.cs b/samples/core/ChangeTracking/IdentityResolutionInEFCore/SerializedGraphExamples.cs index 1f030a4b22..6f4c2ce39c 100644 --- a/samples/core/ChangeTracking/IdentityResolutionInEFCore/SerializedGraphExamples.cs +++ b/samples/core/ChangeTracking/IdentityResolutionInEFCore/SerializedGraphExamples.cs @@ -3,6 +3,7 @@ using System.Linq; using System.Text.Json; using System.Text.Json.Serialization; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Newtonsoft.Json; @@ -12,18 +13,18 @@ namespace Graphs; public static class SerializedGraphExamples { - public static void Attaching_a_serialized_graph_1() + public static async Task Attaching_a_serialized_graph_1() { Console.WriteLine($">>>> Sample: {nameof(Attaching_a_serialized_graph_1)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); #region Attaching_a_serialized_graph_1a using var context = new BlogsContext(); - var blogs = context.Blogs.Include(e => e.Posts).ToList(); + var blogs = await context.Blogs.Include(e => e.Posts).ToListAsync(); var serialized = JsonConvert.SerializeObject( blogs, @@ -32,11 +33,11 @@ public static void Attaching_a_serialized_graph_1() Console.WriteLine(serialized); #endregion - UpdateBlogsFromJson(serialized); + await UpdateBlogsFromJson(serialized); } #region Attaching_a_serialized_graph_1b - public static void UpdateBlogsFromJson(string json) + public static async Task UpdateBlogsFromJson(string json) { using var context = new BlogsContext(); @@ -47,22 +48,22 @@ public static void UpdateBlogsFromJson(string json) context.Update(blog); } - context.SaveChanges(); + await context.SaveChangesAsync(); } #endregion - public static void Attaching_a_serialized_graph_2() + public static async Task Attaching_a_serialized_graph_2() { Console.WriteLine($">>>> Sample: {nameof(Attaching_a_serialized_graph_2)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); #region Attaching_a_serialized_graph_2 using var context = new BlogsContext(); - var posts = context.Posts.Include(e => e.Blog).ToList(); + var posts = await context.Posts.Include(e => e.Blog).ToListAsync(); var serialized = JsonConvert.SerializeObject( posts, @@ -71,10 +72,10 @@ public static void Attaching_a_serialized_graph_2() Console.WriteLine(serialized); #endregion - UpdatePostsFromJsonBad(serialized); + await UpdatePostsFromJsonBad(serialized); } - public static void UpdatePostsFromJsonBad(string json) + public static async Task UpdatePostsFromJsonBad(string json) { using var context = new BlogsContext(); @@ -87,7 +88,7 @@ public static void UpdatePostsFromJsonBad(string json) context.Update(post); // Will throw } - context.SaveChanges(); + await context.SaveChangesAsync(); } catch (Exception e) { @@ -95,17 +96,17 @@ public static void UpdatePostsFromJsonBad(string json) } } - public static void Attaching_a_serialized_graph_3() + public static async Task Attaching_a_serialized_graph_3() { Console.WriteLine($">>>> Sample: {nameof(Attaching_a_serialized_graph_3)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BlogsContext(); - var posts = context.Posts.Include(e => e.Blog).ToList(); + var posts = await context.Posts.Include(e => e.Blog).ToListAsync(); #region Attaching_a_serialized_graph_3 var serialized = JsonConvert.SerializeObject( @@ -118,10 +119,10 @@ public static void Attaching_a_serialized_graph_3() Console.WriteLine(serialized); - UpdatePostsFromJson(serialized); + await UpdatePostsFromJson(serialized); } - public static void UpdatePostsFromJson(string json) + public static async Task UpdatePostsFromJson(string json) { using var context = new BlogsContext(); @@ -132,20 +133,20 @@ public static void UpdatePostsFromJson(string json) context.Update(post); } - context.SaveChanges(); + await context.SaveChangesAsync(); } - public static void Attaching_a_serialized_graph_4() + public static async Task Attaching_a_serialized_graph_4() { Console.WriteLine($">>>> Sample: {nameof(Attaching_a_serialized_graph_4)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BlogsContext(); - var posts = context.Posts.Include(e => e.Blog).ToList(); + var posts = await context.Posts.Include(e => e.Blog).ToListAsync(); #region Attaching_a_serialized_graph_4 var serialized = JsonSerializer.Serialize( @@ -154,20 +155,20 @@ public static void Attaching_a_serialized_graph_4() Console.WriteLine(serialized); - UpdatePostsFromJson(serialized); + await UpdatePostsFromJson(serialized); } - public static void Attaching_a_serialized_graph_5() + public static async Task Attaching_a_serialized_graph_5() { Console.WriteLine($">>>> Sample: {nameof(Attaching_a_serialized_graph_4)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BlogsContext(); - var posts = context.Posts.Include(e => e.Blog).ToList(); + var posts = await context.Posts.Include(e => e.Blog).ToListAsync(); var serialized = JsonConvert.SerializeObject( posts, @@ -175,13 +176,13 @@ public static void Attaching_a_serialized_graph_5() Console.WriteLine(serialized); - Console.WriteLine() - ; - UpdatePostsFromJsonWithIdentityResolution(serialized); + Console.WriteLine(); + + await UpdatePostsFromJsonWithIdentityResolution(serialized); } #region Attaching_a_serialized_graph_5 - public static void UpdatePostsFromJsonWithIdentityResolution(string json) + public static async Task UpdatePostsFromJsonWithIdentityResolution(string json) { using var context = new BlogsContext(); @@ -213,22 +214,22 @@ public static void UpdatePostsFromJsonWithIdentityResolution(string json) }); } - context.SaveChanges(); + await context.SaveChangesAsync(); } #endregion } public static class Helpers { - public static void RecreateCleanDatabase() + public static async Task RecreateCleanDatabase() { using var context = new BlogsContext(quiet: true); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } - public static void PopulateDatabase() + public static async Task PopulateDatabase() { using var context = new BlogsContext(quiet: true); @@ -271,7 +272,7 @@ public static void PopulateDatabase() } }); - context.SaveChanges(); + await context.SaveChangesAsync(); } } @@ -317,4 +318,4 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) optionsBuilder.LogTo(Console.WriteLine, new[] { RelationalEventId.CommandExecuted }); } } -} \ No newline at end of file +} diff --git a/samples/core/DbContextPooling/Program.cs b/samples/core/DbContextPooling/Program.cs index b46fb23195..2ddc477c2f 100644 --- a/samples/core/DbContextPooling/Program.cs +++ b/samples/core/DbContextPooling/Program.cs @@ -61,7 +61,7 @@ private static async Task Main() new Startup().ConfigureServices(serviceCollection); var serviceProvider = serviceCollection.BuildServiceProvider(); - SetupDatabase(serviceProvider); + await SetupDatabase(serviceProvider); var stopwatch = new Stopwatch(); @@ -75,16 +75,16 @@ await Task.WhenAll( await monitorTask; } - private static void SetupDatabase(IServiceProvider serviceProvider) + private static async Task SetupDatabase(IServiceProvider serviceProvider) { using var serviceScope = serviceProvider.CreateScope(); var context = serviceScope.ServiceProvider.GetService(); - if (context.Database.EnsureCreated()) + if (await context.Database.EnsureCreatedAsync()) { context.Blogs.Add(new Blog { Name = "The Dog Blog", Url = "http://sample.com/dogs" }); context.Blogs.Add(new Blog { Name = "The Cat Blog", Url = "http://sample.com/cats" }); - context.SaveChanges(); + await context.SaveChangesAsync(); } } diff --git a/samples/core/GetStarted/Program.cs b/samples/core/GetStarted/Program.cs index 9b1e5538b6..3ca7fcab95 100644 --- a/samples/core/GetStarted/Program.cs +++ b/samples/core/GetStarted/Program.cs @@ -1,5 +1,6 @@ using System; using System.Linq; +using Microsoft.EntityFrameworkCore; using var db = new BloggingContext(); @@ -9,22 +10,22 @@ // Create Console.WriteLine("Inserting a new blog"); db.Add(new Blog { Url = "http://blogs.msdn.com/adonet" }); -db.SaveChanges(); +await db.SaveChangesAsync(); // Read Console.WriteLine("Querying for a blog"); -var blog = db.Blogs +var blog = await db.Blogs .OrderBy(b => b.BlogId) - .First(); + .FirstAsync(); // Update Console.WriteLine("Updating the blog and adding a post"); blog.Url = "https://devblogs.microsoft.com/dotnet"; blog.Posts.Add( new Post { Title = "Hello World", Content = "I wrote an app using EF Core!" }); -db.SaveChanges(); +await db.SaveChangesAsync(); // Delete Console.WriteLine("Delete the blog"); db.Remove(blog); -db.SaveChanges(); \ No newline at end of file +await db.SaveChangesAsync(); diff --git a/samples/core/Intro/Program.cs b/samples/core/Intro/Program.cs index 5a6dc43e62..e4d95c825c 100644 --- a/samples/core/Intro/Program.cs +++ b/samples/core/Intro/Program.cs @@ -1,26 +1,27 @@ using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace Intro; internal class Program { - private static void Main() + private static async Task Main() { using (var db = new BloggingContext()) { // Remove these lines if you are running migrations from the command line - db.Database.EnsureDeleted(); - db.Database.Migrate(); + await db.Database.EnsureDeletedAsync(); + await db.Database.MigrateAsync(); } #region Querying using (var db = new BloggingContext()) { - var blogs = db.Blogs + var blogs = await db.Blogs .Where(b => b.Rating > 3) .OrderBy(b => b.Url) - .ToList(); + .ToListAsync(); } #endregion @@ -29,8 +30,8 @@ private static void Main() { var blog = new Blog { Url = "http://sample.com" }; db.Blogs.Add(blog); - db.SaveChanges(); + await db.SaveChangesAsync(); } #endregion } -} \ No newline at end of file +} diff --git a/samples/core/Miscellaneous/Collations/Program.cs b/samples/core/Miscellaneous/Collations/Program.cs index e045cfaf40..098f18d1d8 100644 --- a/samples/core/Miscellaneous/Collations/Program.cs +++ b/samples/core/Miscellaneous/Collations/Program.cs @@ -1,24 +1,25 @@ using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace EFCollations; public class Program { - public static void Main(string[] args) + public static async Task Main(string[] args) { using (var db = new CustomerContext()) { - db.Database.EnsureDeleted(); - db.Database.EnsureCreated(); + await db.Database.EnsureDeletedAsync(); + await db.Database.EnsureCreatedAsync(); } using (var context = new CustomerContext()) { #region SimpleQueryCollation - var customers = context.Customers + var customers = await context.Customers .Where(c => EF.Functions.Collate(c.Name, "SQL_Latin1_General_CP1_CS_AS") == "John") - .ToList(); + .ToListAsync(); #endregion } } diff --git a/samples/core/Miscellaneous/CommandInterception/Program.cs b/samples/core/Miscellaneous/CommandInterception/Program.cs index 379eb8c822..0adff74e27 100644 --- a/samples/core/Miscellaneous/CommandInterception/Program.cs +++ b/samples/core/Miscellaneous/CommandInterception/Program.cs @@ -1,28 +1,29 @@ using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; public class Program { - public static void Main() + public static async Task Main() { using (var context = new TaggedQueryCommandInterceptorContext()) { - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); context.AddRange( new Blog { Name = "Blog1" }, new Blog { Name = "Blog2" }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = new TaggedQueryCommandInterceptorContext()) { #region TaggedQuery - var blogs1 = context.Blogs.TagWith("Use hint: robust plan").ToList(); + var blogs1 = await context.Blogs.TagWith("Use hint: robust plan").ToListAsync(); #endregion - var blogs2 = context.Blogs.ToList(); + var blogs2 = await context.Blogs.ToListAsync(); } } } diff --git a/samples/core/Miscellaneous/CompiledModels/Program.cs b/samples/core/Miscellaneous/CompiledModels/Program.cs index 6f3e96d108..08a6c80975 100644 --- a/samples/core/Miscellaneous/CompiledModels/Program.cs +++ b/samples/core/Miscellaneous/CompiledModels/Program.cs @@ -1,17 +1,18 @@ using System; using System.Linq; +using System.Threading.Tasks; using BenchmarkDotNet.Running; using CompiledModelTest; public class Program { - public static void Main(string[] args) + public static async Task Main(string[] args) { - PrintSomeStuff(); + await PrintSomeStuff(); BenchmarkRunner.Run(); } - public static void PrintSomeStuff() + public static async Task PrintSomeStuff() { using var context = new BlogsContext(); var model = context.Model; @@ -21,7 +22,7 @@ public static void PrintSomeStuff() Console.WriteLine($" {model.GetEntityTypes().SelectMany(e => e.GetProperties()).Count()} properties"); Console.WriteLine($" {model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()).Count()} relationships"); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } } diff --git a/samples/core/Miscellaneous/CompiledModels/Test.cs b/samples/core/Miscellaneous/CompiledModels/Test.cs index a2ac2ba5b4..980c26c7d4 100644 --- a/samples/core/Miscellaneous/CompiledModels/Test.cs +++ b/samples/core/Miscellaneous/CompiledModels/Test.cs @@ -1,14 +1,16 @@ using System.Linq; +using System.Threading.Tasks; using BenchmarkDotNet.Attributes; using CompiledModelTest; +using Microsoft.EntityFrameworkCore; [SimpleJob(invocationCount: 1, targetCount: 50)] public class Test { [Benchmark] - public void TimeToFirstQuery() + public async Task TimeToFirstQuery() { using var context = new BlogsContext(); - var results = context.Set().ToList(); + var results = await context.Set().ToListAsync(); } } diff --git a/samples/core/Miscellaneous/ConfiguringDbContext/WithContextFactory/MyController.cs b/samples/core/Miscellaneous/ConfiguringDbContext/WithContextFactory/MyController.cs index 579091ae46..d04fd4aa9a 100644 --- a/samples/core/Miscellaneous/ConfiguringDbContext/WithContextFactory/MyController.cs +++ b/samples/core/Miscellaneous/ConfiguringDbContext/WithContextFactory/MyController.cs @@ -15,7 +15,7 @@ public MyController(IDbContextFactory contextFactory) #endregion #region DoSomething - public void DoSomething() + public async Task DoSomething() { using (var context = _contextFactory.CreateDbContext()) { @@ -23,4 +23,4 @@ public void DoSomething() } } #endregion -} \ No newline at end of file +} diff --git a/samples/core/Miscellaneous/ConnectionResiliency/Program.cs b/samples/core/Miscellaneous/ConnectionResiliency/Program.cs index 67eeb28cf5..f56f9158a5 100644 --- a/samples/core/Miscellaneous/ConnectionResiliency/Program.cs +++ b/samples/core/Miscellaneous/ConnectionResiliency/Program.cs @@ -1,5 +1,6 @@ using System; using System.Linq; +using System.Threading.Tasks; using System.Transactions; using Microsoft.EntityFrameworkCore; @@ -7,49 +8,49 @@ namespace EFConnectionResiliency; public class Program { - public static void Main(string[] args) + public static async Task Main(string[] args) { using (var db = new BloggingContext()) { - db.Database.EnsureDeleted(); - db.Database.EnsureCreated(); + await db.Database.EnsureDeletedAsync(); + await db.Database.EnsureCreatedAsync(); } - ExecuteWithManualTransaction(); + await ExecuteWithManualTransaction(); - ExecuteWithManualAmbientTransaction(); + await ExecuteWithManualAmbientTransaction(); - ExecuteInTransactionWithVerification(); + await ExecuteInTransactionWithVerification(); - ExecuteInTransactionWithTracking(); + await ExecuteInTransactionWithTracking(); } - private static void ExecuteWithManualTransaction() + private static async Task ExecuteWithManualTransaction() { #region ManualTransaction using var db = new BloggingContext(); var strategy = db.Database.CreateExecutionStrategy(); - strategy.Execute( - () => + await strategy.ExecuteAsync( + async () => { using var context = new BloggingContext(); - using var transaction = context.Database.BeginTransaction(); + await using var transaction = await context.Database.BeginTransactionAsync(); context.Blogs.Add(new Blog { Url = "http://blogs.msdn.com/dotnet" }); - context.SaveChanges(); + await context.SaveChangesAsync(); context.Blogs.Add(new Blog { Url = "http://blogs.msdn.com/visualstudio" }); - context.SaveChanges(); + await context.SaveChangesAsync(); - transaction.Commit(); + await transaction.CommitAsync(); }); #endregion } - private static void ExecuteWithManualAmbientTransaction() + private static async Task ExecuteWithManualAmbientTransaction() { #region AmbientTransaction @@ -58,16 +59,16 @@ private static void ExecuteWithManualAmbientTransaction() var strategy = context1.Database.CreateExecutionStrategy(); - strategy.Execute( - () => + await strategy.ExecuteAsync( + async () => { using var context2 = new BloggingContext(); using var transaction = new TransactionScope(); context2.Blogs.Add(new Blog { Url = "http://blogs.msdn.com/dotnet" }); - context2.SaveChanges(); + await context2.SaveChangesAsync(); - context1.SaveChanges(); + await context1.SaveChangesAsync(); transaction.Complete(); }); @@ -75,7 +76,7 @@ private static void ExecuteWithManualAmbientTransaction() #endregion } - private static void ExecuteInTransactionWithVerification() + private static async Task ExecuteInTransactionWithVerification() { #region Verification @@ -85,17 +86,17 @@ private static void ExecuteInTransactionWithVerification() var blogToAdd = new Blog { Url = "http://blogs.msdn.com/dotnet" }; db.Blogs.Add(blogToAdd); - strategy.ExecuteInTransaction( + await strategy.ExecuteInTransactionAsync( db, - operation: context => { context.SaveChanges(acceptAllChangesOnSuccess: false); }, - verifySucceeded: context => context.Blogs.AsNoTracking().Any(b => b.BlogId == blogToAdd.BlogId)); + operation: (context, cancellationToken) => context.SaveChangesAsync(acceptAllChangesOnSuccess: false, cancellationToken), + verifySucceeded: (context, cancellationToken) => context.Blogs.AsNoTracking().AnyAsync(b => b.BlogId == blogToAdd.BlogId, cancellationToken)); db.ChangeTracker.AcceptAllChanges(); #endregion } - private static void ExecuteInTransactionWithTracking() + private static async Task ExecuteInTransactionWithTracking() { #region Tracking @@ -107,14 +108,14 @@ private static void ExecuteInTransactionWithTracking() var transaction = new TransactionRow { Id = Guid.NewGuid() }; db.Transactions.Add(transaction); - strategy.ExecuteInTransaction( + await strategy.ExecuteInTransactionAsync( db, - operation: context => { context.SaveChanges(acceptAllChangesOnSuccess: false); }, - verifySucceeded: context => context.Transactions.AsNoTracking().Any(t => t.Id == transaction.Id)); + operation: (context, cancellationToken) => context.SaveChangesAsync(acceptAllChangesOnSuccess: false, cancellationToken), + verifySucceeded: (context, cancellationToken) => context.Transactions.AsNoTracking().AnyAsync(t => t.Id == transaction.Id, cancellationToken)); db.ChangeTracker.AcceptAllChanges(); db.Transactions.Remove(transaction); - db.SaveChanges(); + await db.SaveChangesAsync(); #endregion } diff --git a/samples/core/Miscellaneous/DiagnosticListeners/Program.cs b/samples/core/Miscellaneous/DiagnosticListeners/Program.cs index 1938fd312b..b61e0b113f 100644 --- a/samples/core/Miscellaneous/DiagnosticListeners/Program.cs +++ b/samples/core/Miscellaneous/DiagnosticListeners/Program.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Diagnostics; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; @@ -53,7 +54,7 @@ public void OnNext(KeyValuePair value) public class Program { #region Program - public static void Main() + public static async Task Main() { #region RegisterDiagnosticListener DiagnosticListener.AllListeners.Subscribe(new DiagnosticObserver()); @@ -61,24 +62,24 @@ public static void Main() using (var context = new BlogsContext()) { - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); context.Add( new Blog { Name = "EF Blog", Posts = { new Post { Title = "EF Core 3.1!" }, new Post { Title = "EF Core 5.0!" } } }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = new BlogsContext()) { - var blog = context.Blogs.Include(e => e.Posts).Single(); + var blog = await context.Blogs.Include(e => e.Posts).SingleAsync(); blog.Name = "EF Core Blog"; context.Remove(blog.Posts.First()); blog.Posts.Add(new Post { Title = "EF Core 6.0!" }); - context.SaveChanges(); + await context.SaveChangesAsync(); } #endregion } diff --git a/samples/core/Miscellaneous/Events/Program.cs b/samples/core/Miscellaneous/Events/Program.cs index c14a9bb0ce..2a34131c9f 100644 --- a/samples/core/Miscellaneous/Events/Program.cs +++ b/samples/core/Miscellaneous/Events/Program.cs @@ -2,18 +2,19 @@ using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; public class Program { - public static void Main() + public static async Task Main() { #region Demonstration using (var context = new BlogsContext()) { - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); context.Add( new Blog @@ -23,18 +24,18 @@ public static void Main() Posts = { new Post { Id = 1, Title = "EF Core 3.1!" }, new Post { Id = 2, Title = "EF Core 5.0!" } } }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = new BlogsContext()) { - var blog = context.Blogs.Include(e => e.Posts).Single(); + var blog = await context.Blogs.Include(e => e.Posts).SingleAsync(); blog.Name = "EF Core Blog"; context.Remove(blog.Posts.First()); blog.Posts.Add(new Post { Id = 3, Title = "EF Core 6.0!" }); - context.SaveChanges(); + await context.SaveChangesAsync(); } #endregion } diff --git a/samples/core/Miscellaneous/Logging/Logging/Program.cs b/samples/core/Miscellaneous/Logging/Logging/Program.cs index 558099dd81..a1f0f238dc 100644 --- a/samples/core/Miscellaneous/Logging/Logging/Program.cs +++ b/samples/core/Miscellaneous/Logging/Logging/Program.cs @@ -1,16 +1,17 @@ using System; +using System.Threading.Tasks; namespace EFLogging; public class Program { - public static void Main() + public static async Task Main() { using (var db = new BloggingContext()) { - db.Database.EnsureCreated(); + await db.Database.EnsureCreatedAsync(); db.Blogs.Add(new Blog { Url = "http://sample.com" }); - db.SaveChanges(); + await db.SaveChangesAsync(); } using (var db = new BloggingContext()) @@ -23,9 +24,9 @@ public static void Main() using (var db = new BloggingContextWithFiltering()) { - db.Database.EnsureCreated(); + await db.Database.EnsureCreatedAsync(); db.Blogs.Add(new Blog { Url = "http://sample.com" }); - db.SaveChanges(); + await db.SaveChangesAsync(); } using (var db = new BloggingContextWithFiltering()) @@ -36,4 +37,4 @@ public static void Main() } } } -} \ No newline at end of file +} diff --git a/samples/core/Miscellaneous/Logging/SimpleLogging/Program.cs b/samples/core/Miscellaneous/Logging/SimpleLogging/Program.cs index 24b066adc0..8b919a71c8 100755 --- a/samples/core/Miscellaneous/Logging/SimpleLogging/Program.cs +++ b/samples/core/Miscellaneous/Logging/SimpleLogging/Program.cs @@ -8,43 +8,43 @@ public class Program { - public static void Main() + public static async Task Main() { - TestCode(); - TestCode(); - TestCode(); - TestCode(); - TestCode(); - TestCode(); - TestCode(); - TestCode(); - TestCode(); - TestCode(); - TestCode(); - TestCode(); - TestCode(); - TestCode(); - TestCode(); - TestDatabaseLog(); - - static void TestCode() + await TestCode(); + await TestCode(); + await TestCode(); + await TestCode(); + await TestCode(); + await TestCode(); + await TestCode(); + await TestCode(); + await TestCode(); + await TestCode(); + await TestCode(); + await TestCode(); + await TestCode(); + await TestCode(); + await TestCode(); + await TestDatabaseLog(); + + static async Task TestCode() where TContext : BlogsContext, new() { using var context = new TContext(); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } - static void TestDatabaseLog() + static async Task TestDatabaseLog() { using var context = new DatabaseLogContext(); - context.Database.EnsureDeleted(); + await context.Database.EnsureDeletedAsync(); context.Log = Console.WriteLine; - context.Database.EnsureCreated(); + await context.Database.EnsureCreatedAsync(); } } } diff --git a/samples/core/Miscellaneous/Multitenancy/MultiDb/ContactContext.cs b/samples/core/Miscellaneous/Multitenancy/MultiDb/ContactContext.cs index 143a94918e..4613b0a6f0 100644 --- a/samples/core/Miscellaneous/Multitenancy/MultiDb/ContactContext.cs +++ b/samples/core/Miscellaneous/Multitenancy/MultiDb/ContactContext.cs @@ -16,13 +16,13 @@ public ContactContext( { _tenantService = service; _configuration = config; - } + } public DbSet Contacts { get; set; } = null!; - public void CheckAndSeed() + public async Task CheckAndSeed() { - if (Database.EnsureCreated()) + if (await Database.EnsureCreatedAsync()) { foreach (var contact in Contact.GeneratedContacts) { @@ -33,7 +33,7 @@ public void CheckAndSeed() } } - SaveChanges(); + await SaveChangesAsync(); } } diff --git a/samples/core/Miscellaneous/Multitenancy/MultiDb/Program.cs b/samples/core/Miscellaneous/Multitenancy/MultiDb/Program.cs index 0624d8c56c..2404cfad07 100644 --- a/samples/core/Miscellaneous/Multitenancy/MultiDb/Program.cs +++ b/samples/core/Miscellaneous/Multitenancy/MultiDb/Program.cs @@ -24,7 +24,7 @@ { tenantService.SetTenant(tenant); using var ctx = factory.CreateDbContext(); - ctx.CheckAndSeed(); + await ctx.CheckAndSeed(); } } diff --git a/samples/core/Miscellaneous/Multitenancy/SingleDbSingleTable/Data/ContactContext.cs b/samples/core/Miscellaneous/Multitenancy/SingleDbSingleTable/Data/ContactContext.cs index f3441ab646..8765ad8806 100644 --- a/samples/core/Miscellaneous/Multitenancy/SingleDbSingleTable/Data/ContactContext.cs +++ b/samples/core/Miscellaneous/Multitenancy/SingleDbSingleTable/Data/ContactContext.cs @@ -1,5 +1,6 @@ using Common; using Microsoft.EntityFrameworkCore; +using System.Threading.Tasks; namespace SingleDbSingleTable.Data { @@ -14,9 +15,9 @@ public ContactContext( public DbSet Contacts { get; set; } = null!; - public void CheckAndSeed() + public async Task CheckAndSeedAsync() { - if (Database.EnsureCreated()) + if (await Database.EnsureCreatedAsync()) { foreach (var contact in Contact.GeneratedContacts) { @@ -24,7 +25,7 @@ public void CheckAndSeed() Contacts.Add(new MultitenantContact(contact, tenant)); } - SaveChanges(); + await SaveChangesAsync(); } } diff --git a/samples/core/Miscellaneous/Multitenancy/SingleDbSingleTable/Program.cs b/samples/core/Miscellaneous/Multitenancy/SingleDbSingleTable/Program.cs index 74ee6ffa03..ebcad63b98 100644 --- a/samples/core/Miscellaneous/Multitenancy/SingleDbSingleTable/Program.cs +++ b/samples/core/Miscellaneous/Multitenancy/SingleDbSingleTable/Program.cs @@ -17,7 +17,7 @@ // seed the database so demo is simple and doesn't require migrations using var ctx = app.Services.CreateScope().ServiceProvider.GetRequiredService(); -ctx.CheckAndSeed(); +await ctx.CheckAndSeedAsync(); // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) diff --git a/samples/core/Miscellaneous/NewInEFCore6/ArrayParametersSample.cs b/samples/core/Miscellaneous/NewInEFCore6/ArrayParametersSample.cs index 75d33e224e..e2e55ee04c 100644 --- a/samples/core/Miscellaneous/NewInEFCore6/ArrayParametersSample.cs +++ b/samples/core/Miscellaneous/NewInEFCore6/ArrayParametersSample.cs @@ -1,23 +1,24 @@ using System; using System.Data; +using System.Threading.Tasks; using Microsoft.Data.SqlClient; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; public static class ArrayParametersSample { - public static void Array_parameters_are_logged_in_readable_form() + public static async Task Array_parameters_are_logged_in_readable_form() { Console.WriteLine($">>>> Sample: {nameof(Array_parameters_are_logged_in_readable_form)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); + await Helpers.RecreateCleanDatabase(); using var context = new SomeDbContext(); try { - context.Database.ExecuteSqlRaw( + await context.Database.ExecuteSqlRawAsync( "SELECT * FROM Blogs WHERE Data = {0}", new SqlParameter { @@ -39,12 +40,12 @@ public static void Array_parameters_are_logged_in_readable_form() public static class Helpers { - public static void RecreateCleanDatabase() + public static async Task RecreateCleanDatabase() { using var context = new IsNullOrWhitespaceSample.BooksContext(quiet: true); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } } diff --git a/samples/core/Miscellaneous/NewInEFCore6/BoolToStringTranslationSample.cs b/samples/core/Miscellaneous/NewInEFCore6/BoolToStringTranslationSample.cs index 685c2748fd..707257b5c6 100644 --- a/samples/core/Miscellaneous/NewInEFCore6/BoolToStringTranslationSample.cs +++ b/samples/core/Miscellaneous/NewInEFCore6/BoolToStringTranslationSample.cs @@ -1,21 +1,22 @@ using System; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; public static class BoolToStringTranslationSample { - public static void Translate_bool_to_string_on_SQL_Server() + public static async Task Translate_bool_to_string_on_SQL_Server() { Console.WriteLine($">>>> Sample: {nameof(Translate_bool_to_string_on_SQL_Server)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new CustomersContext(); - var results1 = context.Customers.Select(c => new { c.Name, IsActive = c.IsActive.ToString() }).ToList(); + var results1 = await context.Customers.Select(c => new { c.Name, IsActive = c.IsActive.ToString() }).ToListAsync(); Console.WriteLine(); @@ -26,7 +27,7 @@ public static void Translate_bool_to_string_on_SQL_Server() Console.WriteLine(); - var results2 = context.Customers.Where(b => b.IsActive.ToString() == "true").ToList(); + var results2 = await context.Customers.Where(b => b.IsActive.ToString() == "true").ToListAsync(); Console.WriteLine(); @@ -40,15 +41,15 @@ public static void Translate_bool_to_string_on_SQL_Server() public static class Helpers { - public static void RecreateCleanDatabase() + public static async Task RecreateCleanDatabase() { using var context = new CustomersContext(quiet: true); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } - public static void PopulateDatabase() + public static async Task PopulateDatabase() { using var context = new CustomersContext(quiet: true); @@ -69,7 +70,7 @@ public static void PopulateDatabase() IsActive = true }); - context.SaveChanges(); + await context.SaveChangesAsync(); } } diff --git a/samples/core/Miscellaneous/NewInEFCore6/ColumnOrderSample.cs b/samples/core/Miscellaneous/NewInEFCore6/ColumnOrderSample.cs index 011161d1bc..7cc616bde1 100644 --- a/samples/core/Miscellaneous/NewInEFCore6/ColumnOrderSample.cs +++ b/samples/core/Miscellaneous/NewInEFCore6/ColumnOrderSample.cs @@ -1,20 +1,21 @@ using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; public static class ColumnOrderSample { - public static void Can_use_ColumnAttribute_to_set_column_order() + public static async Task Can_use_ColumnAttribute_to_set_column_order() { Console.WriteLine($">>>> Sample: {nameof(Can_use_ColumnAttribute_to_set_column_order)}"); Console.WriteLine(); using var context = new EmployeeContext(); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); Console.WriteLine(); } diff --git a/samples/core/Miscellaneous/NewInEFCore6/CommandSourceSample.cs b/samples/core/Miscellaneous/NewInEFCore6/CommandSourceSample.cs index f2b29eb3f4..bbc7b304a5 100644 --- a/samples/core/Miscellaneous/NewInEFCore6/CommandSourceSample.cs +++ b/samples/core/Miscellaneous/NewInEFCore6/CommandSourceSample.cs @@ -1,20 +1,21 @@ using System; using System.Data.Common; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; public static class CommandSourceSample { - public static void Interceptors_get_the_source_of_the_command() + public static async Task Interceptors_get_the_source_of_the_command() { Console.WriteLine($">>>> Sample: {nameof(Interceptors_get_the_source_of_the_command)}"); Console.WriteLine(); using var context = new CustomersContext(); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); context.Add( new Customer @@ -22,11 +23,11 @@ public static void Interceptors_get_the_source_of_the_command() Name = "Sam Vimes" }); - context.SaveChanges(); + await context.SaveChangesAsync(); context.ChangeTracker.Clear(); - var customers = context.Customers.ToList(); + var customers = await context.Customers.ToListAsync(); Console.WriteLine(); } diff --git a/samples/core/Miscellaneous/NewInEFCore6/ContainsFreeTextSample.cs b/samples/core/Miscellaneous/NewInEFCore6/ContainsFreeTextSample.cs index 72abcbc68c..2bebe40d74 100644 --- a/samples/core/Miscellaneous/NewInEFCore6/ContainsFreeTextSample.cs +++ b/samples/core/Miscellaneous/NewInEFCore6/ContainsFreeTextSample.cs @@ -1,24 +1,25 @@ using System; using System.Linq; using System.Text.Json; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; public static class ContainsFreeTextSample { - public static void Contains_with_non_string() + public static async Task Contains_with_non_string() { Console.WriteLine($">>>> Sample: {nameof(Contains_with_non_string)}"); Console.WriteLine($">>>> Note: does not work with SQL Server LocalDb"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new CustomerContext(); #region Query - var result = context.Customers.Where(e => EF.Functions.Contains(e.Name, "Martin")).ToList(); + var result = await context.Customers.Where(e => EF.Functions.Contains(e.Name, "Martin")).ToListAsync(); #endregion Console.WriteLine(); @@ -26,19 +27,19 @@ public static void Contains_with_non_string() public static class Helpers { - public static void RecreateCleanDatabase() + public static async Task RecreateCleanDatabase() { using var context = new CustomerContext(quiet: true); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); - context.Database.ExecuteSqlRaw( + await context.Database.ExecuteSqlRawAsync( @"CREATE FULLTEXT CATALOG CustomersAndNames AS DEFAULT; CREATE FULLTEXT INDEX ON Customers (Name) KEY INDEX IX_Names;"); } - public static void PopulateDatabase() + public static async Task PopulateDatabase() { using var context = new CustomerContext(quiet: true); @@ -78,7 +79,7 @@ public static void PopulateDatabase() } }); - context.SaveChanges(); + await context.SaveChangesAsync(); } } diff --git a/samples/core/Miscellaneous/NewInEFCore6/ConvertNullsSample.cs b/samples/core/Miscellaneous/NewInEFCore6/ConvertNullsSample.cs index e78a9c2d23..df8c33847f 100644 --- a/samples/core/Miscellaneous/NewInEFCore6/ConvertNullsSample.cs +++ b/samples/core/Miscellaneous/NewInEFCore6/ConvertNullsSample.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Infrastructure; @@ -9,12 +10,12 @@ public static class ConvertNullsSample { - public static void Value_converters_can_convert_nulls() + public static async Task Value_converters_can_convert_nulls() { Console.WriteLine($">>>> Sample: {nameof(Value_converters_can_convert_nulls)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); + await Helpers.RecreateCleanDatabase(); using (var context = new CatsContext()) { @@ -24,7 +25,7 @@ public static void Value_converters_can_convert_nulls() new Cat { Name = "Clippy", Breed = Breed.Burmese }, new Cat { Name = "Sid", Breed = Breed.Tonkinese }); - context.SaveChanges(); + await context.SaveChangesAsync(); #endregion Console.WriteLine(); @@ -32,7 +33,7 @@ public static void Value_converters_can_convert_nulls() using (var context = new CatsContext()) { - var cats = context.Cats.ToList(); + var cats = await context.Cats.ToListAsync(); Console.WriteLine(); @@ -45,12 +46,12 @@ public static void Value_converters_can_convert_nulls() Console.WriteLine(); } - public static void Value_converters_can_convert_nulls_in_FKs() + public static async Task Value_converters_can_convert_nulls_in_FKs() { Console.WriteLine($">>>> Sample: {nameof(Value_converters_can_convert_nulls_in_FKs)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); + await Helpers.RecreateCleanDatabase(); using (var context = new CarsContext()) { @@ -65,7 +66,7 @@ public static void Value_converters_can_convert_nulls_in_FKs() Model = "Kia Soul" }); - context.SaveChanges(); + await context.SaveChangesAsync(); Console.WriteLine(); } @@ -73,7 +74,7 @@ public static void Value_converters_can_convert_nulls_in_FKs() using (var context = new CarsContext()) { // Not currently working - var cars = context.Cars.Where(e => e.OwnerId == null).ToList(); + var cars = await context.Cars.Where(e => e.OwnerId == null).ToListAsync(); Console.WriteLine(); @@ -88,18 +89,18 @@ public static void Value_converters_can_convert_nulls_in_FKs() public static class Helpers { - public static void RecreateCleanDatabase() + public static async Task RecreateCleanDatabase() { using (var context = new CarsContext(quiet: true)) { - context.Database.EnsureDeleted(); - context.Database.Migrate(); + await context.Database.EnsureDeletedAsync(); + await context.Database.MigrateAsync(); } using (var context = new CatsContext(quiet: true)) { - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } } } diff --git a/samples/core/Miscellaneous/NewInEFCore6/DbContextFactorySample.cs b/samples/core/Miscellaneous/NewInEFCore6/DbContextFactorySample.cs index cf4a12d919..ea1b5229fb 100644 --- a/samples/core/Miscellaneous/NewInEFCore6/DbContextFactorySample.cs +++ b/samples/core/Miscellaneous/NewInEFCore6/DbContextFactorySample.cs @@ -1,5 +1,6 @@ using System; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; @@ -67,9 +68,9 @@ public MyController1(SomeDbContext context) _context = context; } - public void DoSomething() + public async Task DoSomething() { - var results = _context.Blogs.ToList(); + var results = await _context.Blogs.ToListAsync(); // Injected context is disposed when the request scope is disposed } @@ -86,13 +87,13 @@ public MyController2(IDbContextFactory contextFactory) _contextFactory = contextFactory; } - public void DoSomething() + public async Task DoSomething() { using var context1 = _contextFactory.CreateDbContext(); using var context2 = _contextFactory.CreateDbContext(); - var results1 = context1.Blogs.ToList(); - var results2 = context2.Blogs.ToList(); + var results1 = await context1.Blogs.ToListAsync(); + var results2 = await context2.Blogs.ToListAsync(); // Contexts obtained from the factory must be explicitly disposed } diff --git a/samples/core/Miscellaneous/NewInEFCore6/EntityTypeConfigurationAttributeSample.cs b/samples/core/Miscellaneous/NewInEFCore6/EntityTypeConfigurationAttributeSample.cs index 00863f4302..041f79840f 100644 --- a/samples/core/Miscellaneous/NewInEFCore6/EntityTypeConfigurationAttributeSample.cs +++ b/samples/core/Miscellaneous/NewInEFCore6/EntityTypeConfigurationAttributeSample.cs @@ -1,44 +1,45 @@ using System; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Metadata.Builders; public static class EntityTypeConfigurationAttributeSample { - public static void Using_EntityTypeConfigurationAttribute() + public static async Task Using_EntityTypeConfigurationAttribute() { Console.WriteLine($">>>> Sample: {nameof(Using_EntityTypeConfigurationAttribute)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BooksContext(); - var book = context.Books.Single(e => e.Id == 1); + var book = await context.Books.SingleAsync(e => e.Id == 1); Console.WriteLine(); } public static class Helpers { - public static void RecreateCleanDatabase() + public static async Task RecreateCleanDatabase() { using var context = new BooksContext(); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } - public static void PopulateDatabase() + public static async Task PopulateDatabase() { using var context = new BooksContext(); context.Add( new Book() { Isbn = "978-0-39-481823-8", Title = "What Do People Do All Day?" }); - context.SaveChanges(); + await context.SaveChangesAsync(); } } diff --git a/samples/core/Miscellaneous/NewInEFCore6/GroupBySample.cs b/samples/core/Miscellaneous/NewInEFCore6/GroupBySample.cs index 554dca5e8f..016264ded5 100644 --- a/samples/core/Miscellaneous/NewInEFCore6/GroupBySample.cs +++ b/samples/core/Miscellaneous/NewInEFCore6/GroupBySample.cs @@ -1,31 +1,32 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; public static class GroupBySample { - public static void Translate_GroupBy_followed_by_FirstOrDefault_over_group() + public static async Task Translate_GroupBy_followed_by_FirstOrDefault_over_group() { Console.WriteLine($">>>> Sample: {nameof(Translate_GroupBy_followed_by_FirstOrDefault_over_group)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); // Example 1. From #12088 using (var context = new ShoesContext()) { #region GroupBy1 - var people = context.People + var people = await context.People .Include(e => e.Shoes) .GroupBy(e => e.FirstName) .Select( g => g.OrderBy(e => e.FirstName) .ThenBy(e => e.LastName) .FirstOrDefault()) - .ToList(); + .ToListAsync(); #endregion Console.WriteLine(); @@ -42,7 +43,7 @@ public static void Translate_GroupBy_followed_by_FirstOrDefault_over_group() using (var context = new ShoesContext()) { #region GroupBy2 - var group = context.People + var group = await context.People .Select( p => new { @@ -51,7 +52,7 @@ public static void Translate_GroupBy_followed_by_FirstOrDefault_over_group() }) .GroupBy(p => p.FirstName) .Select(g => g.First()) - .First(); + .FirstAsync(); #endregion Console.WriteLine(); @@ -63,12 +64,12 @@ public static void Translate_GroupBy_followed_by_FirstOrDefault_over_group() using (var context = new ShoesContext()) { #region GroupBy3 - var people = context.People + var people = await context.People .Where(e => e.MiddleInitial == "Q" && e.Age == 20) .GroupBy(e => e.LastName) .Select(g => g.First().LastName) .OrderBy(e => e.Length) - .ToList(); + .ToListAsync(); #endregion Console.WriteLine(); @@ -85,7 +86,7 @@ public static void Translate_GroupBy_followed_by_FirstOrDefault_over_group() using (var context = new ShoesContext()) { #region GroupBy4 - var results = (from person in context.People + var results = await (from person in context.People join shoes in context.Shoes on person.Age equals shoes.Age group shoes by shoes.Style into people @@ -95,7 +96,7 @@ into people Style = people.Select(p => p.Style).FirstOrDefault(), Count = people.Count() }) - .ToList(); + .ToListAsync(); #endregion Console.WriteLine(); @@ -112,11 +113,11 @@ into people using (var context = new ShoesContext()) { #region GroupBy5 - var results = context.People + var results = await context.People .GroupBy(e => e.FirstName) .Select(g => g.First().LastName) .OrderBy(e => e) - .ToList(); + .ToListAsync(); #endregion Console.WriteLine(); @@ -133,11 +134,12 @@ into people using (var context = new ShoesContext()) { #region GroupBy6 - var results = context.People.Where(e => e.Age == 20) + var results = await context.People + .Where(e => e.Age == 20) .GroupBy(e => e.Id) .Select(g => g.First().MiddleInitial) .OrderBy(e => e) - .ToList(); + .ToListAsync(); #endregion Console.WriteLine(); @@ -156,7 +158,7 @@ into people #region GroupBy7 var size = 11; var results - = context.People + = await context.People .Where( p => p.Feet.Size == size && p.MiddleInitial != null @@ -174,7 +176,7 @@ var results g.Key.Size, Min = g.Min(p => p.Feet.Size), }) - .ToList(); + .ToListAsync(); #endregion Console.WriteLine(); @@ -191,7 +193,7 @@ var results using (var context = new ShoesContext()) { #region GroupBy8 - var result = context.People + var result = await context.People .Include(x => x.Shoes) .Include(x => x.Feet) .GroupBy( @@ -209,7 +211,7 @@ var results SumOver60 = x.Sum(el => el.Id) / (decimal)60, TotalCallOutCharges = x.Sum(el => el.Feet.Size == 11 ? 1 : 0) }) - .Count(); + .CountAsync(); #endregion Console.WriteLine(); @@ -221,14 +223,14 @@ var results using (var context = new ShoesContext()) { #region GroupBy9 - var results = context.People + var results = await context.People .GroupBy(n => n.FirstName) .Select(g => new { Feet = g.Key, Total = g.Sum(n => n.Feet.Size) }) - .ToList(); + .ToListAsync(); #endregion Console.WriteLine(); @@ -280,7 +282,7 @@ in temp Console.WriteLine(); - foreach (var result in results) + await foreach (var result in results.AsAsyncEnumerable()) { Console.WriteLine($"{result.Id}: {result.Age} year old {result.Style}"); foreach (var value in result.Values) @@ -296,11 +298,11 @@ in temp using (var context = new ShoesContext()) { #region GroupBy11 - var grouping = context.People + var grouping = await context.People .GroupBy(i => i.LastName) .Select(g => new { LastName = g.Key, Count = g.Count() , First = g.FirstOrDefault(), Take = g.Take(2)}) .OrderByDescending(e => e.LastName) - .ToList(); + .ToListAsync(); #endregion Console.WriteLine(); @@ -322,13 +324,13 @@ in temp using (var context = new ShoesContext()) { #region GroupBy12 - var grouping = context.People + var grouping = await context.People .Include(e => e.Shoes) .OrderBy(e => e.FirstName) .ThenBy(e => e.LastName) .GroupBy(e => e.FirstName) .Select(g => new { Name = g.Key, People = g.ToList()}) - .ToList(); + .ToListAsync(); #endregion Console.WriteLine(); @@ -348,14 +350,14 @@ in temp using (var context = new ShoesContext()) { #region GroupBy13 - var grouping = context.People + var grouping = await context.People .GroupBy(m => new {m.FirstName, m.MiddleInitial }) .Select(am => new { Key = am.Key, Items = am.ToList() }) - .ToList(); + .ToListAsync(); #endregion Console.WriteLine(); @@ -376,15 +378,15 @@ in temp public static class Helpers { - public static void RecreateCleanDatabase() + public static async Task RecreateCleanDatabase() { using var context = new ShoesContext(quiet: true); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } - public static void PopulateDatabase() + public static async Task PopulateDatabase() { using var context = new ShoesContext(quiet: true); @@ -498,7 +500,7 @@ public static void PopulateDatabase() Shoes = { new() { Style = "Sneakers", Age = 20 }, new() { Style = "Dress", Age = 21 } } }); - context.SaveChanges(); + await context.SaveChangesAsync(); } } diff --git a/samples/core/Miscellaneous/NewInEFCore6/HasConversionSample.cs b/samples/core/Miscellaneous/NewInEFCore6/HasConversionSample.cs index 6de0b391d6..b8aa5881f1 100644 --- a/samples/core/Miscellaneous/NewInEFCore6/HasConversionSample.cs +++ b/samples/core/Miscellaneous/NewInEFCore6/HasConversionSample.cs @@ -1,32 +1,33 @@ using System; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; public static class HasConversionSample { - public static void Can_set_value_converter_type_using_generic_method() + public static async Task Can_set_value_converter_type_using_generic_method() { Console.WriteLine($">>>> Sample: {nameof(Can_set_value_converter_type_using_generic_method)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); Console.WriteLine(); } public static class Helpers { - public static void RecreateCleanDatabase() + public static async Task RecreateCleanDatabase() { using var context = new CurrencyContext(quiet: true); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } - public static void PopulateDatabase() + public static async Task PopulateDatabase() { using var context = new CurrencyContext(); @@ -68,7 +69,7 @@ public static void PopulateDatabase() Currency = Currency.PoundsSterling }); - context.SaveChanges(); + await context.SaveChangesAsync(); } } diff --git a/samples/core/Miscellaneous/NewInEFCore6/InMemoryRequiredPropertiesSample.cs b/samples/core/Miscellaneous/NewInEFCore6/InMemoryRequiredPropertiesSample.cs index a5b54b720c..caf9a2d9e1 100644 --- a/samples/core/Miscellaneous/NewInEFCore6/InMemoryRequiredPropertiesSample.cs +++ b/samples/core/Miscellaneous/NewInEFCore6/InMemoryRequiredPropertiesSample.cs @@ -1,11 +1,12 @@ using System; using System.ComponentModel.DataAnnotations; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; public static class InMemoryRequiredPropertiesSample { - public static void Required_properties_validated_with_in_memory_database() + public static async Task Required_properties_validated_with_in_memory_database() { Console.WriteLine($">>>> Sample: {nameof(Required_properties_validated_with_in_memory_database)}"); Console.WriteLine(); @@ -16,7 +17,7 @@ public static void Required_properties_validated_with_in_memory_database() try { - context.SaveChanges(); + await context.SaveChangesAsync(); } catch (Exception e) { @@ -26,7 +27,7 @@ public static void Required_properties_validated_with_in_memory_database() Console.WriteLine(); } - public static void Required_property_validation_with_in_memory_database_can_be_disabled() + public static async Task Required_property_validation_with_in_memory_database_can_be_disabled() { Console.WriteLine($">>>> Sample: {nameof(Required_property_validation_with_in_memory_database_can_be_disabled)}"); Console.WriteLine(); @@ -35,7 +36,7 @@ public static void Required_property_validation_with_in_memory_database_can_be_d context.Add(new User()); - context.SaveChanges(); + await context.SaveChangesAsync(); Console.WriteLine(); } diff --git a/samples/core/Miscellaneous/NewInEFCore6/IsNullOrWhitespaceSample.cs b/samples/core/Miscellaneous/NewInEFCore6/IsNullOrWhitespaceSample.cs index c70a067906..647d6a9907 100644 --- a/samples/core/Miscellaneous/NewInEFCore6/IsNullOrWhitespaceSample.cs +++ b/samples/core/Miscellaneous/NewInEFCore6/IsNullOrWhitespaceSample.cs @@ -1,24 +1,25 @@ using System; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; public static class IsNullOrWhitespaceSample { - public static void Translate_IsNullOrWhitespace() + public static async Task Translate_IsNullOrWhitespace() { Console.WriteLine($">>>> Sample: {nameof(Translate_IsNullOrWhitespace)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BooksContext(); #region Query - var users = context.Users.Where( + var users = await context.Users.Where( e => string.IsNullOrWhiteSpace(e.FirstName) - || string.IsNullOrWhiteSpace(e.LastName)).ToList(); + || string.IsNullOrWhiteSpace(e.LastName)).ToListAsync(); #endregion foreach (var user in users) @@ -31,15 +32,15 @@ public static void Translate_IsNullOrWhitespace() public static class Helpers { - public static void RecreateCleanDatabase() + public static async Task RecreateCleanDatabase() { using var context = new BooksContext(quiet: true); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } - public static void PopulateDatabase() + public static async Task PopulateDatabase() { using var context = new BooksContext(quiet: true); @@ -69,7 +70,7 @@ public static void PopulateDatabase() LastName = "\t" }); - context.SaveChanges(); + await context.SaveChangesAsync(); } } diff --git a/samples/core/Miscellaneous/NewInEFCore6/ManyToManyConfigurationSample.cs b/samples/core/Miscellaneous/NewInEFCore6/ManyToManyConfigurationSample.cs index 0019756eac..4e27a760b8 100644 --- a/samples/core/Miscellaneous/NewInEFCore6/ManyToManyConfigurationSample.cs +++ b/samples/core/Miscellaneous/NewInEFCore6/ManyToManyConfigurationSample.cs @@ -1,25 +1,26 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; public static class ManyToManyConfigurationSample { - public static void Many_to_many_relationships_may_need_less_configuration() + public static async Task Many_to_many_relationships_may_need_less_configuration() { Console.WriteLine($">>>> Sample: {nameof(Many_to_many_relationships_may_need_less_configuration)}"); Console.WriteLine(); - ManyToManyTest(); - ManyToManyTest(); - ManyToManyTest(); - ManyToManyTest(); - // ManyToManyTest(); - ManyToManyTest(); + await ManyToManyTest(); + await ManyToManyTest(); + await ManyToManyTest(); + await ManyToManyTest(); + // await ManyToManyTest(); + await ManyToManyTest(); } - public static void ManyToManyTest() + public static async Task ManyToManyTest() where TContext : BaseContext, new() { Console.WriteLine($"{typeof(TContext).Name}: "); @@ -27,13 +28,13 @@ public static void ManyToManyTest() using (var context = new TContext()) { - context.Database.EnsureDeleted(); + await context.Database.EnsureDeletedAsync(); Console.WriteLine(context.Model.ToDebugString()); Console.WriteLine(); context.Log = true; - context.Database.EnsureCreated(); + await context.Database.EnsureCreatedAsync(); context.Log = false; var cats = new List @@ -48,14 +49,14 @@ public static void ManyToManyTest() new() { Name = "Arthur", Cats = { cats[0], cats[1] } } }); - context.SaveChanges(); + await context.SaveChangesAsync(); } Console.WriteLine(); using (var context = new TContext()) { - var cats = context.Cats.Include(e => e.Humans).ToList(); + var cats = await context.Cats.Include(e => e.Humans).ToListAsync(); foreach (var cat in cats) { Console.WriteLine($"{cat.Name} has {cat.Humans.Count} humans."); diff --git a/samples/core/Miscellaneous/NewInEFCore6/MathFTranslationSample.cs b/samples/core/Miscellaneous/NewInEFCore6/MathFTranslationSample.cs index 2431e88399..64d32baadd 100644 --- a/samples/core/Miscellaneous/NewInEFCore6/MathFTranslationSample.cs +++ b/samples/core/Miscellaneous/NewInEFCore6/MathFTranslationSample.cs @@ -1,29 +1,30 @@ using System; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; public static class MathFTranslationSample { - public static void Translate_MathF_methods() + public static async Task Translate_MathF_methods() { Console.WriteLine($">>>> Sample: {nameof(Translate_MathF_methods)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new CustomersContext(); // Fails; see #25421 - // var result = context.Reviews + // var result = await context.Reviews // .Select(e => new // { // e.Title, // Rating = MathF.Truncate(e.Rating) // }) // .OrderBy(e => e.Rating) - // .First(); + // .FirstAsync(); Console.WriteLine(); // Console.WriteLine($"Found {result.Title} with rating {result.Rating}."); @@ -32,15 +33,15 @@ public static void Translate_MathF_methods() public static class Helpers { - public static void RecreateCleanDatabase() + public static async Task RecreateCleanDatabase() { using var context = new CustomersContext(quiet: true); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } - public static void PopulateDatabase() + public static async Task PopulateDatabase() { using var context = new CustomersContext(quiet: true); @@ -64,7 +65,7 @@ public static void PopulateDatabase() Rating = 3.5f }); - context.SaveChanges(); + await context.SaveChangesAsync(); } } diff --git a/samples/core/Miscellaneous/NewInEFCore6/OptionalDependentsSample.cs b/samples/core/Miscellaneous/NewInEFCore6/OptionalDependentsSample.cs index 9e7f11f958..b9d9c92f2d 100644 --- a/samples/core/Miscellaneous/NewInEFCore6/OptionalDependentsSample.cs +++ b/samples/core/Miscellaneous/NewInEFCore6/OptionalDependentsSample.cs @@ -1,17 +1,18 @@ using System; using System.ComponentModel.DataAnnotations; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; public static class OptionalDependentsSample { - public static void Optional_dependents_with_a_required_property() + public static async Task Optional_dependents_with_a_required_property() { Console.WriteLine($">>>> Sample: {nameof(Optional_dependents_with_a_required_property)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); + await Helpers.RecreateCleanDatabase(); using (var context = new SomeDbContext()) { @@ -35,13 +36,13 @@ public static void Optional_dependents_with_a_required_property() }); #endregion - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = new SomeDbContext()) { #region CheckForNullAddress - foreach (var customer in context.Customers1) + await foreach (var customer in context.Customers1.AsAsyncEnumerable()) { Console.Write(customer.Name); @@ -60,12 +61,12 @@ public static void Optional_dependents_with_a_required_property() Console.WriteLine(); } - public static void Optional_dependents_without_a_required_property() + public static async Task Optional_dependents_without_a_required_property() { Console.WriteLine($">>>> Sample: {nameof(Optional_dependents_without_a_required_property)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); + await Helpers.RecreateCleanDatabase(); using (var context = new SomeDbContext()) { @@ -85,7 +86,7 @@ public static void Optional_dependents_without_a_required_property() #endregion - context.SaveChanges(); + await context.SaveChangesAsync(); } Console.WriteLine(); @@ -93,15 +94,15 @@ public static void Optional_dependents_without_a_required_property() using (var context = new SomeDbContext()) { var connection = context.Database.GetDbConnection(); - connection.Open(); + await connection.OpenAsync(); - using var command = connection.CreateCommand(); + await using var command = connection.CreateCommand(); command.CommandText = "SELECT Id, Name, Address_House, Address_Street, Address_City, Address_Postcode FROM Customers2"; Console.WriteLine($"Id Name House Street City Postcode"); - using var reader = command.ExecuteReader(); - while (reader.Read()) + await using var reader = await command.ExecuteReaderAsync(); + while (await reader.ReadAsync()) { Console.Write($"{reader.GetInt32(0)} {reader.GetString(1).PadRight(17)} "); for (int i = 2; i <= 5; i++) @@ -111,18 +112,18 @@ public static void Optional_dependents_without_a_required_property() Console.WriteLine(); } - connection.Close(); + await connection.CloseAsync(); } Console.WriteLine(); } - public static void Handling_optional_dependents_sharing_table_with_principal_1() + public static async Task Handling_optional_dependents_sharing_table_with_principal_1() { Console.WriteLine($">>>> Sample: {nameof(Handling_optional_dependents_sharing_table_with_principal_1)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); + await Helpers.RecreateCleanDatabase(); using (var context = new SomeDbContext()) { @@ -134,12 +135,12 @@ public static void Handling_optional_dependents_sharing_table_with_principal_1() Console.WriteLine($" Dependent with only required properties is {(principal.DependentWithOnlyRequiredProperties != null ? "not " : "")}null."); Console.WriteLine($" Dependent with both optional and required properties is {(principal.DependentWithOptionalAndRequiredProperties != null ? "not " : "")}null."); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = new SomeDbContext()) { - var principal = context.PrincipalsWithOptionalDependents.Single(); + var principal = await context.PrincipalsWithOptionalDependents.SingleAsync(); Console.WriteLine("After querying back principal and dependents saved above:"); Console.WriteLine($" Dependent with only optional properties is {(principal.DependentWithOnlyOptionalProperties != null ? "not " : "")}null."); Console.WriteLine($" Dependent with only required properties is {(principal.DependentWithOnlyRequiredProperties != null ? "not " : "")}null."); @@ -149,12 +150,12 @@ public static void Handling_optional_dependents_sharing_table_with_principal_1() Console.WriteLine(); } - public static void Handling_optional_dependents_sharing_table_with_principal_2() + public static async Task Handling_optional_dependents_sharing_table_with_principal_2() { Console.WriteLine($">>>> Sample: {nameof(Handling_optional_dependents_sharing_table_with_principal_2)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); + await Helpers.RecreateCleanDatabase(); using (var context = new SomeDbContext()) { @@ -175,13 +176,13 @@ public static void Handling_optional_dependents_sharing_table_with_principal_2() Console.WriteLine(); Console.WriteLine("SaveChanges will warn:"); Console.WriteLine(); - context.SaveChanges(); + await context.SaveChangesAsync(); Console.WriteLine(); } using (var context = new SomeDbContext()) { - var principal = context.PrincipalsWithOptionalDependents.Single(); + var principal = await context.PrincipalsWithOptionalDependents.SingleAsync(); Console.WriteLine("After querying back principal and dependents saved above:"); Console.WriteLine($" Dependent with only optional properties is {(principal.DependentWithOnlyOptionalProperties != null ? "not " : "")}null. <-- Note dependent is null here."); Console.WriteLine($" Dependent with only required properties is {(principal.DependentWithOnlyRequiredProperties != null ? "not " : "")}null."); @@ -191,12 +192,12 @@ public static void Handling_optional_dependents_sharing_table_with_principal_2() Console.WriteLine(); } - public static void Handling_required_dependents_sharing_table_with_principal() + public static async Task Handling_required_dependents_sharing_table_with_principal() { Console.WriteLine($">>>> Sample: {nameof(Handling_required_dependents_sharing_table_with_principal)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); + await Helpers.RecreateCleanDatabase(); using (var context = new SomeDbContext()) { @@ -213,12 +214,12 @@ public static void Handling_required_dependents_sharing_table_with_principal() Console.WriteLine($" Dependent with only required properties is {(principal.DependentWithOnlyRequiredProperties != null ? "not " : "")}null."); Console.WriteLine($" Dependent with both optional and required properties is {(principal.DependentWithOptionalAndRequiredProperties != null ? "not " : "")}null."); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = new SomeDbContext()) { - var principal = context.PrincipalsWithRequiredDependents.Single(); + var principal = await context.PrincipalsWithRequiredDependents.SingleAsync(); Console.WriteLine("After querying back principal and dependents saved above:"); Console.WriteLine($" Dependent with only optional properties is {(principal.DependentWithOnlyOptionalProperties != null ? "not " : "")}null."); Console.WriteLine($" Dependent with only required properties is {(principal.DependentWithOnlyRequiredProperties != null ? "not " : "")}null."); @@ -228,12 +229,12 @@ public static void Handling_required_dependents_sharing_table_with_principal() Console.WriteLine(); } - public static void Handling_nested_optional_dependents_sharing_table_with_principal() + public static async Task Handling_nested_optional_dependents_sharing_table_with_principal() { Console.WriteLine($">>>> Sample: {nameof(Handling_nested_optional_dependents_sharing_table_with_principal)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); + await Helpers.RecreateCleanDatabase(); using (var context = new SomeDbContext()) { @@ -255,13 +256,13 @@ public static void Handling_nested_optional_dependents_sharing_table_with_princi Console.WriteLine(); Console.WriteLine("SaveChanges will warn:"); Console.WriteLine(); - context.SaveChanges(); + await context.SaveChangesAsync(); Console.WriteLine(); } using (var context = new SomeDbContext()) { - var principal = context.PrincipalsWithNestedOptionalDependents.Single(); + var principal = await context.PrincipalsWithNestedOptionalDependents.SingleAsync(); Console.WriteLine("After querying back principal and dependents saved above:"); Console.WriteLine($" Dependent with only optional properties is {(principal.DependentWithOptionalNestedDependents != null ? "not " : "")}null."); Console.WriteLine($" Nested dependent with only optional properties is {(principal.DependentWithOptionalNestedDependents?.Nested != null ? "not " : "")}null. <-- Note nested dependent is null here."); @@ -270,12 +271,12 @@ public static void Handling_nested_optional_dependents_sharing_table_with_princi Console.WriteLine(); } - public static void Handling_nested_required_dependents_sharing_table_with_principal() + public static async Task Handling_nested_required_dependents_sharing_table_with_principal() { Console.WriteLine($">>>> Sample: {nameof(Handling_nested_required_dependents_sharing_table_with_principal)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); + await Helpers.RecreateCleanDatabase(); using (var context = new SomeDbContext()) { @@ -293,12 +294,12 @@ public static void Handling_nested_required_dependents_sharing_table_with_princi Console.WriteLine($" Dependent with only optional properties is {(principal.DependentWithRequiredNestedDependents != null ? "not " : "")}null."); Console.WriteLine($" Nested dependent with only optional properties is {(principal.DependentWithRequiredNestedDependents?.Nested != null ? "not " : "")}null."); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = new SomeDbContext()) { - var principal = context.PrincipalsWithNestedRequiredDependents.Single(); + var principal = await context.PrincipalsWithNestedRequiredDependents.SingleAsync(); Console.WriteLine("After querying back principal and dependents saved above:"); Console.WriteLine($" Dependent with only optional properties is {(principal.DependentWithRequiredNestedDependents != null ? "not " : "")}null."); Console.WriteLine($" Nested dependent with only optional properties is {(principal.DependentWithRequiredNestedDependents?.Nested != null ? "not " : "")}null."); @@ -309,12 +310,12 @@ public static void Handling_nested_required_dependents_sharing_table_with_princi public static class Helpers { - public static void RecreateCleanDatabase() + public static async Task RecreateCleanDatabase() { using var context = new SomeDbContext(quiet: true); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } } diff --git a/samples/core/Miscellaneous/NewInEFCore6/PreConventionModelConfigurationSample.cs b/samples/core/Miscellaneous/NewInEFCore6/PreConventionModelConfigurationSample.cs index c3171b9833..20bde36622 100644 --- a/samples/core/Miscellaneous/NewInEFCore6/PreConventionModelConfigurationSample.cs +++ b/samples/core/Miscellaneous/NewInEFCore6/PreConventionModelConfigurationSample.cs @@ -2,19 +2,20 @@ using System.Collections.Generic; using System.Text.Json; using System.Text.Json.Serialization; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; public static class PreConventionModelConfigurationSample { - public static void Configure_property_types_and_value_converter_in_one_place() + public static async Task Configure_property_types_and_value_converter_in_one_place() { Console.WriteLine($">>>> Sample: {nameof(Configure_property_types_and_value_converter_in_one_place)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new CustomersContext(); @@ -23,15 +24,15 @@ public static void Configure_property_types_and_value_converter_in_one_place() public static class Helpers { - public static void RecreateCleanDatabase() + public static async Task RecreateCleanDatabase() { using var context = new CustomersContext(quiet: true); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } - public static void PopulateDatabase() + public static async Task PopulateDatabase() { using var context = new CustomersContext(quiet: true); @@ -69,7 +70,7 @@ public static void PopulateDatabase() Name = "Andrew", }); - context.SaveChanges(); + await context.SaveChangesAsync(); } } diff --git a/samples/core/Miscellaneous/NewInEFCore6/PrecisionAttributeSample.cs b/samples/core/Miscellaneous/NewInEFCore6/PrecisionAttributeSample.cs index 96dcc663c6..e33b510d39 100644 --- a/samples/core/Miscellaneous/NewInEFCore6/PrecisionAttributeSample.cs +++ b/samples/core/Miscellaneous/NewInEFCore6/PrecisionAttributeSample.cs @@ -1,42 +1,43 @@ using System; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; public static class PrecisionAttributeSample { - public static void Using_PrecisionAttribute() + public static async Task Using_PrecisionAttribute() { Console.WriteLine($">>>> Sample: {nameof(Using_PrecisionAttribute)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BooksContext(); - _ = context.Products.Single(e => e.Id == 1); + _ = await context.Products.SingleAsync(e => e.Id == 1); Console.WriteLine(); } public static class Helpers { - public static void RecreateCleanDatabase() + public static async Task RecreateCleanDatabase() { using var context = new BooksContext(); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } - public static void PopulateDatabase() + public static async Task PopulateDatabase() { using var context = new BooksContext(); context.Add(new Product { Price = 3.99m }); - context.SaveChanges(); + await context.SaveChangesAsync(); } } diff --git a/samples/core/Miscellaneous/NewInEFCore6/Program.cs b/samples/core/Miscellaneous/NewInEFCore6/Program.cs index 29d230a70f..baed816a8e 100644 --- a/samples/core/Miscellaneous/NewInEFCore6/Program.cs +++ b/samples/core/Miscellaneous/NewInEFCore6/Program.cs @@ -1,52 +1,54 @@ -public class Program +using System.Threading.Tasks; + +public class Program { - public static void Main() + public static async Task Main() { - EntityTypeConfigurationAttributeSample.Using_EntityTypeConfigurationAttribute(); - UnicodeAttributeSample.Using_UnicodeAttribute(); - PrecisionAttributeSample.Using_PrecisionAttribute(); - ToStringTranslationSample.Using_ToString_in_queries(); - RandomFunctionSample.Call_EF_Functions_Random(); - SparseColumnsSample.Use_sparse_columns(); - InMemoryRequiredPropertiesSample.Required_properties_validated_with_in_memory_database(); - InMemoryRequiredPropertiesSample.Required_property_validation_with_in_memory_database_can_be_disabled(); - IsNullOrWhitespaceSample.Translate_IsNullOrWhitespace(); - StringConcatSample.Concat_with_multiple_args(); - ArrayParametersSample.Array_parameters_are_logged_in_readable_form(); - TemporaryValuesSample.Explicit_temporary_values_can_be_stored_in_entity_instance_1(); - TemporaryValuesSample.Explicit_temporary_values_can_be_stored_in_entity_instance_2(); - TrailingUnderscoresSample.Backing_fields_with_trailing_underscores_are_matched(); - OptionalDependentsSample.Optional_dependents_with_a_required_property(); - OptionalDependentsSample.Optional_dependents_without_a_required_property(); - OptionalDependentsSample.Handling_optional_dependents_sharing_table_with_principal_1(); - OptionalDependentsSample.Handling_optional_dependents_sharing_table_with_principal_2(); - OptionalDependentsSample.Handling_required_dependents_sharing_table_with_principal(); - OptionalDependentsSample.Handling_nested_optional_dependents_sharing_table_with_principal(); - OptionalDependentsSample.Handling_nested_required_dependents_sharing_table_with_principal(); + await EntityTypeConfigurationAttributeSample.Using_EntityTypeConfigurationAttribute(); + await UnicodeAttributeSample.Using_UnicodeAttribute(); + await PrecisionAttributeSample.Using_PrecisionAttribute(); + await ToStringTranslationSample.Using_ToString_in_queries(); + await RandomFunctionSample.Call_EF_Functions_Random(); + await SparseColumnsSample.Use_sparse_columns(); + await InMemoryRequiredPropertiesSample.Required_properties_validated_with_in_memory_database(); + await InMemoryRequiredPropertiesSample.Required_property_validation_with_in_memory_database_can_be_disabled(); + await IsNullOrWhitespaceSample.Translate_IsNullOrWhitespace(); + await StringConcatSample.Concat_with_multiple_args(); + await ArrayParametersSample.Array_parameters_are_logged_in_readable_form(); + await TemporaryValuesSample.Explicit_temporary_values_can_be_stored_in_entity_instance_1(); + await TemporaryValuesSample.Explicit_temporary_values_can_be_stored_in_entity_instance_2(); + await TrailingUnderscoresSample.Backing_fields_with_trailing_underscores_are_matched(); + await OptionalDependentsSample.Optional_dependents_with_a_required_property(); + await OptionalDependentsSample.Optional_dependents_without_a_required_property(); + await OptionalDependentsSample.Handling_optional_dependents_sharing_table_with_principal_1(); + await OptionalDependentsSample.Handling_optional_dependents_sharing_table_with_principal_2(); + await OptionalDependentsSample.Handling_required_dependents_sharing_table_with_principal(); + await OptionalDependentsSample.Handling_nested_optional_dependents_sharing_table_with_principal(); + await OptionalDependentsSample.Handling_nested_required_dependents_sharing_table_with_principal(); PublicPooledDbContextFactorySample.Can_create_pooled_DbContext_factory(); DbContextFactorySample.Ignore_parameterless_constructor_when_creating_DbContext_from_factory(); DbContextFactorySample.AddDbContextFactory_also_registers_scoped_DbContext_instance(); - SplitQuerySample.Split_query_for_non_navigation_collections(); - SplitQuerySample.Last_column_in_ORDER_BY_removed_when_joining_for_collection(); - SubstringTranslationSample.Translate_Substring_with_single_parameter(); - BoolToStringTranslationSample.Translate_bool_to_string_on_SQL_Server(); - TagWithFileAndLineSample.Queries_can_be_tagged_with_filename_and_line_number(); - PreConventionModelConfigurationSample.Configure_property_types_and_value_converter_in_one_place(); - MathFTranslationSample.Translate_MathF_methods(); - TemporalTablesSample.Use_SQL_Server_temporal_tables(); - GroupBySample.Translate_GroupBy_followed_by_FirstOrDefault_over_group(); - HasConversionSample.Can_set_value_converter_type_using_generic_method(); + await SplitQuerySample.Split_query_for_non_navigation_collections(); + await SplitQuerySample.Last_column_in_ORDER_BY_removed_when_joining_for_collection(); + await SubstringTranslationSample.Translate_Substring_with_single_parameter(); + await BoolToStringTranslationSample.Translate_bool_to_string_on_SQL_Server(); + await TagWithFileAndLineSample.Queries_can_be_tagged_with_filename_and_line_number(); + await PreConventionModelConfigurationSample.Configure_property_types_and_value_converter_in_one_place(); + await MathFTranslationSample.Translate_MathF_methods(); + await TemporalTablesSample.Use_SQL_Server_temporal_tables(); + await GroupBySample.Translate_GroupBy_followed_by_FirstOrDefault_over_group(); + await HasConversionSample.Can_set_value_converter_type_using_generic_method(); MinimalApiSample.Add_a_DbContext_and_provider(); - ToInMemoryQuerySample.Can_query_keyless_types_from_in_memory_database(); - CommandSourceSample.Interceptors_get_the_source_of_the_command(); - ScaffoldingSample.Reverse_engineer_from_database(); - ManyToManyConfigurationSample.Many_to_many_relationships_may_need_less_configuration(); - ConvertNullsSample.Value_converters_can_convert_nulls(); - ColumnOrderSample.Can_use_ColumnAttribute_to_set_column_order(); + await ToInMemoryQuerySample.Can_query_keyless_types_from_in_memory_database(); + await CommandSourceSample.Interceptors_get_the_source_of_the_command(); + await ScaffoldingSample.Reverse_engineer_from_database(); + await ManyToManyConfigurationSample.Many_to_many_relationships_may_need_less_configuration(); + await ConvertNullsSample.Value_converters_can_convert_nulls(); + await ColumnOrderSample.Can_use_ColumnAttribute_to_set_column_order(); - SqliteSamples.SavepointsApi(); - SqliteSamples.ConnectionPooling(); - SqliteSamples.DateOnly_and_TimeOnly(); + await SqliteSamples.SavepointsApi(); + await SqliteSamples.ConnectionPooling(); + await SqliteSamples.DateOnly_and_TimeOnly(); // Note: this sample requires a full version of SQL Server. It does not work with LocalDb // ContainsFreeTextSample.Contains_with_non_string(); diff --git a/samples/core/Miscellaneous/NewInEFCore6/RandomFunctionSample.cs b/samples/core/Miscellaneous/NewInEFCore6/RandomFunctionSample.cs index 3ae68e3281..4716ce75cd 100644 --- a/samples/core/Miscellaneous/NewInEFCore6/RandomFunctionSample.cs +++ b/samples/core/Miscellaneous/NewInEFCore6/RandomFunctionSample.cs @@ -1,22 +1,23 @@ using System; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; public static class RandomFunctionSample { - public static void Call_EF_Functions_Random() + public static async Task Call_EF_Functions_Random() { Console.WriteLine($">>>> Sample: {nameof(Call_EF_Functions_Random)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BooksContext(); #region Query - var users = context.Users.Where(u => u.Popularity == (int)(EF.Functions.Random() * 4.0) + 1).ToList(); + var users = await context.Users.Where(u => u.Popularity == (int)(EF.Functions.Random() * 4.0) + 1).ToListAsync(); #endregion foreach (var user in users) @@ -29,15 +30,15 @@ public static void Call_EF_Functions_Random() public static class Helpers { - public static void RecreateCleanDatabase() + public static async Task RecreateCleanDatabase() { using var context = new BooksContext(quiet: true); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } - public static void PopulateDatabase() + public static async Task PopulateDatabase() { using var context = new BooksContext(quiet: true); @@ -51,7 +52,7 @@ public static void PopulateDatabase() new User { Popularity = 2, Username = "olive" }, new User { Popularity = 3, Username = "toast" }); - context.SaveChanges(); + await context.SaveChangesAsync(); } } diff --git a/samples/core/Miscellaneous/NewInEFCore6/ScaffoldingSample.cs b/samples/core/Miscellaneous/NewInEFCore6/ScaffoldingSample.cs index 8a3f68a2d3..58f39d147a 100644 --- a/samples/core/Miscellaneous/NewInEFCore6/ScaffoldingSample.cs +++ b/samples/core/Miscellaneous/NewInEFCore6/ScaffoldingSample.cs @@ -1,22 +1,23 @@ using System; using System.Collections.Generic; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; #nullable enable public static class ScaffoldingSample { - public static void Reverse_engineer_from_database() + public static async Task Reverse_engineer_from_database() { Console.WriteLine($">>>> Sample: {nameof(Reverse_engineer_from_database)}"); Console.WriteLine(); using var context = new BloggingWithNRTsContext(); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } - + // The code below was scaffolded from an existing database. // To replicate this, run this sample to create the database and then use the command line as documented in the text. diff --git a/samples/core/Miscellaneous/NewInEFCore6/SparseColumnsSample.cs b/samples/core/Miscellaneous/NewInEFCore6/SparseColumnsSample.cs index d3ceeb7bef..f99bf969c5 100644 --- a/samples/core/Miscellaneous/NewInEFCore6/SparseColumnsSample.cs +++ b/samples/core/Miscellaneous/NewInEFCore6/SparseColumnsSample.cs @@ -1,22 +1,23 @@ using System; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; public static class SparseColumnsSample { - public static void Use_sparse_columns() + public static async Task Use_sparse_columns() { Console.WriteLine($">>>> Sample: {nameof(Use_sparse_columns)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BooksContext(); #region Query - _ = context.Users.ToList(); + _ = await context.Users.ToListAsync(); #endregion Console.WriteLine(); @@ -24,15 +25,15 @@ public static void Use_sparse_columns() public static class Helpers { - public static void RecreateCleanDatabase() + public static async Task RecreateCleanDatabase() { using var context = new BooksContext(); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } - public static void PopulateDatabase() + public static async Task PopulateDatabase() { using var context = new BooksContext(); @@ -46,7 +47,7 @@ public static void PopulateDatabase() new ForumUser { Username = "olive" }, new ForumUser { Username = "toast" }); - context.SaveChanges(); + await context.SaveChangesAsync(); } } diff --git a/samples/core/Miscellaneous/NewInEFCore6/SplitQuerySample.cs b/samples/core/Miscellaneous/NewInEFCore6/SplitQuerySample.cs index 6ae9ffd1cd..3acf64a32d 100644 --- a/samples/core/Miscellaneous/NewInEFCore6/SplitQuerySample.cs +++ b/samples/core/Miscellaneous/NewInEFCore6/SplitQuerySample.cs @@ -1,18 +1,19 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; public static class SplitQuerySample { - public static void Split_query_for_non_navigation_collections() + public static async Task Split_query_for_non_navigation_collections() { Console.WriteLine($">>>> Sample: {nameof(Split_query_for_non_navigation_collections)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new CustomersContext(); @@ -21,7 +22,7 @@ public static void Split_query_for_non_navigation_collections() Console.WriteLine("Executed as a single query:"); #region SplitQuery1 - context.Customers + await context.Customers .Select( c => new { @@ -29,12 +30,12 @@ public static void Split_query_for_non_navigation_collections() Orders = c.Orders .Where(o => o.Id > 1) }) - .ToList(); + .ToListAsync(); #endregion Console.WriteLine(); Console.WriteLine("Executed as split queries:"); - context.Customers.AsSplitQuery().Select(c => new { c, Orders = c.Orders.Where(o => o.Id > 1) }).ToList(); + await context.Customers.AsSplitQuery().Select(c => new { c, Orders = c.Orders.Where(o => o.Id > 1) }).ToListAsync(); Console.WriteLine(); Console.WriteLine("LINQ query: 'context.Customers.Select(c => new { c, OrderDates = c.Orders.Where(o => o.Id > 1).Select(o => o.OrderDate) })'"); @@ -42,7 +43,7 @@ public static void Split_query_for_non_navigation_collections() Console.WriteLine("Executed as a single query:"); #region SplitQuery2 - context.Customers + await context.Customers .Select( c => new { @@ -51,12 +52,12 @@ public static void Split_query_for_non_navigation_collections() .Where(o => o.Id > 1) .Select(o => o.OrderDate) }) - .ToList(); + .ToListAsync(); #endregion Console.WriteLine(); Console.WriteLine("Executed as split queries:"); - context.Customers.AsSplitQuery().Select(c => new { c, OrderDates = c.Orders.Where(o => o.Id > 1).Select(o => o.OrderDate) }).ToList(); + await context.Customers.AsSplitQuery().Select(c => new { c, OrderDates = c.Orders.Where(o => o.Id > 1).Select(o => o.OrderDate) }).ToListAsync(); Console.WriteLine(); Console.WriteLine("LINQ query: 'context.Customers.Select(c => new { c, OrderDates = c.Orders.Where(o => o.Id > 1).Select(o => o.OrderDate).Distinct() })'"); @@ -64,7 +65,7 @@ public static void Split_query_for_non_navigation_collections() Console.WriteLine("Executed as a single query:"); #region SplitQuery3 - context.Customers + await context.Customers .Select( c => new { @@ -74,35 +75,35 @@ public static void Split_query_for_non_navigation_collections() .Select(o => o.OrderDate) .Distinct() }) - .ToList(); + .ToListAsync(); #endregion Console.WriteLine(); Console.WriteLine("Executed as split queries:"); - context.Customers.AsSplitQuery().Select(c => new { c, OrderDates = c.Orders.Where(o => o.Id > 1).Select(o => o.OrderDate).Distinct() }).ToList(); + await context.Customers.AsSplitQuery().Select(c => new { c, OrderDates = c.Orders.Where(o => o.Id > 1).Select(o => o.OrderDate).Distinct() }).ToListAsync(); Console.WriteLine(); } - public static void Last_column_in_ORDER_BY_removed_when_joining_for_collection() + public static async Task Last_column_in_ORDER_BY_removed_when_joining_for_collection() { Console.WriteLine($">>>> Sample: {nameof(Last_column_in_ORDER_BY_removed_when_joining_for_collection)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new CustomersContext(); #region OrderBy - context.Customers + await context.Customers .Select( e => new { e.Id, FirstOrder = e.Orders.Where(i => i.Id == 1).ToList() }) - .ToList(); + .ToListAsync(); #endregion Console.WriteLine(); @@ -110,15 +111,15 @@ public static void Last_column_in_ORDER_BY_removed_when_joining_for_collection() public static class Helpers { - public static void RecreateCleanDatabase() + public static async Task RecreateCleanDatabase() { using var context = new CustomersContext(quiet: true); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } - public static void PopulateDatabase() + public static async Task PopulateDatabase() { using var context = new CustomersContext(quiet: true); @@ -142,7 +143,7 @@ public static void PopulateDatabase() } }); - context.SaveChanges(); + await context.SaveChangesAsync(); } } diff --git a/samples/core/Miscellaneous/NewInEFCore6/SqliteSamples.cs b/samples/core/Miscellaneous/NewInEFCore6/SqliteSamples.cs index 228062f305..cf37803dea 100644 --- a/samples/core/Miscellaneous/NewInEFCore6/SqliteSamples.cs +++ b/samples/core/Miscellaneous/NewInEFCore6/SqliteSamples.cs @@ -1,57 +1,58 @@ using System; using System.Linq; +using System.Threading.Tasks; using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; public static class SqliteSamples { - public static void SavepointsApi() + public static async Task SavepointsApi() { Console.WriteLine($">>>> Sample: {nameof(SavepointsApi)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); Console.WriteLine("Before update:"); using (var context = new UsersContext()) { - foreach (var user in context.Users) + await foreach (var user in context.Users.AsAsyncEnumerable()) { Console.WriteLine($" Found '{user.Username}'"); } } - PerformUpdates(); + await PerformUpdates(); Console.WriteLine(); Console.WriteLine("After update:"); using (var context = new UsersContext()) { - foreach (var user in context.Users) + await foreach (var user in context.Users.AsAsyncEnumerable()) { Console.WriteLine($" Found '{user.Username}'"); } } } - public static void DateOnly_and_TimeOnly() + public static async Task DateOnly_and_TimeOnly() { Console.WriteLine($">>>> Sample: {nameof(DateOnly_and_TimeOnly)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new UsersContext(); #region DateOnlyQuery - var users = context.Users.Where(u => u.Birthday < new DateOnly(1900, 1, 1)).ToList(); + var users = await context.Users.Where(u => u.Birthday < new DateOnly(1900, 1, 1)).ToListAsync(); #endregion - + Console.WriteLine(); foreach (var user in users) @@ -59,47 +60,47 @@ public static void DateOnly_and_TimeOnly() Console.WriteLine($" Found '{user.Username}'"); user.Birthday = new(user.Birthday.Year + 100, user.Birthday.Month, user.Birthday.Day); } - + Console.WriteLine(); - context.SaveChanges(); + await context.SaveChangesAsync(); } - private static void PerformUpdates() + private static async Task PerformUpdates() { #region PerformUpdates using var connection = new SqliteConnection("Command Timeout=60;DataSource=test.db"); - connection.Open(); + await connection.OpenAsync(); - using var transaction = connection.BeginTransaction(); + await using var transaction = await connection.BeginTransactionAsync(); using (var command = connection.CreateCommand()) { command.CommandText = @"UPDATE Users SET Username = 'ajcvickers' WHERE Id = 1"; - command.ExecuteNonQuery(); + await command.ExecuteNonQueryAsync(); } - transaction.Save("MySavepoint"); + await transaction.SaveAsync("MySavepoint"); using (var command = connection.CreateCommand()) { command.CommandText = @"UPDATE Users SET Username = 'wfvickers' WHERE Id = 2"; - command.ExecuteNonQuery(); + await command.ExecuteNonQueryAsync(); } - transaction.Rollback("MySavepoint"); + await transaction.RollbackAsync("MySavepoint"); - transaction.Commit(); + await transaction.CommitAsync(); #endregion } - public static void ConnectionPooling() + public static async Task ConnectionPooling() { Console.WriteLine($">>>> Sample: {nameof(ConnectionPooling)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using (var context = new UsersContext(quiet: false, connectionEvents: true)) { @@ -107,7 +108,7 @@ public static void ConnectionPooling() Console.WriteLine("Starting query..."); Console.WriteLine(); - var users = context.Users.ToList(); + var users = await context.Users.ToListAsync(); Console.WriteLine(); Console.WriteLine("Query finished."); @@ -122,7 +123,7 @@ public static void ConnectionPooling() Console.WriteLine("Starting SaveChanges..."); Console.WriteLine(); - context.SaveChanges(); + await context.SaveChangesAsync(); Console.WriteLine(); Console.WriteLine("SaveChanges finished."); @@ -136,42 +137,42 @@ public static void ConnectionPooling() public static class Helpers { - public static void RecreateCleanDatabase() + public static async Task RecreateCleanDatabase() { using var context = new UsersContext(quiet: true); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } - public static void PopulateDatabase() + public static async Task PopulateDatabase() { using var context = new UsersContext(quiet: true); context.AddRange( new User { - Username = "arthur", + Username = "arthur", Birthday = new(1869, 9, 3), - TokensRenewed = new(16, 30) + TokensRenewed = new(16, 30) }, new User { Username = "wendy", Birthday = new(1873, 8, 3), - TokensRenewed = new(9, 25) + TokensRenewed = new(9, 25) }, new User { Username = "microsoft", Birthday = new(1975, 4, 4), - TokensRenewed = new(0, 0) + TokensRenewed = new(0, 0) }); - context.SaveChanges(); + await context.SaveChangesAsync(); context.ChangeTracker.Entries().First().Entity.Username = "ajcvickers"; - context.SaveChanges(); + await context.SaveChangesAsync(); } } @@ -180,7 +181,7 @@ public class User { public int Id { get; set; } public string Username { get; set; } - + public DateOnly Birthday { get; set; } public TimeOnly TokensRenewed { get; set; } } diff --git a/samples/core/Miscellaneous/NewInEFCore6/StringConcatSample.cs b/samples/core/Miscellaneous/NewInEFCore6/StringConcatSample.cs index a4d083d26e..aef1a414cb 100644 --- a/samples/core/Miscellaneous/NewInEFCore6/StringConcatSample.cs +++ b/samples/core/Miscellaneous/NewInEFCore6/StringConcatSample.cs @@ -1,24 +1,25 @@ using System; using System.ComponentModel.DataAnnotations; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; public static class StringConcatSample { - public static void Concat_with_multiple_args() + public static async Task Concat_with_multiple_args() { Console.WriteLine($">>>> Sample: {nameof(Concat_with_multiple_args)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BooksContext(); #region StringConcat - var shards = context.Shards - .Where(e => string.Concat(e.Token1, e.Token2, e.Token3) != e.TokensProcessed).ToList(); + var shards = await context.Shards + .Where(e => string.Concat(e.Token1, e.Token2, e.Token3) != e.TokensProcessed).ToListAsync(); #endregion foreach (var shard in shards) @@ -31,15 +32,15 @@ public static void Concat_with_multiple_args() public static class Helpers { - public static void RecreateCleanDatabase() + public static async Task RecreateCleanDatabase() { using var context = new BooksContext(quiet: true); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } - public static void PopulateDatabase() + public static async Task PopulateDatabase() { using var context = new BooksContext(quiet: true); @@ -79,7 +80,7 @@ public static void PopulateDatabase() TokensProcessed = "JAM" }); - context.SaveChanges(); + await context.SaveChangesAsync(); } } diff --git a/samples/core/Miscellaneous/NewInEFCore6/SubstringTranslationSample.cs b/samples/core/Miscellaneous/NewInEFCore6/SubstringTranslationSample.cs index 09f2c54a22..b8aadeb298 100644 --- a/samples/core/Miscellaneous/NewInEFCore6/SubstringTranslationSample.cs +++ b/samples/core/Miscellaneous/NewInEFCore6/SubstringTranslationSample.cs @@ -1,24 +1,25 @@ using System; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; public static class SubstringTranslationSample { - public static void Translate_Substring_with_single_parameter() + public static async Task Translate_Substring_with_single_parameter() { Console.WriteLine($">>>> Sample: {nameof(Translate_Substring_with_single_parameter)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new CustomersContext(); #region Substring - var result = context.Customers + var result = await context.Customers .Select(a => new { Name = a.Name.Substring(3) }) - .FirstOrDefault(a => a.Name == "hur"); + .FirstOrDefaultAsync(a => a.Name == "hur"); #endregion Console.WriteLine(); @@ -28,15 +29,15 @@ public static void Translate_Substring_with_single_parameter() public static class Helpers { - public static void RecreateCleanDatabase() + public static async Task RecreateCleanDatabase() { using var context = new CustomersContext(quiet: true); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } - public static void PopulateDatabase() + public static async Task PopulateDatabase() { using var context = new CustomersContext(quiet: true); @@ -54,7 +55,7 @@ public static void PopulateDatabase() Name = "Andrew" }); - context.SaveChanges(); + await context.SaveChangesAsync(); } } diff --git a/samples/core/Miscellaneous/NewInEFCore6/TagWithFileAndLineSample.cs b/samples/core/Miscellaneous/NewInEFCore6/TagWithFileAndLineSample.cs index 6d17211929..4ea6644323 100644 --- a/samples/core/Miscellaneous/NewInEFCore6/TagWithFileAndLineSample.cs +++ b/samples/core/Miscellaneous/NewInEFCore6/TagWithFileAndLineSample.cs @@ -1,51 +1,52 @@ using System; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; public static class TagWithFileAndLineSample { - public static void Queries_can_be_tagged_with_filename_and_line_number() + public static async Task Queries_can_be_tagged_with_filename_and_line_number() { Console.WriteLine($">>>> Sample: {nameof(Queries_can_be_tagged_with_filename_and_line_number)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new CustomersContext(); #region TagWithCallSite - var results1 = context + var results1 = await context .Customers .TagWithCallSite() .Where(c => c.Name.StartsWith("A")) - .ToList(); + .ToListAsync(); #endregion Console.WriteLine(); - var results2 = context + var results2 = await context .Customers .OrderBy(c => c.Name) .TagWith("Ordering query") .TagWithCallSite() - .ToList(); + .ToListAsync(); Console.WriteLine(); } public static class Helpers { - public static void RecreateCleanDatabase() + public static async Task RecreateCleanDatabase() { using var context = new CustomersContext(quiet: true); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } - public static void PopulateDatabase() + public static async Task PopulateDatabase() { using var context = new CustomersContext(quiet: true); @@ -63,7 +64,7 @@ public static void PopulateDatabase() Name = "Andrew", }); - context.SaveChanges(); + await context.SaveChangesAsync(); } } diff --git a/samples/core/Miscellaneous/NewInEFCore6/TemporalTablesSample.cs b/samples/core/Miscellaneous/NewInEFCore6/TemporalTablesSample.cs index fef92f1eb1..fcaf5f9362 100644 --- a/samples/core/Miscellaneous/NewInEFCore6/TemporalTablesSample.cs +++ b/samples/core/Miscellaneous/NewInEFCore6/TemporalTablesSample.cs @@ -1,17 +1,18 @@ using System; using System.Linq; using System.Threading; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; public static class TemporalTablesSample { - public static void Use_SQL_Server_temporal_tables() + public static async Task Use_SQL_Server_temporal_tables() { Console.WriteLine($">>>> Sample: {nameof(Use_SQL_Server_temporal_tables)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); + await Helpers.RecreateCleanDatabase(); DateTime timeStamp1; DateTime timeStamp2; @@ -47,7 +48,7 @@ public static void Use_SQL_Server_temporal_tables() AnnualSalary = 30.0m }); - context.SaveChanges(); + await context.SaveChangesAsync(); #endregion } @@ -56,7 +57,7 @@ public static void Use_SQL_Server_temporal_tables() Console.WriteLine(); Console.WriteLine("Starting data:"); - var employees = context.Employees.ToList(); + var employees = await context.Employees.ToListAsync(); foreach (var employee in employees) { var employeeEntry = context.Entry(employee); @@ -76,23 +77,23 @@ public static void Use_SQL_Server_temporal_tables() timeStamp1 = DateTime.UtcNow; Thread.Sleep(millisecondsDelay); - var employee = context.Employees.Single(e => e.Name == "Rainbow Dash"); + var employee = await context.Employees.SingleAsync(e => e.Name == "Rainbow Dash"); employee.Position = "Wonderbolt Trainee"; - context.SaveChanges(); + await context.SaveChangesAsync(); Thread.Sleep(millisecondsDelay); timeStamp2 = DateTime.UtcNow; Thread.Sleep(millisecondsDelay); employee.Position = "Wonderbolt Reservist"; - context.SaveChanges(); + await context.SaveChangesAsync(); Thread.Sleep(millisecondsDelay); timeStamp3 = DateTime.UtcNow; Thread.Sleep(millisecondsDelay); employee.Position = "Wonderbolt"; - context.SaveChanges(); + await context.SaveChangesAsync(); Thread.Sleep(millisecondsDelay); timeStamp4 = DateTime.UtcNow; @@ -102,9 +103,9 @@ public static void Use_SQL_Server_temporal_tables() using (var context = new EmployeeContext(quiet: true)) { #region NormalQuery - var employee = context.Employees.Single(e => e.Name == "Rainbow Dash"); + var employee = await context.Employees.SingleAsync(e => e.Name == "Rainbow Dash"); context.Remove(employee); - context.SaveChanges(); + await context.SaveChangesAsync(); #endregion } @@ -114,7 +115,7 @@ public static void Use_SQL_Server_temporal_tables() Console.WriteLine("After updates and delete:"); #region TrackingQuery - var employees = context.Employees.ToList(); + var employees = await context.Employees.ToListAsync(); foreach (var employee in employees) { var employeeEntry = context.Entry(employee); @@ -129,7 +130,7 @@ public static void Use_SQL_Server_temporal_tables() Console.WriteLine("Historical data for Rainbow Dash:"); #region TemporalAll - var history = context + var history = await context .Employees .TemporalAll() .Where(e => e.Name == "Rainbow Dash") @@ -141,7 +142,7 @@ public static void Use_SQL_Server_temporal_tables() ValidFrom = EF.Property(e, "ValidFrom"), ValidTo = EF.Property(e, "ValidTo") }) - .ToList(); + .ToListAsync(); foreach (var pointInTime in history) { @@ -157,7 +158,7 @@ public static void Use_SQL_Server_temporal_tables() Console.WriteLine($"Historical data for Rainbow Dash between {timeStamp2} and {timeStamp3}:"); #region TemporalBetween - var history = context + var history = await context .Employees .TemporalBetween(timeStamp2, timeStamp3) .Where(e => e.Name == "Rainbow Dash") @@ -169,7 +170,7 @@ public static void Use_SQL_Server_temporal_tables() ValidFrom = EF.Property(e, "ValidFrom"), ValidTo = EF.Property(e, "ValidTo") }) - .ToList(); + .ToListAsync(); #endregion foreach (var pointInTime in history) @@ -184,7 +185,7 @@ public static void Use_SQL_Server_temporal_tables() Console.WriteLine(); Console.WriteLine($"Historical data for Rainbow Dash as of {timeStamp2}:"); - var history = context + var history = await context .Employees .TemporalAsOf(timeStamp2) .Where(e => e.Name == "Rainbow Dash") @@ -196,7 +197,7 @@ public static void Use_SQL_Server_temporal_tables() ValidFrom = EF.Property(e, "ValidFrom"), ValidTo = EF.Property(e, "ValidTo") }) - .ToList(); + .ToListAsync(); foreach (var pointInTime in history) { @@ -211,19 +212,19 @@ public static void Use_SQL_Server_temporal_tables() Console.WriteLine($"Restoring Rainbow Dash from {timeStamp2}..."); #region RestoreData - var employee = context + var employee = await context .Employees .TemporalAsOf(timeStamp2) - .Single(e => e.Name == "Rainbow Dash"); + .SingleAsync(e => e.Name == "Rainbow Dash"); context.Add(employee); - context.SaveChanges(); + await context.SaveChangesAsync(); #endregion Console.WriteLine(); Console.WriteLine($"Historical data for Rainbow Dash between:"); - var history = context + var history = await context .Employees .TemporalAll() .Where(e => e.Name == "Rainbow Dash") @@ -235,7 +236,7 @@ public static void Use_SQL_Server_temporal_tables() ValidFrom = EF.Property(e, "ValidFrom"), ValidTo = EF.Property(e, "ValidTo") }) - .ToList(); + .ToListAsync(); foreach (var pointInTime in history) { @@ -249,16 +250,16 @@ public static void Use_SQL_Server_temporal_tables() public static class Helpers { - public static void RecreateCleanDatabase() + public static async Task RecreateCleanDatabase() { using (var context = new EmployeeContext(quiet: true)) { - context.Database.EnsureDeleted(); + await context.Database.EnsureDeletedAsync(); } using (var context = new EmployeeContext()) { - context.Database.EnsureCreated(); + await context.Database.EnsureCreatedAsync(); } } } diff --git a/samples/core/Miscellaneous/NewInEFCore6/TemporaryValuesSample.cs b/samples/core/Miscellaneous/NewInEFCore6/TemporaryValuesSample.cs index fc120a4a01..d64e42180d 100644 --- a/samples/core/Miscellaneous/NewInEFCore6/TemporaryValuesSample.cs +++ b/samples/core/Miscellaneous/NewInEFCore6/TemporaryValuesSample.cs @@ -1,16 +1,17 @@ using System; using System.Collections.Generic; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; public static class TemporaryValuesSample { - public static void Explicit_temporary_values_can_be_stored_in_entity_instance_1() + public static async Task Explicit_temporary_values_can_be_stored_in_entity_instance_1() { Console.WriteLine($">>>> Sample: {nameof(Explicit_temporary_values_can_be_stored_in_entity_instance_1)}"); Console.WriteLine(">>>> Shows using explicit temporary values with FK values to relate posts to a blog."); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); + await Helpers.RecreateCleanDatabase(); using var context = new SomeDbContext(); @@ -30,7 +31,7 @@ public static void Explicit_temporary_values_can_be_stored_in_entity_instance_1( Console.WriteLine(); Console.WriteLine("SavingChanges..."); - context.SaveChanges(); + await context.SaveChangesAsync(); Console.WriteLine(); Console.WriteLine($"Blog has ID = {blog.Id}"); @@ -40,13 +41,13 @@ public static void Explicit_temporary_values_can_be_stored_in_entity_instance_1( Console.WriteLine(); } - public static void Explicit_temporary_values_can_be_stored_in_entity_instance_2() + public static async Task Explicit_temporary_values_can_be_stored_in_entity_instance_2() { Console.WriteLine($">>>> Sample: {nameof(Explicit_temporary_values_can_be_stored_in_entity_instance_2)}"); Console.WriteLine(">>>> Shows taking generated temporary values and setting them into entity instances."); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); + await Helpers.RecreateCleanDatabase(); using var context = new SomeDbContext(); @@ -87,7 +88,7 @@ public static void Explicit_temporary_values_can_be_stored_in_entity_instance_2( Console.WriteLine(); Console.WriteLine("SavingChanges..."); - context.SaveChanges(); + await context.SaveChangesAsync(); Console.WriteLine(); Console.WriteLine($"Blog has ID = {blog.Id}"); @@ -99,12 +100,12 @@ public static void Explicit_temporary_values_can_be_stored_in_entity_instance_2( public static class Helpers { - public static void RecreateCleanDatabase() + public static async Task RecreateCleanDatabase() { using var context = new SomeDbContext(quiet: true); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } } diff --git a/samples/core/Miscellaneous/NewInEFCore6/ToInMemoryQuerySample.cs b/samples/core/Miscellaneous/NewInEFCore6/ToInMemoryQuerySample.cs index 4ae762f70f..83311eff9d 100644 --- a/samples/core/Miscellaneous/NewInEFCore6/ToInMemoryQuerySample.cs +++ b/samples/core/Miscellaneous/NewInEFCore6/ToInMemoryQuerySample.cs @@ -1,20 +1,21 @@ using System; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; public static class ToInMemoryQuerySample { - public static void Can_query_keyless_types_from_in_memory_database() + public static async Task Can_query_keyless_types_from_in_memory_database() { Console.WriteLine($">>>> Sample: {nameof(Can_query_keyless_types_from_in_memory_database)}"); Console.WriteLine(); - Helpers.PopulateDatabase(); + await Helpers.PopulateDatabase(); using var context = new CustomerContext(); #region Query - var results = context.CustomerDensities.ToList(); + var results = await context.CustomerDensities.ToListAsync(); #endregion foreach (var customerDensity in results) @@ -27,7 +28,7 @@ public static void Can_query_keyless_types_from_in_memory_database() public static class Helpers { - public static void PopulateDatabase() + public static async Task PopulateDatabase() { using var context = new CustomerContext(); @@ -109,7 +110,7 @@ public static void PopulateDatabase() Postcode = "MK3 2ND", } }); - context.SaveChanges(); + await context.SaveChangesAsync(); } } @@ -120,7 +121,7 @@ public class CustomerDensity public int CustomerCount { get; set; } } #endregion - + #region EntityTypes public class Customer { diff --git a/samples/core/Miscellaneous/NewInEFCore6/ToStringTranslationSample.cs b/samples/core/Miscellaneous/NewInEFCore6/ToStringTranslationSample.cs index a6c55ee0a1..bdc513cf97 100644 --- a/samples/core/Miscellaneous/NewInEFCore6/ToStringTranslationSample.cs +++ b/samples/core/Miscellaneous/NewInEFCore6/ToStringTranslationSample.cs @@ -1,22 +1,23 @@ using System; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; public static class ToStringTranslationSample { - public static void Using_ToString_in_queries() + public static async Task Using_ToString_in_queries() { Console.WriteLine($">>>> Sample: {nameof(Using_ToString_in_queries)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BooksContext(); #region Query - var users = context.Users.Where(u => EF.Functions.Like(u.PhoneNumber.ToString(), "%555%")).ToList(); + var users = await context.Users.Where(u => EF.Functions.Like(u.PhoneNumber.ToString(), "%555%")).ToListAsync(); #endregion foreach (var user in users) @@ -29,15 +30,15 @@ public static void Using_ToString_in_queries() public static class Helpers { - public static void RecreateCleanDatabase() + public static async Task RecreateCleanDatabase() { using var context = new BooksContext(quiet: true); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } - public static void PopulateDatabase() + public static async Task PopulateDatabase() { using var context = new BooksContext(quiet: true); @@ -46,7 +47,7 @@ public static void PopulateDatabase() new User { PhoneNumber = 5155552234, Username = "wendy" }, new User { PhoneNumber = 18005525123, Username = "microsoft" }); - context.SaveChanges(); + await context.SaveChangesAsync(); } } diff --git a/samples/core/Miscellaneous/NewInEFCore6/TrailingUnderscoresSample.cs b/samples/core/Miscellaneous/NewInEFCore6/TrailingUnderscoresSample.cs index ed730ca078..13f3520cb8 100644 --- a/samples/core/Miscellaneous/NewInEFCore6/TrailingUnderscoresSample.cs +++ b/samples/core/Miscellaneous/NewInEFCore6/TrailingUnderscoresSample.cs @@ -1,14 +1,15 @@ using System; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; public static class TrailingUnderscoresSample { - public static void Backing_fields_with_trailing_underscores_are_matched() + public static async Task Backing_fields_with_trailing_underscores_are_matched() { Console.WriteLine($">>>> Sample: {nameof(Backing_fields_with_trailing_underscores_are_matched)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); + await Helpers.RecreateCleanDatabase(); using var context = new SomeDbContext(); @@ -25,12 +26,12 @@ public static void Backing_fields_with_trailing_underscores_are_matched() public static class Helpers { - public static void RecreateCleanDatabase() + public static async Task RecreateCleanDatabase() { using var context = new SomeDbContext(quiet: true); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } } diff --git a/samples/core/Miscellaneous/NewInEFCore6/UnicodeAttributeSample.cs b/samples/core/Miscellaneous/NewInEFCore6/UnicodeAttributeSample.cs index a3648f8acb..273ec9c6fe 100644 --- a/samples/core/Miscellaneous/NewInEFCore6/UnicodeAttributeSample.cs +++ b/samples/core/Miscellaneous/NewInEFCore6/UnicodeAttributeSample.cs @@ -1,44 +1,45 @@ using System; using System.ComponentModel.DataAnnotations; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; public static class UnicodeAttributeSample { - public static void Using_UnicodeAttribute() + public static async Task Using_UnicodeAttribute() { Console.WriteLine($">>>> Sample: {nameof(Using_UnicodeAttribute)}"); Console.WriteLine(); - Helpers.RecreateCleanDatabase(); - Helpers.PopulateDatabase(); + await Helpers.RecreateCleanDatabase(); + await Helpers.PopulateDatabase(); using var context = new BooksContext(); - var book = context.Books.Single(e => e.Id == 1); + var book = await context.Books.SingleAsync(e => e.Id == 1); Console.WriteLine(); } public static class Helpers { - public static void RecreateCleanDatabase() + public static async Task RecreateCleanDatabase() { using var context = new BooksContext(); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } - public static void PopulateDatabase() + public static async Task PopulateDatabase() { using var context = new BooksContext(); context.Add( new Book() { Isbn = "978-0-39-481823-8", Title = "What Do People Do All Day?" }); - context.SaveChanges(); + await context.SaveChangesAsync(); } } diff --git a/samples/core/Miscellaneous/NewInEFCore7/ModelBuildingConventionsSample.cs b/samples/core/Miscellaneous/NewInEFCore7/ModelBuildingConventionsSample.cs index 06a2a23681..8e8c34c3b5 100644 --- a/samples/core/Miscellaneous/NewInEFCore7/ModelBuildingConventionsSample.cs +++ b/samples/core/Miscellaneous/NewInEFCore7/ModelBuildingConventionsSample.cs @@ -66,10 +66,10 @@ private static async Task ConventionsTest() Console.WriteLine(context.Model.ToDebugString()); - var blogs = context.Blogs + var blogs = await context.Blogs .Include(blog => blog.Posts).ThenInclude(post => post.Author) .Include(blog => blog.Posts).ThenInclude(post => post.Tags) - .ToList(); + .ToListAsync(); blogs[0].Name += "Changed"; blogs[1].Posts[2].Content += "Changed"; diff --git a/samples/core/Miscellaneous/NewInEFCore7/TpcInheritanceSample.cs b/samples/core/Miscellaneous/NewInEFCore7/TpcInheritanceSample.cs index ecebf60bd7..436316a1a0 100644 --- a/samples/core/Miscellaneous/NewInEFCore7/TpcInheritanceSample.cs +++ b/samples/core/Miscellaneous/NewInEFCore7/TpcInheritanceSample.cs @@ -115,7 +115,7 @@ public static async Task ManyToManyTest() context.Remove(context.Animals.Local.Single(e => e.Name == "Christi")); context.Humans.Local.Single(e => e.Name == "Wendy").Food = new HumanFood("White pizza", 400); - var sushi = context.Foods.OfType().Single(e => e.Name == "Sushi"); + var sushi = await context.Foods.OfType().SingleAsync(e => e.Name == "Sushi"); sushi.Calories -= 100; await context.SaveChangesAsync(); diff --git a/samples/core/Miscellaneous/NewInEFCore9/NewInEFCore9.csproj b/samples/core/Miscellaneous/NewInEFCore9/NewInEFCore9.csproj index 39476a1f38..02b03bce32 100644 --- a/samples/core/Miscellaneous/NewInEFCore9/NewInEFCore9.csproj +++ b/samples/core/Miscellaneous/NewInEFCore9/NewInEFCore9.csproj @@ -20,6 +20,7 @@ + diff --git a/samples/core/Miscellaneous/NewInEFCore9/NullSemanticsSample.cs b/samples/core/Miscellaneous/NewInEFCore9/NullSemanticsSample.cs index 7285911c3d..69225c523c 100644 --- a/samples/core/Miscellaneous/NewInEFCore9/NullSemanticsSample.cs +++ b/samples/core/Miscellaneous/NewInEFCore9/NullSemanticsSample.cs @@ -35,7 +35,7 @@ private static async Task NullSemanticsInComparisonTest() .Select(x => new { x.NullableIntOne, x.NullableIntTwo }).ToListAsync(); #endregion - var negatedNullableComparisonFilterL2O = context.Entities.AsEnumerable().Where(x => !(x.NullableIntOne > x.NullableIntTwo)).Select(x => new { x.NullableIntOne, x.NullableIntTwo }).ToList(); + var negatedNullableComparisonFilterL2O = await context.Entities.AsAsyncEnumerable().Where(x => !(x.NullableIntOne > x.NullableIntTwo)).Select(x => new { x.NullableIntOne, x.NullableIntTwo }).ToListAsync(); #region NullableComparisonProjection var nullableComparisonProjection = await context.Entities.Select(x => new @@ -46,7 +46,7 @@ private static async Task NullSemanticsInComparisonTest() }).ToListAsync(); #endregion - var nullableComparisonProjectionL2O = context.Entities.AsEnumerable().Select(x => new { x.NullableIntOne, x.NullableIntTwo, Operation = x.NullableIntOne > x.NullableIntTwo }).ToList(); + var nullableComparisonProjectionL2O = await context.Entities.AsAsyncEnumerable().Select(x => new { x.NullableIntOne, x.NullableIntTwo, Operation = x.NullableIntOne > x.NullableIntTwo }).ToListAsync(); #region NegatedNullableComparisonProjection var negatedNullableComparisonProjection = await context.Entities.Select(x => new @@ -57,7 +57,7 @@ private static async Task NullSemanticsInComparisonTest() }).ToListAsync(); #endregion - var negatedNullableComparisonProjectionL2O = context.Entities.AsEnumerable().Select(x => new { x.NullableIntOne, x.NullableIntTwo, Operation = !(x.NullableIntOne > x.NullableIntTwo) }).ToList(); + var negatedNullableComparisonProjectionL2O = await context.Entities.AsAsyncEnumerable().Select(x => new { x.NullableIntOne, x.NullableIntTwo, Operation = !(x.NullableIntOne > x.NullableIntTwo) }).ToListAsync(); } private static void PrintSampleName([CallerMemberName] string? methodName = null) diff --git a/samples/core/Miscellaneous/NewInEFCore9/QuerySample.cs b/samples/core/Miscellaneous/NewInEFCore9/QuerySample.cs index a51ea1ad9e..1c1ac72f24 100644 --- a/samples/core/Miscellaneous/NewInEFCore9/QuerySample.cs +++ b/samples/core/Miscellaneous/NewInEFCore9/QuerySample.cs @@ -96,11 +96,11 @@ async Task> GetPostsForceConstantCollection(int[] ids) .Posts .Where(p => p.Title.Contains(".NET")); - var results = dotnetPosts + var results = await dotnetPosts .Where(p => p.Id > 2) .Select(p => new { Post = p, TotalCount = dotnetPosts.Count() }) .Skip(2).Take(10) - .ToArray(); + .ToArrayAsync(); #endregion Console.WriteLine(); diff --git a/samples/core/Miscellaneous/NullableReferenceTypes/Program.cs b/samples/core/Miscellaneous/NullableReferenceTypes/Program.cs index 450f3589bd..cfd362f67a 100644 --- a/samples/core/Miscellaneous/NullableReferenceTypes/Program.cs +++ b/samples/core/Miscellaneous/NullableReferenceTypes/Program.cs @@ -1,17 +1,18 @@ using System; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace NullableReferenceTypes { public static class Program { - private static void Main(string[] args) + private static async Task Main(string[] args) { using (var context = new NullableReferenceTypesContext()) { - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); context.Add(new Customer("John", "Doe")); @@ -26,19 +27,19 @@ private static void Main(string[] args) } }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = new NullableReferenceTypesContext()) { - var john = context.Customers.First(c => c.FirstName == "John"); + var john = await context.Customers.FirstAsync(c => c.FirstName == "John"); Console.WriteLine("John's last name: " + john.LastName); #region Including - var order = context.Orders + var order = await context.Orders .Include(o => o.OptionalInfo!) .ThenInclude(op => op.ExtraAdditionalInfo) - .Single(); + .SingleAsync(); #endregion // The following would be a programming bug: we forgot to include ShippingAddress above. It would throw InvalidOperationException. diff --git a/samples/core/Miscellaneous/SaveChangesInterception/Program.cs b/samples/core/Miscellaneous/SaveChangesInterception/Program.cs index cdc019b77c..32bc224c8e 100644 --- a/samples/core/Miscellaneous/SaveChangesInterception/Program.cs +++ b/samples/core/Miscellaneous/SaveChangesInterception/Program.cs @@ -22,13 +22,13 @@ public static async Task Main() using (var context = new BlogsContext()) { - var blog = context.Blogs.Include(e => e.Posts).Single(); + var blog = await context.Blogs.Include(e => e.Posts).SingleAsync(); blog.Name = "EF Core Blog"; context.Remove(blog.Posts.First()); blog.Posts.Add(new Post { Title = "EF Core 6.0!" }); - context.SaveChanges(); + await context.SaveChangesAsync(); } // Do an insert that will fail @@ -50,7 +50,7 @@ public static async Task Main() using (var context = new AuditContext("DataSource=audit.db")) { - foreach (var audit in context.SaveChangesAudits.Include(e => e.Entities).ToList()) + foreach (var audit in await context.SaveChangesAudits.Include(e => e.Entities).ToListAsync()) { Console.WriteLine( $"Audit {audit.AuditId} from {audit.StartTime} to {audit.EndTime} was{(audit.Succeeded ? "" : " not")} successful."); diff --git a/samples/core/Modeling/BulkConfiguration/ModelBuildingConventionsSample.cs b/samples/core/Modeling/BulkConfiguration/ModelBuildingConventionsSample.cs index de9d809485..64bcd9d526 100644 --- a/samples/core/Modeling/BulkConfiguration/ModelBuildingConventionsSample.cs +++ b/samples/core/Modeling/BulkConfiguration/ModelBuildingConventionsSample.cs @@ -58,10 +58,10 @@ private static async Task ConventionsTest() Console.WriteLine(context.Model.ToDebugString()); - var blogs = context.Blogs + var blogs = await context.Blogs .Include(blog => blog.Posts).ThenInclude(post => post.Author) .Include(blog => blog.Posts).ThenInclude(post => post.Tags) - .ToList(); + .ToListAsync(); blogs[0].Name += "Changed"; blogs[1].Posts[2].Content += "Changed"; diff --git a/samples/core/Modeling/BulkConfiguration/Program.cs b/samples/core/Modeling/BulkConfiguration/Program.cs index 7ca48021da..40106b60b0 100644 --- a/samples/core/Modeling/BulkConfiguration/Program.cs +++ b/samples/core/Modeling/BulkConfiguration/Program.cs @@ -14,12 +14,12 @@ private static async Task Main() using (var context = new MetadataAPIContext()) { - RoundtripValue(context); + await RoundtripValue(context); } using (var context = new PreConventionContext()) { - RoundtripValue(context); + await RoundtripValue(context); } await ModelBuildingConventionsSample.No_foreign_key_index_convention(); @@ -31,13 +31,13 @@ private static async Task Main() Console.WriteLine("Sample finished."); } - private static void RoundtripValue(DbContext context) + private static async Task RoundtripValue(DbContext context) { Console.WriteLine("Using " + context.GetType().Name); Console.WriteLine("Deleting and re-creating database..."); Console.WriteLine(); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); Console.WriteLine(); Console.WriteLine("Done. Database is clean and fresh."); @@ -47,10 +47,10 @@ private static void RoundtripValue(DbContext context) Console.WriteLine("Save a new product with price: " + product.Price.Amount); Console.WriteLine(); - context.SaveChanges(); + await context.SaveChangesAsync(); Console.WriteLine(); - Console.WriteLine("Read the entity back with price: " + context.Set().Single().Price.Amount); + Console.WriteLine("Read the entity back with price: " + (await context.Set().SingleAsync()).Price.Amount); Console.WriteLine(); } } diff --git a/samples/core/Modeling/DataSeeding/Program.cs b/samples/core/Modeling/DataSeeding/Program.cs index a6fe5d9bc5..2e9c2cbd9c 100644 --- a/samples/core/Modeling/DataSeeding/Program.cs +++ b/samples/core/Modeling/DataSeeding/Program.cs @@ -1,18 +1,19 @@ using System; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace EFModeling.DataSeeding; internal static class Program { - private static void Main(string[] args) + private static async Task Main(string[] args) { using (var context = new ManagingDataContext()) { - context.Database.EnsureCreated(); + await context.Database.EnsureCreatedAsync(); - foreach (var country in context.Countries.Include(b => b.OfficialLanguages)) + await foreach (var country in context.Countries.Include(b => b.OfficialLanguages).AsAsyncEnumerable()) { Console.WriteLine($"{country.Name} official language(s):"); @@ -30,20 +31,20 @@ private static void Main(string[] args) #region CustomSeeding using (var context = new DataSeedingContext()) { - context.Database.EnsureCreated(); + await context.Database.EnsureCreatedAsync(); - var testBlog = context.Blogs.FirstOrDefault(b => b.Url == "http://test.com"); + var testBlog = await context.Blogs.FirstOrDefaultAsync(b => b.Url == "http://test.com"); if (testBlog == null) { context.Blogs.Add(new Blog { Url = "http://test.com" }); - context.SaveChanges(); + await context.SaveChangesAsync(); } } #endregion using (var context = new DataSeedingContext()) { - foreach (var blog in context.Blogs.Include(b => b.Posts)) + await foreach (var blog in context.Blogs.Include(b => b.Posts).AsAsyncEnumerable()) { Console.WriteLine($"Blog {blog.Url}"); diff --git a/samples/core/Modeling/DynamicModel/Program.cs b/samples/core/Modeling/DynamicModel/Program.cs index f51f9df5be..37b5bc9866 100644 --- a/samples/core/Modeling/DynamicModel/Program.cs +++ b/samples/core/Modeling/DynamicModel/Program.cs @@ -1,29 +1,31 @@ using System; using System.Linq; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; namespace EFModeling.DynamicModel; public class Program { - private static void Main() + private static async Task Main() { // Note that because this sample uses InMemory as its provider, each model gets it's own separate store. using (var context = new DynamicContext { UseIntProperty = true }) { context.Entities.Add(new ConfigurableEntity { IntProperty = 44, StringProperty = "Aloha" }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = new DynamicContext { UseIntProperty = false }) { context.Entities.Add(new ConfigurableEntity { IntProperty = 43, StringProperty = "Hola" }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = new DynamicContext { UseIntProperty = true }) { - var entity = context.Entities.Single(); + var entity = await context.Entities.SingleAsync(); // Writes 44 and an empty string Console.WriteLine($"{entity.IntProperty} {entity.StringProperty}"); @@ -31,10 +33,10 @@ private static void Main() using (var context = new DynamicContext { UseIntProperty = false }) { - var entity = context.Entities.Single(); + var entity = await context.Entities.SingleAsync(); // Writes 0 and an "Hola" Console.WriteLine($"{entity.IntProperty} {entity.StringProperty}"); } } -} \ No newline at end of file +} diff --git a/samples/core/Modeling/EntityTypes/Program.cs b/samples/core/Modeling/EntityTypes/Program.cs index 5981aa1def..c6bf4209ec 100644 --- a/samples/core/Modeling/EntityTypes/Program.cs +++ b/samples/core/Modeling/EntityTypes/Program.cs @@ -1,17 +1,18 @@ using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace EFModeling.EntityTypes; internal class Program { - private static void Main(string[] args) + private static async Task Main(string[] args) { using var context = new MyContextWithFunctionMapping(); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); - context.Database.ExecuteSqlRaw( + await context.Database.ExecuteSqlRawAsync( @"CREATE FUNCTION dbo.BlogsWithMultiplePosts() RETURNS TABLE AS @@ -29,6 +30,6 @@ HAVING COUNT(p.BlogId) > 1 where b.PostCount > 3 select new { b.Url, b.PostCount }; #endregion - var result = query.ToList(); + var result = await query.ToListAsync(); } -} \ No newline at end of file +} diff --git a/samples/core/Modeling/KeylessEntityTypes/Program.cs b/samples/core/Modeling/KeylessEntityTypes/Program.cs index 6a13a2937b..eeddf268fa 100644 --- a/samples/core/Modeling/KeylessEntityTypes/Program.cs +++ b/samples/core/Modeling/KeylessEntityTypes/Program.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; @@ -10,14 +11,14 @@ namespace EFModeling.KeylessEntityTypes; public class Program { - private static void Main() + private static async Task Main() { - SetupDatabase(); + await SetupDatabase(); using var db = new BloggingContext(); #region Query - var postCounts = db.BlogPostCounts.ToList(); + var postCounts = await db.BlogPostCounts.ToListAsync(); foreach (var postCount in postCounts) { @@ -27,11 +28,11 @@ private static void Main() #endregion } - private static void SetupDatabase() + private static async Task SetupDatabase() { using var db = new BloggingContext(); - if (db.Database.EnsureCreated()) + if (await db.Database.EnsureCreatedAsync()) { db.Blogs.Add( new Blog @@ -70,10 +71,10 @@ private static void SetupDatabase() } }); - db.SaveChanges(); + await db.SaveChangesAsync(); #region View - db.Database.ExecuteSqlRaw( + await db.Database.ExecuteSqlRawAsync( @"CREATE VIEW View_BlogPostCounts AS SELECT b.Name, Count(p.PostId) as PostCount FROM Blogs b diff --git a/samples/core/Modeling/OwnedEntities/Program.cs b/samples/core/Modeling/OwnedEntities/Program.cs index 85e628f5a7..f0861fb10d 100644 --- a/samples/core/Modeling/OwnedEntities/Program.cs +++ b/samples/core/Modeling/OwnedEntities/Program.cs @@ -1,16 +1,18 @@ using System; using System.Linq; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; namespace EFModeling.OwnedEntities; public static class Program { - private static void Main(string[] args) + private static async Task Main(string[] args) { using (var context = new OwnedEntityContext()) { - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); context.Add( new DetailedOrder @@ -23,15 +25,15 @@ private static void Main(string[] args) } }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = new OwnedEntityContext()) { #region DetailedOrderQuery - var order = context.DetailedOrders.First(o => o.Status == OrderStatus.Pending); + var order = await context.DetailedOrders.FirstAsync(o => o.Status == OrderStatus.Pending); Console.WriteLine($"First pending order will ship to: {order.OrderDetails.ShippingAddress.City}"); #endregion } } -} \ No newline at end of file +} diff --git a/samples/core/Modeling/Relationships/ManyToMany.cs b/samples/core/Modeling/Relationships/ManyToMany.cs index ac37a5e25f..2b566ecd6e 100644 --- a/samples/core/Modeling/Relationships/ManyToMany.cs +++ b/samples/core/Modeling/Relationships/ManyToMany.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace EFModeling.Relationships; @@ -1386,11 +1387,11 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) public class DirectJoinTableNoManyToMany { - public static void BuildModels() + public static async Task BuildModels() { using var context0 = new BlogContext0(); - context0.Database.EnsureDeleted(); - context0.Database.EnsureCreated(); + await context0.Database.EnsureDeletedAsync(); + await context0.Database.EnsureCreatedAsync(); Console.WriteLine("Directly mapping the join table without creating a many-to-many relationship:"); var modelDebugString = context0.Model.ToDebugString(indent: 2); @@ -1439,11 +1440,11 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) public class FullMappingWithJoinEntity { - public static void BuildModels() + public static async Task BuildModels() { using var context0 = new BlogContext0(); - context0.Database.EnsureDeleted(); - context0.Database.EnsureCreated(); + await context0.Database.EnsureDeletedAsync(); + await context0.Database.EnsureCreatedAsync(); Console.WriteLine("Directly mapping the join table and including skip navigations for the many-to-many relationship:"); var modelDebugString = context0.Model.ToDebugString(indent: 2); diff --git a/samples/core/Modeling/Relationships/Program.cs b/samples/core/Modeling/Relationships/Program.cs index 12d96f7677..31ecbc117f 100644 --- a/samples/core/Modeling/Relationships/Program.cs +++ b/samples/core/Modeling/Relationships/Program.cs @@ -1,8 +1,10 @@ +using System.Threading.Tasks; + namespace EFModeling.Relationships; public class Program { - private static void Main() + private static async Task Main() { OneToMany.Required.BuildModels(); OneToMany.Optional.BuildModels(); @@ -76,8 +78,8 @@ private static void Main() ManyToMany.SelfReferencingManyToMany.BuildModels(); ManyToMany.SelfReferencingUnidirectionalManyToMany.BuildModels(); ManyToMany.ManyToManyWithCustomSharedTypeEntityType.BuildModels(); - ManyToMany.DirectJoinTableNoManyToMany.BuildModels(); - ManyToMany.FullMappingWithJoinEntity.BuildModels(); + await ManyToMany.DirectJoinTableNoManyToMany.BuildModels(); + await ManyToMany.FullMappingWithJoinEntity.BuildModels(); RelationshipConventions.ReferenceNavigations.BuildModels(); RelationshipConventions.CollectionNavigations.BuildModels(); diff --git a/samples/core/Modeling/TableSplitting/Program.cs b/samples/core/Modeling/TableSplitting/Program.cs index b724ac0a50..ee981e3b10 100644 --- a/samples/core/Modeling/TableSplitting/Program.cs +++ b/samples/core/Modeling/TableSplitting/Program.cs @@ -1,17 +1,19 @@ using System; using System.Linq; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; namespace EFModeling.TableSplitting; public static class Program { - private static void Main(string[] args) + private static async Task Main(string[] args) { #region Usage using (var context = new TableSplittingContext()) { - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); context.Add( new Order @@ -25,20 +27,20 @@ private static void Main(string[] args) } }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = new TableSplittingContext()) { - var pendingCount = context.Orders.Count(o => o.Status == OrderStatus.Pending); + var pendingCount = await context.Orders.CountAsync(o => o.Status == OrderStatus.Pending); Console.WriteLine($"Current number of pending orders: {pendingCount}"); } using (var context = new TableSplittingContext()) { - var order = context.DetailedOrders.First(o => o.Status == OrderStatus.Pending); + var order = await context.DetailedOrders.FirstAsync(o => o.Status == OrderStatus.Pending); Console.WriteLine($"First pending order will ship to: {order.ShippingAddress}"); } #endregion } -} \ No newline at end of file +} diff --git a/samples/core/Modeling/ValueConversions/CaseInsensitiveStrings.cs b/samples/core/Modeling/ValueConversions/CaseInsensitiveStrings.cs index cd97d29933..8289ea8955 100644 --- a/samples/core/Modeling/ValueConversions/CaseInsensitiveStrings.cs +++ b/samples/core/Modeling/ValueConversions/CaseInsensitiveStrings.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Diagnostics; @@ -12,13 +13,13 @@ namespace EFModeling.ValueConversions; public class CaseInsensitiveStrings : Program { - public void Run() + public async Task Run() { ConsoleWriteLines("Sample showing value conversions for case-insensitive string keys..."); using (var context = new SampleDbContext()) { - CleanDatabase(context); + await CleanDatabase(context); ConsoleWriteLines("Save new entities..."); @@ -40,14 +41,14 @@ public void Run() BlogId = "DotNet", Title = "Some more good .NET stuff" }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = new SampleDbContext()) { ConsoleWriteLines("Read the entities back..."); - var blog = context.Set().Include(e => e.Posts).Single(); + var blog = await context.Set().Include(e => e.Posts).SingleAsync(); ConsoleWriteLines($"The blog has {blog.Posts.Count} posts with foreign keys '{blog.Posts.First().BlogId}' and '{blog.Posts.Skip(1).First().BlogId}'"); } diff --git a/samples/core/Modeling/ValueConversions/CompositeValueObject.cs b/samples/core/Modeling/ValueConversions/CompositeValueObject.cs index b9c8b26912..4e72a32133 100644 --- a/samples/core/Modeling/ValueConversions/CompositeValueObject.cs +++ b/samples/core/Modeling/ValueConversions/CompositeValueObject.cs @@ -5,6 +5,7 @@ using System.Linq; using System.Text.Json; using System.Text.Json.Serialization; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; @@ -12,25 +13,25 @@ namespace EFModeling.ValueConversions; public class CompositeValueObject : Program { - public void Run() + public async Task Run() { ConsoleWriteLines("Sample showing value conversions for a composite value object..."); using (var context = new SampleDbContext()) { - CleanDatabase(context); + await CleanDatabase(context); ConsoleWriteLines("Save a new entity..."); context.Add(new Order { Price = new Money(3.99m, Currency.UsDollars) }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = new SampleDbContext()) { ConsoleWriteLines("Read the entity back..."); - var order = context.Set().Single(); + var order = await context.Set().SingleAsync(); ConsoleWriteLines($"Order with price {order.Price.Amount} in {order.Price.Currency}."); } @@ -90,4 +91,4 @@ public enum Currency PoundsSterling } #endregion -} \ No newline at end of file +} diff --git a/samples/core/Modeling/ValueConversions/EncryptPropertyValues.cs b/samples/core/Modeling/ValueConversions/EncryptPropertyValues.cs index 45eedc1266..7928514b44 100644 --- a/samples/core/Modeling/ValueConversions/EncryptPropertyValues.cs +++ b/samples/core/Modeling/ValueConversions/EncryptPropertyValues.cs @@ -3,6 +3,7 @@ using System; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; @@ -10,25 +11,25 @@ namespace EFModeling.ValueConversions; public class EncryptPropertyValues : Program { - public void Run() + public async Task Run() { ConsoleWriteLines("Sample showing value conversions for encrypting property values..."); using (var context = new SampleDbContext()) { - CleanDatabase(context); + await CleanDatabase(context); ConsoleWriteLines("Save a new entity..."); context.Add(new User { Name = "arthur", Password = "password" }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = new SampleDbContext()) { ConsoleWriteLines("Read the entity back..."); - var user = context.Set().Single(); + var user = await context.Set().SingleAsync(); ConsoleWriteLines($"User {user.Name} has password '{user.Password}'"); } diff --git a/samples/core/Modeling/ValueConversions/EnumToStringConversions.cs b/samples/core/Modeling/ValueConversions/EnumToStringConversions.cs index efc314f06b..d5699145d8 100644 --- a/samples/core/Modeling/ValueConversions/EnumToStringConversions.cs +++ b/samples/core/Modeling/ValueConversions/EnumToStringConversions.cs @@ -1,6 +1,7 @@ using System; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; @@ -9,125 +10,111 @@ namespace EFModeling.ValueConversions; public class EnumToStringConversions : Program { - public void Run() + public async Task Run() { ConsoleWriteLines("Sample showing explicitly configured value converter"); using (var context = new SampleDbContextExplicit()) { - CleanDatabase(context); + await CleanDatabase(context); context.Add(new Rider { Mount = EquineBeast.Horse }); - context.SaveChanges(); - - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = new SampleDbContextExplicit()) { - ConsoleWriteLines($"Enum value read as '{context.Set().Single().Mount}'."); + ConsoleWriteLines($"Enum value read as '{(await context.Set().SingleAsync()).Mount}'."); } ConsoleWriteLines("Sample showing conversion configured by CLR type"); using (var context = new SampleDbContextByClrType()) { - CleanDatabase(context); + await CleanDatabase(context); context.Add(new Rider { Mount = EquineBeast.Horse }); - context.SaveChanges(); - - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = new SampleDbContextByClrType()) { - ConsoleWriteLines($"Enum value read as '{context.Set().Single().Mount}'."); + ConsoleWriteLines($"Enum value read as '{(await context.Set().SingleAsync()).Mount}'."); } ConsoleWriteLines("Sample showing conversion configured by database type"); using (var context = new SampleDbContextByDatabaseType()) { - CleanDatabase(context); + await CleanDatabase(context); context.Add(new Rider2 { Mount = EquineBeast.Horse }); - context.SaveChanges(); - - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = new SampleDbContextByDatabaseType()) { - ConsoleWriteLines($"Enum value read as '{context.Set().Single().Mount}'."); + ConsoleWriteLines($"Enum value read as '{(await context.Set().SingleAsync()).Mount}'."); } ConsoleWriteLines("Sample showing conversion configured by a ValueConverter instance"); using (var context = new SampleDbContextByConverterInstance()) { - CleanDatabase(context); + await CleanDatabase(context); context.Add(new Rider { Mount = EquineBeast.Horse }); - context.SaveChanges(); - - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = new SampleDbContextByConverterInstance()) { - ConsoleWriteLines($"Enum value read as '{context.Set().Single().Mount}'."); + ConsoleWriteLines($"Enum value read as '{(await context.Set().SingleAsync()).Mount}'."); } ConsoleWriteLines("Sample showing conversion configured by a built-in ValueConverter instance"); using (var context = new SampleDbContextByBuiltInInstance()) { - CleanDatabase(context); + await CleanDatabase(context); context.Add(new Rider { Mount = EquineBeast.Horse }); - context.SaveChanges(); - - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = new SampleDbContextByBuiltInInstance()) { - ConsoleWriteLines($"Enum value read as '{context.Set().Single().Mount}'."); + ConsoleWriteLines($"Enum value read as '{(await context.Set().SingleAsync()).Mount}'."); } ConsoleWriteLines("Sample showing conversion configured by CLR type with per-property facets"); using (var context = new SampleDbContextByClrTypeWithFacets()) { - CleanDatabase(context); + await CleanDatabase(context); context.Add(new Rider { Mount = EquineBeast.Horse }); - context.SaveChanges(); - - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = new SampleDbContextByClrTypeWithFacets()) { - ConsoleWriteLines($"Enum value read as '{context.Set().Single().Mount}'."); + ConsoleWriteLines($"Enum value read as '{(await context.Set().SingleAsync()).Mount}'."); } ConsoleWriteLines("Sample showing conversion configured by a ValueConverter instance with per-property facets"); using (var context = new SampleDbContextByConverterInstanceWithFacets()) { - CleanDatabase(context); + await CleanDatabase(context); context.Add(new Rider { Mount = EquineBeast.Horse }); - context.SaveChanges(); - - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = new SampleDbContextByConverterInstanceWithFacets()) { - ConsoleWriteLines($"Enum value read as '{context.Set().Single().Mount}'."); + ConsoleWriteLines($"Enum value read as '{(await context.Set().SingleAsync()).Mount}'."); } } diff --git a/samples/core/Modeling/ValueConversions/FixedLengthStrings.cs b/samples/core/Modeling/ValueConversions/FixedLengthStrings.cs index 9ec9db2493..8499488ccc 100644 --- a/samples/core/Modeling/ValueConversions/FixedLengthStrings.cs +++ b/samples/core/Modeling/ValueConversions/FixedLengthStrings.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Diagnostics; @@ -13,13 +14,13 @@ namespace EFModeling.ValueConversions; public class FixedLengthStrings : Program { - public void Run() + public async Task Run() { ConsoleWriteLines("Sample showing value conversions for fixed-length, case-insensitive string keys..."); using (var context = new SampleDbContext()) { - CleanDatabase(context); + await CleanDatabase(context); ConsoleWriteLines("Save new entities..."); @@ -41,14 +42,14 @@ public void Run() BlogId = "DotNet", Title = "Some more good .NET stuff" }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = new SampleDbContext()) { ConsoleWriteLines("Read the entities back..."); - var blog = context.Set().Include(e => e.Posts).Single(); + var blog = await context.Set().Include(e => e.Posts).SingleAsync(); ConsoleWriteLines($"The blog has {blog.Posts.Count} posts with foreign keys '{blog.Posts.First().BlogId}' and '{blog.Posts.Skip(1).First().BlogId}'"); } diff --git a/samples/core/Modeling/ValueConversions/KeyValueObjects.cs b/samples/core/Modeling/ValueConversions/KeyValueObjects.cs index 4551b9b0d4..534bb44baf 100644 --- a/samples/core/Modeling/ValueConversions/KeyValueObjects.cs +++ b/samples/core/Modeling/ValueConversions/KeyValueObjects.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; @@ -12,13 +13,13 @@ namespace EFModeling.ValueConversions; public class KeyValueObjects : Program { - public void Run() + public async Task Run() { ConsoleWriteLines("Sample showing value conversions for a value objects used as keys..."); using (var context = new SampleDbContext()) { - CleanDatabase(context); + await CleanDatabase(context); ConsoleWriteLines("Save a new entity..."); @@ -38,14 +39,14 @@ public void Run() } }; context.Add(blog); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = new SampleDbContext()) { ConsoleWriteLines("Read the entity back..."); - var blog = context.Set().Include(e => e.Posts).Single(); + var blog = await context.Set().Include(e => e.Posts).SingleAsync(); } ConsoleWriteLines("Sample finished."); @@ -112,4 +113,4 @@ public readonly struct PostKey public int Id { get; } } #endregion -} \ No newline at end of file +} diff --git a/samples/core/Modeling/ValueConversions/MappingImmutableClassProperty.cs b/samples/core/Modeling/ValueConversions/MappingImmutableClassProperty.cs index a805b06537..3f86be68ab 100644 --- a/samples/core/Modeling/ValueConversions/MappingImmutableClassProperty.cs +++ b/samples/core/Modeling/ValueConversions/MappingImmutableClassProperty.cs @@ -1,5 +1,6 @@ using System.Diagnostics; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; @@ -7,33 +8,33 @@ namespace EFModeling.ValueConversions; public class MappingImmutableClassProperty : Program { - public void Run() + public async Task Run() { ConsoleWriteLines("Sample showing value conversions for a simple immutable class..."); using (var context = new SampleDbContext()) { - CleanDatabase(context); + await CleanDatabase(context); ConsoleWriteLines("Save a new entity..."); var entity = new MyEntityType { MyProperty = new ImmutableClass(7) }; context.Add(entity); - context.SaveChanges(); + await context.SaveChangesAsync(); ConsoleWriteLines("Change the property value and save again..."); // This will be detected and EF will update the database on SaveChanges entity.MyProperty = new ImmutableClass(77); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = new SampleDbContext()) { ConsoleWriteLines("Read the entity back..."); - var entity = context.Set().Single(); + var entity = await context.Set().SingleAsync(); Debug.Assert(entity.MyProperty.Value == 77); } @@ -91,4 +92,4 @@ public override int GetHashCode() => Value.GetHashCode(); } #endregion -} \ No newline at end of file +} diff --git a/samples/core/Modeling/ValueConversions/MappingImmutableStructProperty.cs b/samples/core/Modeling/ValueConversions/MappingImmutableStructProperty.cs index ec6c5f00b1..9d70c9666d 100644 --- a/samples/core/Modeling/ValueConversions/MappingImmutableStructProperty.cs +++ b/samples/core/Modeling/ValueConversions/MappingImmutableStructProperty.cs @@ -1,5 +1,6 @@ using System.Diagnostics; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; @@ -7,33 +8,33 @@ namespace EFModeling.ValueConversions; public class MappingImmutableStructProperty : Program { - public void Run() + public async Task Run() { ConsoleWriteLines("Sample showing value conversions for a simple immutable struct..."); using (var context = new SampleDbContext()) { - CleanDatabase(context); + await CleanDatabase(context); ConsoleWriteLines("Save a new entity..."); var entity = new EntityType { MyProperty = new ImmutableStruct(6) }; context.Add(entity); - context.SaveChanges(); + await context.SaveChangesAsync(); ConsoleWriteLines("Change the property value and save again..."); // This will be detected and EF will update the database on SaveChanges entity.MyProperty = new ImmutableStruct(66); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = new SampleDbContext()) { ConsoleWriteLines("Read the entity back..."); - var entity = context.Set().Single(); + var entity = await context.Set().SingleAsync(); Debug.Assert(entity.MyProperty.Value == 66); } @@ -82,4 +83,4 @@ public ImmutableStruct(int value) public int Value { get; } } #endregion -} \ No newline at end of file +} diff --git a/samples/core/Modeling/ValueConversions/MappingListProperty.cs b/samples/core/Modeling/ValueConversions/MappingListProperty.cs index 9a6e9e03c1..a2764a8a85 100644 --- a/samples/core/Modeling/ValueConversions/MappingListProperty.cs +++ b/samples/core/Modeling/ValueConversions/MappingListProperty.cs @@ -3,6 +3,7 @@ using System.Diagnostics; using System.Linq; using System.Text.Json; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.Extensions.Logging; @@ -11,33 +12,33 @@ namespace EFModeling.ValueConversions; public class MappingListProperty : Program { - public void Run() + public async Task Run() { ConsoleWriteLines("Sample showing value conversions for a List..."); using (var context = new SampleDbContext()) { - CleanDatabase(context); + await CleanDatabase(context); ConsoleWriteLines("Save a new entity..."); var entity = new EntityType { MyListProperty = new List { 1, 2, 3 } }; context.Add(entity); - context.SaveChanges(); + await context.SaveChangesAsync(); ConsoleWriteLines("Mutate the property value and save again..."); // This will be detected and EF will update the database on SaveChanges entity.MyListProperty.Add(4); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = new SampleDbContext()) { ConsoleWriteLines("Read the entity back..."); - var entity = context.Set().Single(); + var entity = await context.Set().SingleAsync(); Debug.Assert(entity.MyListProperty.SequenceEqual(new List { 1, 2, 3, 4 })); } @@ -81,4 +82,4 @@ public class EntityType public List MyListProperty { get; set; } #endregion } -} \ No newline at end of file +} diff --git a/samples/core/Modeling/ValueConversions/MappingListPropertyOld.cs b/samples/core/Modeling/ValueConversions/MappingListPropertyOld.cs index 77dae07ffc..7a3ebcb1de 100644 --- a/samples/core/Modeling/ValueConversions/MappingListPropertyOld.cs +++ b/samples/core/Modeling/ValueConversions/MappingListPropertyOld.cs @@ -3,6 +3,7 @@ using System.Diagnostics; using System.Linq; using System.Text.Json; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.Extensions.Logging; @@ -11,33 +12,33 @@ namespace EFModeling.ValueConversions; public class MappingListPropertyOld : Program { - public void Run() + public async Task Run() { ConsoleWriteLines("Sample showing value conversions for a List..."); using (var context = new SampleDbContext()) { - CleanDatabase(context); + await CleanDatabase(context); ConsoleWriteLines("Save a new entity..."); var entity = new EntityType { MyListProperty = new List { 1, 2, 3 } }; context.Add(entity); - context.SaveChanges(); + await context.SaveChangesAsync(); ConsoleWriteLines("Mutate the property value and save again..."); // This will be detected and EF will update the database on SaveChanges entity.MyListProperty.Add(4); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = new SampleDbContext()) { ConsoleWriteLines("Read the entity back..."); - var entity = context.Set().Single(); + var entity = await context.Set().SingleAsync(); Debug.Assert(entity.MyListProperty.SequenceEqual(new List { 1, 2, 3, 4 })); } @@ -88,4 +89,4 @@ public class EntityType public List MyListProperty { get; set; } #endregion } -} \ No newline at end of file +} diff --git a/samples/core/Modeling/ValueConversions/OverridingByteArrayComparisons.cs b/samples/core/Modeling/ValueConversions/OverridingByteArrayComparisons.cs index 00e465c274..50229f887c 100644 --- a/samples/core/Modeling/ValueConversions/OverridingByteArrayComparisons.cs +++ b/samples/core/Modeling/ValueConversions/OverridingByteArrayComparisons.cs @@ -1,6 +1,7 @@ using System; using System.Diagnostics; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.Extensions.Logging; @@ -9,19 +10,19 @@ namespace EFModeling.ValueConversions; public class OverridingByteArrayComparisons : Program { - public void Run() + public async Task Run() { ConsoleWriteLines("Sample showing overriding byte array comparisons..."); using (var context = new SampleDbContext()) { - CleanDatabase(context); + await CleanDatabase(context); ConsoleWriteLines("Save a new entity..."); var entity = new EntityType { MyBytes = new byte[] { 1, 2, 3 } }; context.Add(entity); - context.SaveChanges(); + await context.SaveChangesAsync(); ConsoleWriteLines("Mutate the property value and save again..."); @@ -29,14 +30,14 @@ public void Run() // In this case it will be detected because the comparer in the model is overridden. entity.MyBytes[1] = 4; - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = new SampleDbContext()) { ConsoleWriteLines("Read the entity back..."); - var entity = context.Set().Single(); + var entity = await context.Set().SingleAsync(); Debug.Assert(entity.MyBytes.SequenceEqual(new byte[] { 1, 4, 3 })); } @@ -77,4 +78,4 @@ public class EntityType public byte[] MyBytes { get; set; } } -} \ No newline at end of file +} diff --git a/samples/core/Modeling/ValueConversions/PreserveDateTimeKind.cs b/samples/core/Modeling/ValueConversions/PreserveDateTimeKind.cs index 9edc93aab4..7ca40dbb51 100644 --- a/samples/core/Modeling/ValueConversions/PreserveDateTimeKind.cs +++ b/samples/core/Modeling/ValueConversions/PreserveDateTimeKind.cs @@ -3,6 +3,7 @@ using System; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; @@ -10,13 +11,13 @@ namespace EFModeling.ValueConversions; public class PreserveDateTimeKind : Program { - public void Run() + public async Task Run() { ConsoleWriteLines("Sample showing value conversions for preserving/setting DateTime.Kind..."); using (var context = new SampleDbContext()) { - CleanDatabase(context); + await CleanDatabase(context); ConsoleWriteLines("Save new entities..."); @@ -35,18 +36,18 @@ public void Run() LastUpdated = new DateTime(1976, 9, 3, 0, 0, 0, 0, DateTimeKind.Utc), DeletedOn = new DateTime(2017, 9, 3, 0, 0, 0, 0, DateTimeKind.Utc) }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = new SampleDbContext()) { ConsoleWriteLines("Read the entities back..."); - var blog1 = context.Set().Single(e => e.Title == "Post 1"); + var blog1 = await context.Set().SingleAsync(e => e.Title == "Post 1"); ConsoleWriteLines($"Blog 1: PostedOn.Kind = {blog1.PostedOn.Kind} LastUpdated.Kind = {blog1.LastUpdated.Kind} DeletedOn.Kind = {blog1.DeletedOn.Kind}"); - var blog2 = context.Set().Single(e => e.Title == "Post 2"); + var blog2 = await context.Set().SingleAsync(e => e.Title == "Post 2"); ConsoleWriteLines($"Blog 2: PostedOn.Kind = {blog2.PostedOn.Kind} LastUpdated.Kind = {blog2.LastUpdated.Kind} DeletedOn.Kind = {blog2.DeletedOn.Kind}"); } diff --git a/samples/core/Modeling/ValueConversions/PrimitiveCollection.cs b/samples/core/Modeling/ValueConversions/PrimitiveCollection.cs index 7b6f1319e0..7c15359caa 100644 --- a/samples/core/Modeling/ValueConversions/PrimitiveCollection.cs +++ b/samples/core/Modeling/ValueConversions/PrimitiveCollection.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Linq; using System.Text.Json; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Diagnostics; @@ -13,32 +14,32 @@ namespace EFModeling.ValueConversions; public class PrimitiveCollection : Program { - public void Run() + public async Task Run() { ConsoleWriteLines("Sample showing value conversions for a collections of primitive values..."); using (var context = new SampleDbContext()) { - CleanDatabase(context); + await CleanDatabase(context); ConsoleWriteLines("Save a new entity..."); context.Add(new Post { Tags = new List { "EF Core", "Unicorns", "Donkeys" } }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = new SampleDbContext()) { ConsoleWriteLines("Read the entity back..."); - var post = context.Set().Single(); + var post = await context.Set().SingleAsync(); ConsoleWriteLines($"Post with tags {string.Join(", ", post.Tags)}."); ConsoleWriteLines("Changing the value object and saving again"); post.Tags.Add("ASP.NET Core"); - context.SaveChanges(); + await context.SaveChangesAsync(); } ConsoleWriteLines("Sample finished."); @@ -78,4 +79,4 @@ public class Post public ICollection Tags { get; set; } } #endregion -} \ No newline at end of file +} diff --git a/samples/core/Modeling/ValueConversions/Program.cs b/samples/core/Modeling/ValueConversions/Program.cs index 06b78d4b0e..4eea2aa26a 100644 --- a/samples/core/Modeling/ValueConversions/Program.cs +++ b/samples/core/Modeling/ValueConversions/Program.cs @@ -1,4 +1,5 @@ using System; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace EFModeling.ValueConversions; @@ -8,25 +9,25 @@ namespace EFModeling.ValueConversions; /// public class Program { - public static void Main() + public static async Task Main() { - new MappingImmutableClassProperty().Run(); - new MappingImmutableStructProperty().Run(); - new MappingListProperty().Run(); - new MappingListPropertyOld().Run(); - new OverridingByteArrayComparisons().Run(); - new EnumToStringConversions().Run(); - new KeyValueObjects().Run(); - new SimpleValueObject().Run(); - new CompositeValueObject().Run(); - new PrimitiveCollection().Run(); - new ValueObjectCollection().Run(); - new ULongConcurrency().Run(); - new PreserveDateTimeKind().Run(); - new CaseInsensitiveStrings().Run(); - new FixedLengthStrings().Run(); - new EncryptPropertyValues().Run(); - new WithMappingHints().Run(); + await new MappingImmutableClassProperty().Run(); + await new MappingImmutableStructProperty().Run(); + await new MappingListProperty().Run(); + await new MappingListPropertyOld().Run(); + await new OverridingByteArrayComparisons().Run(); + await new EnumToStringConversions().Run(); + await new KeyValueObjects().Run(); + await new SimpleValueObject().Run(); + await new CompositeValueObject().Run(); + await new PrimitiveCollection().Run(); + await new ValueObjectCollection().Run(); + await new ULongConcurrency().Run(); + await new PreserveDateTimeKind().Run(); + await new CaseInsensitiveStrings().Run(); + await new FixedLengthStrings().Run(); + await new EncryptPropertyValues().Run(); + await new WithMappingHints().Run(); } protected static void ConsoleWriteLines(params string[] values) @@ -40,11 +41,11 @@ protected static void ConsoleWriteLines(params string[] values) Console.WriteLine(); } - protected static void CleanDatabase(DbContext context) + protected static async Task CleanDatabase(DbContext context) { ConsoleWriteLines("Deleting and re-creating database..."); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); ConsoleWriteLines("Done. Database is clean and fresh."); } -} \ No newline at end of file +} diff --git a/samples/core/Modeling/ValueConversions/SimpleValueObject.cs b/samples/core/Modeling/ValueConversions/SimpleValueObject.cs index da3c7a51e2..1cebf7f84d 100644 --- a/samples/core/Modeling/ValueConversions/SimpleValueObject.cs +++ b/samples/core/Modeling/ValueConversions/SimpleValueObject.cs @@ -3,6 +3,7 @@ using System; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; @@ -10,25 +11,25 @@ namespace EFModeling.ValueConversions; public class SimpleValueObject : Program { - public void Run() + public async Task Run() { ConsoleWriteLines("Sample showing value conversions for a simple value object..."); using (var context = new SampleDbContext()) { - CleanDatabase(context); + await CleanDatabase(context); ConsoleWriteLines("Save a new entity..."); context.Add(new Order { Price = new Dollars(3.99m) }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = new SampleDbContext()) { ConsoleWriteLines("Read the entity back..."); - var entity = context.Set().Single(); + var entity = await context.Set().SingleAsync(); } ConsoleWriteLines("Sample finished."); @@ -66,13 +67,13 @@ public class Order #region SimpleValueObject public readonly struct Dollars { - public Dollars(decimal amount) + public Dollars(decimal amount) => Amount = amount; - + public decimal Amount { get; } - public override string ToString() + public override string ToString() => $"${Amount}"; } #endregion -} \ No newline at end of file +} diff --git a/samples/core/Modeling/ValueConversions/ULongConcurrency.cs b/samples/core/Modeling/ValueConversions/ULongConcurrency.cs index 2eb5717d60..864e969963 100644 --- a/samples/core/Modeling/ValueConversions/ULongConcurrency.cs +++ b/samples/core/Modeling/ValueConversions/ULongConcurrency.cs @@ -3,6 +3,7 @@ using System; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; @@ -10,13 +11,13 @@ namespace EFModeling.ValueConversions; public class ULongConcurrency : Program { - public void Run() + public async Task Run() { ConsoleWriteLines("Sample showing how to map rowversion to ulong..."); using (var context = new SampleDbContext()) { - CleanDatabase(context); + await CleanDatabase(context); ConsoleWriteLines("Save a new entity..."); @@ -25,40 +26,40 @@ public void Run() { Name = "OneUnicorn" }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = new SampleDbContext()) { ConsoleWriteLines("Read the entity back in one context..."); - var blog = context.Set().Single(); + var blog = await context.Set().SingleAsync(); blog.Name = "TwoUnicorns"; using (var context2 = new SampleDbContext()) { ConsoleWriteLines("Change the blog name and save in a different context..."); - context2.Set().Single().Name = "1unicorn2"; - context2.SaveChanges(); + (await context2.Set().SingleAsync()).Name = "1unicorn2"; + await context2.SaveChangesAsync(); } try { ConsoleWriteLines("Change the blog name and save in the first context..."); - context.SaveChanges(); + await context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException e) { ConsoleWriteLines($"{e.GetType().FullName}: {e.Message}"); - var databaseValues = context.Entry(blog).GetDatabaseValues(); + var databaseValues = await context.Entry(blog).GetDatabaseValuesAsync(); context.Entry(blog).OriginalValues.SetValues(databaseValues); ConsoleWriteLines("Refresh original values and save again..."); - context.SaveChanges(); + await context.SaveChangesAsync(); } } diff --git a/samples/core/Modeling/ValueConversions/ValueObjectCollection.cs b/samples/core/Modeling/ValueConversions/ValueObjectCollection.cs index c17faa80f9..f740aff28f 100644 --- a/samples/core/Modeling/ValueConversions/ValueObjectCollection.cs +++ b/samples/core/Modeling/ValueConversions/ValueObjectCollection.cs @@ -6,6 +6,7 @@ using System.Linq; using System.Text.Json; using System.Text.Json.Serialization; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Diagnostics; @@ -14,13 +15,13 @@ namespace EFModeling.ValueConversions; public class ValueObjectCollection : Program { - public void Run() + public async Task Run() { ConsoleWriteLines("Sample showing value conversions for a collection of value objects..."); using (var context = new SampleDbContext()) { - CleanDatabase(context); + await CleanDatabase(context); ConsoleWriteLines("Save a new entity..."); @@ -34,21 +35,21 @@ public void Run() new AnnualFinance(2020, new Money(25.77m, Currency.UsDollars), new Money(125m, Currency.UsDollars)) } }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = new SampleDbContext()) { ConsoleWriteLines("Read the entity back..."); - var blog = context.Set().Single(); + var blog = await context.Set().SingleAsync(); ConsoleWriteLines($"Blog with finances {string.Join(", ", blog.Finances.Select(f => $"{f.Year}: I={f.Income} E={f.Expenses} R={f.Revenue}"))}."); ConsoleWriteLines("Changing the value object and saving again"); blog.Finances.Add(new AnnualFinance(2021, new Money(12.0m, Currency.UsDollars), new Money(125m, Currency.UsDollars))); - context.SaveChanges(); + await context.SaveChangesAsync(); } ConsoleWriteLines("Sample finished."); @@ -129,4 +130,4 @@ public class Blog public IList Finances { get; set; } } #endregion -} \ No newline at end of file +} diff --git a/samples/core/Modeling/ValueConversions/WithMappingHints.cs b/samples/core/Modeling/ValueConversions/WithMappingHints.cs index 9610227ab7..eefc2ce5ce 100644 --- a/samples/core/Modeling/ValueConversions/WithMappingHints.cs +++ b/samples/core/Modeling/ValueConversions/WithMappingHints.cs @@ -3,6 +3,7 @@ using System; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; @@ -11,27 +12,27 @@ namespace EFModeling.ValueConversions; public class WithMappingHints : Program { - public void Run() + public async Task Run() { ConsoleWriteLines("Sample showing value conversions with mapping hints for facets..."); using (var context = new SampleDbContext()) { - CleanDatabase(context); + await CleanDatabase(context); ConsoleWriteLines("Save a entities..."); context.Add(new Order1 { Price = new Dollars(3.99m) }); context.Add(new Order2 { Price = new Dollars(3.99m) }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = new SampleDbContext()) { ConsoleWriteLines("Read the entities back..."); - var entity1 = context.Set().Single(); - var entity2 = context.Set().Single(); + var entity1 = await context.Set().SingleAsync(); + var entity2 = await context.Set().SingleAsync(); } ConsoleWriteLines("Sample finished."); diff --git a/samples/core/Performance/AspNetContextPooling/Controllers/WeatherForecastController.cs b/samples/core/Performance/AspNetContextPooling/Controllers/WeatherForecastController.cs index 42003f4952..87e80d2c5e 100644 --- a/samples/core/Performance/AspNetContextPooling/Controllers/WeatherForecastController.cs +++ b/samples/core/Performance/AspNetContextPooling/Controllers/WeatherForecastController.cs @@ -1,4 +1,5 @@ using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; namespace Performance.AspNetContextPooling.Controllers; @@ -12,6 +13,6 @@ public WeatherForecastController(WeatherForecastContext dbContext) => _dbContext = dbContext; [HttpGet(Name = "GetWeatherForecast")] - public IEnumerable Get() - => _dbContext.Forecasts.OrderBy(f => f.Date).Take(5).ToArray(); -} \ No newline at end of file + public async Task> Get() + => await _dbContext.Forecasts.OrderBy(f => f.Date).Take(5).ToArrayAsync(); +} diff --git a/samples/core/Performance/AspNetContextPoolingWithState/Controllers/WeatherForecastController.cs b/samples/core/Performance/AspNetContextPoolingWithState/Controllers/WeatherForecastController.cs index a48d8eb936..cbce0387cf 100644 --- a/samples/core/Performance/AspNetContextPoolingWithState/Controllers/WeatherForecastController.cs +++ b/samples/core/Performance/AspNetContextPoolingWithState/Controllers/WeatherForecastController.cs @@ -1,4 +1,5 @@ using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; namespace Performance.AspNetContextPoolingWithState.Controllers; @@ -12,6 +13,6 @@ public WeatherForecastController(WeatherForecastContext dbContext) => _dbContext = dbContext; [HttpGet(Name = "GetWeatherForecast")] - public IEnumerable Get() - => _dbContext.Forecasts.OrderBy(f => f.Date).Take(5).ToArray(); -} \ No newline at end of file + public async Task> Get() + => await _dbContext.Forecasts.OrderBy(f => f.Date).Take(5).ToArrayAsync(); +} diff --git a/samples/core/Performance/Other/Other.csproj b/samples/core/Performance/Other/Other.csproj index 65847f0f41..6faf421318 100644 --- a/samples/core/Performance/Other/Other.csproj +++ b/samples/core/Performance/Other/Other.csproj @@ -11,6 +11,7 @@ + diff --git a/samples/core/Performance/Other/Program.cs b/samples/core/Performance/Other/Program.cs index f53ed94b44..f8d7175bbb 100644 --- a/samples/core/Performance/Other/Program.cs +++ b/samples/core/Performance/Other/Program.cs @@ -20,8 +20,8 @@ private static async Task Main(string[] args) { using (var context = new BloggingContext()) { - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); context.Add( new Blog @@ -35,30 +35,30 @@ private static async Task Main(string[] args) } }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = new BloggingContext()) { #region Indexes // Matches on start, so uses an index (on SQL Server) - var posts1 = context.Posts.Where(p => p.Title.StartsWith("A")).ToList(); + var posts1 = await context.Posts.Where(p => p.Title.StartsWith("A")).ToListAsync(); // Matches on end, so does not use the index - var posts2 = context.Posts.Where(p => p.Title.EndsWith("A")).ToList(); + var posts2 = await context.Posts.Where(p => p.Title.EndsWith("A")).ToListAsync(); #endregion } using (var context = new BloggingContext()) { #region ProjectEntities - foreach (var blog in context.Blogs) + await foreach (var blog in context.Blogs.AsAsyncEnumerable()) { Console.WriteLine("Blog: " + blog.Url); } #endregion #region ProjectSingleProperty - foreach (var blogName in context.Blogs.Select(b => b.Url)) + await foreach (var blogName in context.Blogs.Select(b => b.Url).AsAsyncEnumerable()) { Console.WriteLine("Blog: " + blogName); } @@ -68,23 +68,23 @@ private static async Task Main(string[] args) using (var context = new BloggingContext()) { #region NoLimit - var blogsAll = context.Posts + var blogsAll = await context.Posts .Where(p => p.Title.StartsWith("A")) - .ToList(); + .ToListAsync(); #endregion #region Limit25 - var blogs25 = context.Posts + var blogs25 = await context.Posts .Where(p => p.Title.StartsWith("A")) .Take(25) - .ToList(); + .ToListAsync(); #endregion } using (var context = new BloggingContext()) { #region EagerlyLoadRelatedAndProject - foreach (var blog in context.Blogs.Select(b => new { b.Url, b.Posts }).ToList()) + await foreach (var blog in context.Blogs.Select(b => new { b.Url, b.Posts }).AsAsyncEnumerable()) { foreach (var post in blog.Posts) { @@ -98,19 +98,19 @@ private static async Task Main(string[] args) { #region BufferingAndStreaming // ToList and ToArray cause the entire resultset to be buffered: - var blogsList = context.Posts.Where(p => p.Title.StartsWith("A")).ToList(); - var blogsArray = context.Posts.Where(p => p.Title.StartsWith("A")).ToArray(); + var blogsList = await context.Posts.Where(p => p.Title.StartsWith("A")).ToListAsync(); + var blogsArray = await context.Posts.Where(p => p.Title.StartsWith("A")).ToArrayAsync(); // Foreach streams, processing one row at a time: - foreach (var blog in context.Posts.Where(p => p.Title.StartsWith("A"))) + await foreach (var blog in context.Posts.Where(p => p.Title.StartsWith("A")).AsAsyncEnumerable()) { // ... } - // AsEnumerable also streams, allowing you to execute LINQ operators on the client-side: + // AsAsyncEnumerable also streams, allowing you to execute LINQ operators on the client-side: var doubleFilteredBlogs = context.Posts .Where(p => p.Title.StartsWith("A")) // Translated to SQL and executed in the database - .AsEnumerable() + .AsAsyncEnumerable() .Where(p => SomeDotNetMethod(p)); // Executed at the client on all database results #endregion @@ -122,19 +122,19 @@ private static async Task Main(string[] args) using (var context = new BloggingContext()) { #region SaveChangesBatching - var blog = context.Blogs.Single(b => b.Url == "http://someblog.microsoft.com"); + var blog = await context.Blogs.SingleAsync(b => b.Url == "http://someblog.microsoft.com"); blog.Url = "http://someotherblog.microsoft.com"; context.Add(new Blog { Url = "http://newblog1.microsoft.com" }); context.Add(new Blog { Url = "http://newblog2.microsoft.com" }); - context.SaveChanges(); + await context.SaveChangesAsync(); #endregion } using (var context = new BloggingContext()) { #region QueriesWithConstants - var post1 = context.Posts.FirstOrDefault(p => p.Title == "post1"); - var post2 = context.Posts.FirstOrDefault(p => p.Title == "post2"); + var post1 = await context.Posts.FirstOrDefaultAsync(p => p.Title == "post1"); + var post2 = await context.Posts.FirstOrDefaultAsync(p => p.Title == "post2"); #endregion } @@ -142,16 +142,16 @@ private static async Task Main(string[] args) { #region QueriesWithParameterization var postTitle = "post1"; - var post1 = context.Posts.FirstOrDefault(p => p.Title == postTitle); + var post1 = await context.Posts.FirstOrDefaultAsync(p => p.Title == postTitle); postTitle = "post2"; - var post2 = context.Posts.FirstOrDefault(p => p.Title == postTitle); + var post2 = await context.Posts.FirstOrDefaultAsync(p => p.Title == postTitle); #endregion } using (var context = new LazyBloggingContext()) { - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); for (var i = 0; i < 10; i++) { @@ -166,13 +166,13 @@ private static async Task Main(string[] args) }); } - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = new LazyBloggingContext()) { #region NPlusOne - foreach (var blog in context.Blogs.ToList()) + foreach (var blog in await context.Blogs.ToListAsync()) { foreach (var post in blog.Posts) { @@ -184,8 +184,8 @@ private static async Task Main(string[] args) using (var context = new EmployeeContext()) { - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); for (var i = 0; i < 10; i++) { @@ -196,19 +196,19 @@ private static async Task Main(string[] args) using (var context = new EmployeeContext()) { #region UpdateWithoutBulk - foreach (var employee in context.Employees) + await foreach (var employee in context.Employees.AsAsyncEnumerable()) { employee.Salary += 1000; } - context.SaveChanges(); + await context.SaveChangesAsync(); #endregion } using (var context = new EmployeeContext()) { #region UpdateWithBulk - context.Database.ExecuteSqlRaw("UPDATE [Employees] SET [Salary] = [Salary] + 1000"); + await context.Database.ExecuteSqlRawAsync("UPDATE [Employees] SET [Salary] = [Salary] + 1000"); #endregion } @@ -217,8 +217,8 @@ private static async Task Main(string[] args) .UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;ConnectRetryCount=0") .Options)) { - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } #region DbContextPoolingWithoutDI @@ -230,7 +230,7 @@ private static async Task Main(string[] args) using (var context = factory.CreateDbContext()) { - var allPosts = context.Posts.ToList(); + var allPosts = await context.Posts.ToListAsync(); } #endregion diff --git a/samples/core/Querying/ClientEvaluation/ClientEvaluation.csproj b/samples/core/Querying/ClientEvaluation/ClientEvaluation.csproj index 7c6272d507..cdbc54cb16 100644 --- a/samples/core/Querying/ClientEvaluation/ClientEvaluation.csproj +++ b/samples/core/Querying/ClientEvaluation/ClientEvaluation.csproj @@ -10,6 +10,7 @@ + diff --git a/samples/core/Querying/ClientEvaluation/Program.cs b/samples/core/Querying/ClientEvaluation/Program.cs index 603e7ec5b6..b82b45f0cb 100644 --- a/samples/core/Querying/ClientEvaluation/Program.cs +++ b/samples/core/Querying/ClientEvaluation/Program.cs @@ -1,5 +1,7 @@ using System; using System.Linq; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; namespace EFQuerying.ClientEvaluation; @@ -19,22 +21,22 @@ public static string StandardizeUrl(string url) } #endregion - private static void Main(string[] args) + private static async Task Main(string[] args) { using (var context = new BloggingContext()) { - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } using (var context = new BloggingContext()) { #region ClientProjection - var blogs = context.Blogs + var blogs = await context.Blogs .OrderByDescending(blog => blog.Rating) .Select( blog => new { Id = blog.BlogId, Url = StandardizeUrl(blog.Url) }) - .ToList(); + .ToListAsync(); #endregion } @@ -43,9 +45,9 @@ private static void Main(string[] args) try { #region ClientWhere - var blogs = context.Blogs + var blogs = await context.Blogs .Where(blog => StandardizeUrl(blog.Url).Contains("dotnet")) - .ToList(); + .ToListAsync(); #endregion } catch (Exception e) @@ -58,10 +60,10 @@ private static void Main(string[] args) { #region ExplicitClientEvaluation var blogs = context.Blogs - .AsEnumerable() + .AsAsyncEnumerable() .Where(blog => StandardizeUrl(blog.Url).Contains("dotnet")) - .ToList(); + .ToListAsync(); #endregion } } -} \ No newline at end of file +} diff --git a/samples/core/Querying/NullSemantics/Program.cs b/samples/core/Querying/NullSemantics/Program.cs index fe6cf57ff2..e57ef06bdf 100644 --- a/samples/core/Querying/NullSemantics/Program.cs +++ b/samples/core/Querying/NullSemantics/Program.cs @@ -1,17 +1,19 @@ using System.Linq; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; namespace NullSemantics; internal class Program { - private static void Main(string[] args) + private static async Task Main(string[] args) { using var context = new NullSemanticsContext(); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); //#region FunctionSqlRaw - //context.Database.ExecuteSqlRaw( + //await context.Database.ExecuteSqlRawAsync( // @"create function [dbo].[ConcatStrings] (@prm1 nvarchar(max), @prm2 nvarchar(max)) // returns nvarchar(max) // as @@ -20,12 +22,12 @@ private static void Main(string[] args) // end"); //#endregion - //BasicExamples(); - Functions(); - //ManualOptimization(); + //await BasicExamples(); + await Functions(); + //await ManualOptimization(); } - private static void BasicExamples() + private static async Task BasicExamples() { using var context = new NullSemanticsContext(); #region BasicExamples @@ -36,14 +38,14 @@ private static void BasicExamples() var query5 = context.Entities.Where(e => e.String1 != e.String2); #endregion - var result1 = query1.ToList(); - var result2 = query2.ToList(); - var result3 = query3.ToList(); - var result4 = query4.ToList(); - var result5 = query5.ToList(); + var result1 = await query1.ToListAsync(); + var result2 = await query2.ToListAsync(); + var result3 = await query3.ToListAsync(); + var result4 = await query4.ToListAsync(); + var result5 = await query5.ToListAsync(); } - private static void Functions() + private static async Task Functions() { using var context = new NullSemanticsContext(); @@ -51,10 +53,10 @@ private static void Functions() var query = context.Entities.Where(e => e.String1.Substring(0, e.String2.Length) == null); #endregion - var result = query.ToList(); + var result = await query.ToListAsync(); } - private static void ManualOptimization() + private static async Task ManualOptimization() { using var context = new NullSemanticsContext(); @@ -64,7 +66,7 @@ private static void ManualOptimization() e => e.String1 != null && e.String2 != null && (e.String1 != e.String2 || e.String1.Length == e.String2.Length)); #endregion - var result1 = query1.ToList(); - var result2 = query2.ToList(); + var result1 = await query1.ToListAsync(); + var result2 = await query2.ToListAsync(); } -} \ No newline at end of file +} diff --git a/samples/core/Querying/Overview/Program.cs b/samples/core/Querying/Overview/Program.cs index f99860d807..24a122a9e8 100644 --- a/samples/core/Querying/Overview/Program.cs +++ b/samples/core/Querying/Overview/Program.cs @@ -1,39 +1,41 @@ using System.Linq; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; namespace EFQuerying.Overview; internal class Program { - private static void Main(string[] args) + private static async Task Main(string[] args) { using (var context = new BloggingContext()) { - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } #region LoadingAllData using (var context = new BloggingContext()) { - var blogs = context.Blogs.ToList(); + var blogs = await context.Blogs.ToListAsync(); } #endregion #region LoadingSingleEntity using (var context = new BloggingContext()) { - var blog = context.Blogs - .Single(b => b.BlogId == 1); + var blog = await context.Blogs + .SingleAsync(b => b.BlogId == 1); } #endregion #region Filtering using (var context = new BloggingContext()) { - var blogs = context.Blogs + var blogs = await context.Blogs .Where(b => b.Url.Contains("dotnet")) - .ToList(); + .ToListAsync(); } #endregion } -} \ No newline at end of file +} diff --git a/samples/core/Querying/Pagination/Program.cs b/samples/core/Querying/Pagination/Program.cs index e2a62eb61c..4eedaa5207 100644 --- a/samples/core/Querying/Pagination/Program.cs +++ b/samples/core/Querying/Pagination/Program.cs @@ -1,28 +1,29 @@ using System; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace EFQuerying.Pagination; internal class Program { - private static void Main(string[] args) + private static async Task Main(string[] args) { using (var context = new BloggingContext()) { - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } using (var context = new BloggingContext()) { #region OffsetPagination var position = 20; - var nextPage = context.Posts + var nextPage = await context.Posts .OrderBy(b => b.PostId) .Skip(position) .Take(10) - .ToList(); + .ToListAsync(); #endregion } @@ -30,11 +31,11 @@ private static void Main(string[] args) { #region KeySetPagination var lastId = 55; - var nextPage = context.Posts + var nextPage = await context.Posts .OrderBy(b => b.PostId) .Where(b => b.PostId > lastId) .Take(10) - .ToList(); + .ToListAsync(); #endregion } @@ -43,13 +44,13 @@ private static void Main(string[] args) #region KeySetPaginationWithMultipleKeys var lastDate = new DateTime(2020, 1, 1); var lastId = 55; - var nextPage = context.Posts + var nextPage = await context.Posts .OrderBy(b => b.Date) .ThenBy(b => b.PostId) .Where(b => b.Date > lastDate || (b.Date == lastDate && b.PostId > lastId)) .Take(10) - .ToList(); + .ToListAsync(); #endregion } } -} \ No newline at end of file +} diff --git a/samples/core/Querying/QueryFilters/BloggingContext.cs b/samples/core/Querying/QueryFilters/BloggingContext.cs index 60d8ed7121..c14d8e5eb8 100644 --- a/samples/core/Querying/QueryFilters/BloggingContext.cs +++ b/samples/core/Querying/QueryFilters/BloggingContext.cs @@ -1,4 +1,6 @@ using System.Linq; +using System.Threading; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace EFQuerying.QueryFilters; @@ -33,7 +35,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) #endregion } - public override int SaveChanges() + public override async Task SaveChangesAsync(CancellationToken cancellationToken = default) { ChangeTracker.DetectChanges(); @@ -50,6 +52,6 @@ public override int SaveChanges() item.CurrentValues["IsDeleted"] = true; } - return base.SaveChanges(); + return await base.SaveChangesAsync(cancellationToken); } } diff --git a/samples/core/Querying/QueryFilters/Program.cs b/samples/core/Querying/QueryFilters/Program.cs index ab28ed4f8c..0cbb694430 100644 --- a/samples/core/Querying/QueryFilters/Program.cs +++ b/samples/core/Querying/QueryFilters/Program.cs @@ -1,25 +1,26 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace EFQuerying.QueryFilters; internal class Program { - private static void Main(string[] args) + private static async Task Main(string[] args) { - QueryFiltersBasicExample(); - QueryFiltersWithNavigationsExample(); - QueryFiltersWithRequiredNavigationExample(); - QueryFiltersUsingNavigationExample(); + await QueryFiltersBasicExample(); + await QueryFiltersWithNavigationsExample(); + await QueryFiltersWithRequiredNavigationExample(); + await QueryFiltersUsingNavigationExample(); } - private static void QueryFiltersBasicExample() + private static async Task QueryFiltersBasicExample() { using (var db = new BloggingContext("diego")) { - if (db.Database.EnsureCreated()) + if (await db.Database.EnsureCreatedAsync()) { db.Blogs.Add( new Blog @@ -45,7 +46,7 @@ private static void QueryFiltersBasicExample() } }); - db.SaveChanges(); + await db.SaveChangesAsync(); using (var andrewDb = new BloggingContext("andrew")) { @@ -59,25 +60,25 @@ private static void QueryFiltersBasicExample() } }); - andrewDb.SaveChanges(); + await andrewDb.SaveChangesAsync(); } - db.Posts + (await db.Posts .Where( p => p.Title == "Caring for tropical fish" || p.Title == "Cat care 101") - .ToList() + .ToListAsync()) .ForEach(p => db.Posts.Remove(p)); - db.SaveChanges(); + await db.SaveChangesAsync(); } } using (var db = new BloggingContext("Diego")) { - var blogs = db.Blogs + var blogs = await db.Blogs .Include(b => b.Posts) - .ToList(); + .ToListAsync(); foreach (var blog in blogs) { @@ -93,10 +94,10 @@ private static void QueryFiltersBasicExample() } #region IgnoreFilters - blogs = db.Blogs + blogs = await db.Blogs .Include(b => b.Posts) .IgnoreQueryFilters() - .ToList(); + .ToListAsync(); #endregion foreach (var blog in blogs) @@ -112,12 +113,12 @@ private static void QueryFiltersBasicExample() } } - private static void QueryFiltersWithNavigationsExample() + private static async Task QueryFiltersWithNavigationsExample() { using (var animalContext = new AnimalContext()) { - animalContext.Database.EnsureDeleted(); - animalContext.Database.EnsureCreated(); + await animalContext.Database.EnsureDeletedAsync(); + await animalContext.Database.EnsureCreatedAsync(); var janice = new Person { Name = "Janice" }; var jamie = new Person { Name = "Jamie" }; @@ -135,7 +136,7 @@ private static void QueryFiltersWithNavigationsExample() animalContext.People.AddRange(janice, jamie, cesar, paul, dominic); animalContext.Animals.AddRange(kibbles, sammy, puffy, hati, simba); - animalContext.SaveChanges(); + await animalContext.SaveChangesAsync(); } using (var animalContext = new AnimalContext()) @@ -146,7 +147,7 @@ private static void QueryFiltersWithNavigationsExample() // Jamie and Paul are filtered out. // Paul doesn't own any pets. Jamie owns Puffy, but her pet has been filtered out. - var animalLovers = animalContext.People.ToList(); + var animalLovers = await animalContext.People.ToListAsync(); DisplayResults(animalLovers); Console.WriteLine("**************************************************"); @@ -157,10 +158,10 @@ private static void QueryFiltersWithNavigationsExample() // Paul doesn't own any pets. Jamie owns Puffy, but her pet has been filtered out. // Simba's favorite toy has also been filtered out. // Puffy is filtered out so he doesn't show up as Hati's friend. - var ownersAndTheirPets = animalContext.People + var ownersAndTheirPets = await animalContext.People .Include(p => p.Pets) .ThenInclude(p => ((Dog)p).FavoriteToy) - .ToList(); + .ToListAsync(); DisplayResults(ownersAndTheirPets); @@ -168,11 +169,11 @@ private static void QueryFiltersWithNavigationsExample() Console.WriteLine("* Animal lovers and their pets - query filters disabled *"); Console.WriteLine("*********************************************************"); - var ownersAndTheirPetsUnfiltered = animalContext.People + var ownersAndTheirPetsUnfiltered = await animalContext.People .IgnoreQueryFilters() .Include(p => p.Pets) .ThenInclude(p => ((Dog)p).FavoriteToy) - .ToList(); + .ToListAsync(); DisplayResults(ownersAndTheirPetsUnfiltered); } @@ -203,12 +204,12 @@ static void DisplayResults(List people) } } - private static void QueryFiltersWithRequiredNavigationExample() + private static async Task QueryFiltersWithRequiredNavigationExample() { using (var db = new FilteredBloggingContextRequired()) { - db.Database.EnsureDeleted(); - db.Database.EnsureCreated(); + await db.Database.EnsureDeletedAsync(); + await db.Database.EnsureCreatedAsync(); #region SeedData db.Blogs.Add( @@ -236,15 +237,15 @@ private static void QueryFiltersWithRequiredNavigationExample() }); #endregion - db.SaveChanges(); + await db.SaveChangesAsync(); } Console.WriteLine("Use of required navigations to access entity with query filter demo"); using (var db = new FilteredBloggingContextRequired()) { #region Queries - var allPosts = db.Posts.ToList(); - var allPostsWithBlogsIncluded = db.Posts.Include(p => p.Blog).ToList(); + var allPosts = await db.Posts.ToListAsync(); + var allPostsWithBlogsIncluded = await db.Posts.Include(p => p.Blog).ToListAsync(); #endregion if (allPosts.Count == allPostsWithBlogsIncluded.Count) @@ -260,12 +261,12 @@ private static void QueryFiltersWithRequiredNavigationExample() } } - private static void QueryFiltersUsingNavigationExample() + private static async Task QueryFiltersUsingNavigationExample() { using (var db = new FilteredBloggingContextRequired()) { - db.Database.EnsureDeleted(); - db.Database.EnsureCreated(); + await db.Database.EnsureDeletedAsync(); + await db.Database.EnsureCreatedAsync(); #region SeedDataNavigation db.Blogs.Add( @@ -303,16 +304,16 @@ private static void QueryFiltersUsingNavigationExample() }); #endregion - db.SaveChanges(); + await db.SaveChangesAsync(); } Console.WriteLine("Query filters using navigations demo"); using (var db = new FilteredBloggingContextRequired()) { #region QueriesNavigation - var filteredBlogs = db.Blogs.ToList(); + var filteredBlogs = await db.Blogs.ToListAsync(); #endregion - var filteredBlogsInclude = db.Blogs.Include(b => b.Posts).ToList(); + var filteredBlogsInclude = await db.Blogs.Include(b => b.Posts).ToListAsync(); if (filteredBlogs.Count == 2 && filteredBlogsInclude.Count == 2) { @@ -322,4 +323,4 @@ private static void QueryFiltersUsingNavigationExample() } } } -} \ No newline at end of file +} diff --git a/samples/core/Querying/RelatedData/Program.cs b/samples/core/Querying/RelatedData/Program.cs index 0a2cbcc880..e30c8663c5 100644 --- a/samples/core/Querying/RelatedData/Program.cs +++ b/samples/core/Querying/RelatedData/Program.cs @@ -1,223 +1,224 @@ using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace EFQuerying.RelatedData; internal class Program { - private static void Main(string[] args) + private static async Task Main(string[] args) { using (var context = new BloggingContext()) { - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } #region SingleInclude using (var context = new BloggingContext()) { - var blogs = context.Blogs + var blogs = await context.Blogs .Include(blog => blog.Posts) - .ToList(); + .ToListAsync(); } #endregion #region IgnoredInclude using (var context = new BloggingContext()) { - var blogs = context.Blogs + var blogs = await context.Blogs .Include(blog => blog.Posts) .Select( blog => new { Id = blog.BlogId, blog.Url }) - .ToList(); + .ToListAsync(); } #endregion #region MultipleIncludes using (var context = new BloggingContext()) { - var blogs = context.Blogs + var blogs = await context.Blogs .Include(blog => blog.Posts) .Include(blog => blog.Owner) - .ToList(); + .ToListAsync(); } #endregion #region SingleThenInclude using (var context = new BloggingContext()) { - var blogs = context.Blogs + var blogs = await context.Blogs .Include(blog => blog.Posts) .ThenInclude(post => post.Author) - .ToList(); + .ToListAsync(); } #endregion #region MultipleThenIncludes using (var context = new BloggingContext()) { - var blogs = context.Blogs + var blogs = await context.Blogs .Include(blog => blog.Posts) .ThenInclude(post => post.Author) .ThenInclude(author => author.Photo) - .ToList(); + .ToListAsync(); } #endregion #region IncludeTree using (var context = new BloggingContext()) { - var blogs = context.Blogs + var blogs = await context.Blogs .Include(blog => blog.Posts) .ThenInclude(post => post.Author) .ThenInclude(author => author.Photo) .Include(blog => blog.Owner) .ThenInclude(owner => owner.Photo) - .ToList(); + .ToListAsync(); } #endregion #region MultipleLeafIncludes using (var context = new BloggingContext()) { - var blogs = context.Blogs + var blogs = await context.Blogs .Include(blog => blog.Posts) .ThenInclude(post => post.Author) .Include(blog => blog.Posts) .ThenInclude(post => post.Tags) - .ToList(); + .ToListAsync(); } #endregion #region IncludeMultipleNavigationsWithSingleInclude using (var context = new BloggingContext()) { - var blogs = context.Blogs + var blogs = await context.Blogs .Include(blog => blog.Owner.AuthoredPosts) .ThenInclude(post => post.Blog.Owner.Photo) - .ToList(); + .ToListAsync(); } #endregion #region AsSplitQuery using (var context = new BloggingContext()) { - var blogs = context.Blogs + var blogs = await context.Blogs .Include(blog => blog.Posts) .AsSplitQuery() - .ToList(); + .ToListAsync(); } #endregion using (var context = new SplitQueriesBloggingContext()) { - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } #region WithSplitQueryAsDefault using (var context = new SplitQueriesBloggingContext()) { - var blogs = context.Blogs + var blogs = await context.Blogs .Include(blog => blog.Posts) - .ToList(); + .ToListAsync(); } #endregion #region AsSingleQuery using (var context = new SplitQueriesBloggingContext()) { - var blogs = context.Blogs + var blogs = await context.Blogs .Include(blog => blog.Posts) .AsSingleQuery() - .ToList(); + .ToListAsync(); } #endregion #region Explicit using (var context = new BloggingContext()) { - var blog = context.Blogs - .Single(b => b.BlogId == 1); + var blog = await context.Blogs + .SingleAsync(b => b.BlogId == 1); - context.Entry(blog) + await context.Entry(blog) .Collection(b => b.Posts) - .Load(); + .LoadAsync(); - context.Entry(blog) + await context.Entry(blog) .Reference(b => b.Owner) - .Load(); + .LoadAsync(); } #endregion #region NavQueryAggregate using (var context = new BloggingContext()) { - var blog = context.Blogs - .Single(b => b.BlogId == 1); + var blog = await context.Blogs + .SingleAsync(b => b.BlogId == 1); - var postCount = context.Entry(blog) + var postCount = await context.Entry(blog) .Collection(b => b.Posts) .Query() - .Count(); + .CountAsync(); } #endregion #region NavQueryFiltered using (var context = new BloggingContext()) { - var blog = context.Blogs - .Single(b => b.BlogId == 1); + var blog = await context.Blogs + .SingleAsync(b => b.BlogId == 1); - var goodPosts = context.Entry(blog) + var goodPosts = await context.Entry(blog) .Collection(b => b.Posts) .Query() .Where(p => p.Rating > 3) - .ToList(); + .ToListAsync(); } #endregion #region FilteredInclude using (var context = new BloggingContext()) { - var filteredBlogs = context.Blogs + var filteredBlogs = await context.Blogs .Include( blog => blog.Posts .Where(post => post.BlogId == 1) .OrderByDescending(post => post.Title) .Take(5)) - .ToList(); + .ToListAsync(); } #endregion #region MultipleLeafIncludesFiltered1 using (var context = new BloggingContext()) { - var filteredBlogs = context.Blogs + var filteredBlogs = await context.Blogs .Include(blog => blog.Posts.Where(post => post.BlogId == 1)) .ThenInclude(post => post.Author) .Include(blog => blog.Posts) .ThenInclude(post => post.Tags.OrderBy(postTag => postTag.TagId).Skip(3)) - .ToList(); + .ToListAsync(); } #endregion #region MultipleLeafIncludesFiltered2 using (var context = new BloggingContext()) { - var filteredBlogs = context.Blogs + var filteredBlogs = await context.Blogs .Include(blog => blog.Posts.Where(post => post.BlogId == 1)) .ThenInclude(post => post.Author) .Include(blog => blog.Posts.Where(post => post.BlogId == 1)) .ThenInclude(post => post.Tags.OrderBy(postTag => postTag.TagId).Skip(3)) - .ToList(); + .ToListAsync(); } #endregion #region AutoIncludes using (var context = new BloggingContext()) { - var themes = context.Themes.ToList(); + var themes = await context.Themes.ToListAsync(); } #endregion @@ -225,7 +226,7 @@ private static void Main(string[] args) #region IgnoreAutoIncludes using (var context = new BloggingContext()) { - var themes = context.Themes.IgnoreAutoIncludes().ToList(); + var themes = await context.Themes.IgnoreAutoIncludes().ToListAsync(); } #endregion diff --git a/samples/core/Querying/SqlQueries/Program.cs b/samples/core/Querying/SqlQueries/Program.cs index f8c70d3dcd..a44c3d24a9 100644 --- a/samples/core/Querying/SqlQueries/Program.cs +++ b/samples/core/Querying/SqlQueries/Program.cs @@ -1,4 +1,5 @@ using System.Linq; +using System.Threading.Tasks; using Microsoft.Data.SqlClient; using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; @@ -8,14 +9,14 @@ namespace EFQuerying.RawSQL; #pragma warning disable EF1002 // Risk of vulnerability to SQL injection. internal class Program { - private static void Main(string[] args) + private static async Task Main(string[] args) { using (var context = new BloggingContext()) { - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); - context.Database.ExecuteSqlRaw( + await context.Database.ExecuteSqlRawAsync( @"create function [dbo].[SearchBlogs] (@searchTerm nvarchar(max)) returns @found table ( @@ -35,13 +36,13 @@ from [Post] as [p] return end"); - context.Database.ExecuteSqlRaw( + await context.Database.ExecuteSqlRawAsync( @"create procedure [dbo].[GetMostPopularBlogs] as begin select * from dbo.Blogs order by Rating end"); - context.Database.ExecuteSqlRaw( + await context.Database.ExecuteSqlRawAsync( @"create procedure [dbo].[GetMostPopularBlogsForUser] @filterByUser nvarchar(max) as begin select * from dbo.Blogs order by Rating @@ -50,43 +51,43 @@ from [Post] as [p] using (var context = new BloggingContext()) { - var blogs = context.Blogs + var blogs = await context.Blogs .FromSql($"SELECT * FROM dbo.Blogs") - .ToList(); + .ToListAsync(); } using (var context = new BloggingContext()) { - var blogs = context.Blogs + var blogs = await context.Blogs .FromSql($"EXECUTE dbo.GetMostPopularBlogs") - .ToList(); + .ToListAsync(); } using (var context = new BloggingContext()) { var user = "johndoe"; - var blogs = context.Blogs + var blogs = await context.Blogs .FromSql($"EXECUTE dbo.GetMostPopularBlogsForUser {user}") - .ToList(); + .ToListAsync(); } using (var context = new BloggingContext()) { var user = new SqliteParameter("user", "johndoe"); - var blogs = context.Blogs + var blogs = await context.Blogs .FromSql($"EXECUTE dbo.GetMostPopularBlogsForUser @filterByUser={user}") - .ToList(); + .ToListAsync(); } using (var context = new BloggingContext()) { var user = new SqliteParameter("user", "johndoe"); - var blogs = context.Blogs + var blogs = await context.Blogs .FromSql($"EXECUTE dbo.GetMostPopularBlogsForUser {user}") - .ToList(); + .ToListAsync(); } using (var context = new BloggingContext()) @@ -94,60 +95,60 @@ from [Post] as [p] var columnName = "Url"; var columnValue = new SqliteParameter("columnValue", "http://SomeURL"); - var blogs = context.Blogs + var blogs = await context.Blogs .FromSqlRaw($"SELECT * FROM [Blogs] WHERE {columnName} = @columnValue", columnValue) - .ToList(); + .ToListAsync(); } using (var context = new BloggingContext()) { var searchTerm = "Lorem ipsum"; - var blogs = context.Blogs + var blogs = await context.Blogs .FromSql($"SELECT * FROM dbo.SearchBlogs({searchTerm})") .Where(b => b.Rating > 3) .OrderByDescending(b => b.Rating) - .ToList(); + .ToListAsync(); } using (var context = new BloggingContext()) { var searchTerm = "Lorem ipsum"; - var blogs = context.Blogs + var blogs = await context.Blogs .FromSql($"SELECT * FROM dbo.SearchBlogs({searchTerm})") .Include(b => b.Posts) - .ToList(); + .ToListAsync(); } using (var context = new BloggingContext()) { var searchTerm = "Lorem ipsum"; - var blogs = context.Blogs + var blogs = await context.Blogs .FromSql($"SELECT * FROM dbo.SearchBlogs({searchTerm})") .AsNoTracking() - .ToList(); + .ToListAsync(); } using (var context = new BloggingContext()) { - var ids = context.Database + var ids = await context.Database .SqlQuery($"SELECT [BlogId] FROM [Blogs]") - .ToList(); + .ToListAsync(); } using (var context = new BloggingContext()) { - var overAverageIds = context.Database + var overAverageIds = await context.Database .SqlQuery($"SELECT [BlogId] AS [Value] FROM [Blogs]") .Where(id => id > context.Blogs.Average(b => b.BlogId)) - .ToList(); + .ToListAsync(); } using (var context = new BloggingContext()) { - var rowsModified = context.Database.ExecuteSql($"UPDATE [Blogs] SET [Url] = NULL"); + var rowsModified = await context.Database.ExecuteSqlAsync($"UPDATE [Blogs] SET [Url] = NULL"); } } } diff --git a/samples/core/Querying/Tags/Program.cs b/samples/core/Querying/Tags/Program.cs index aad7e02154..a376d7db13 100644 --- a/samples/core/Querying/Tags/Program.cs +++ b/samples/core/Querying/Tags/Program.cs @@ -1,4 +1,5 @@ using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using NetTopologySuite.Geometries; @@ -6,37 +7,37 @@ namespace EFQuerying.Tags; internal class Program { - private static void Main(string[] args) + private static async Task Main(string[] args) { using (var context = new SpatialContext()) { - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } using (var context = new SpatialContext()) { #region BasicQueryTag var myLocation = new Point(1, 2); - var nearestPeople = (from f in context.People.TagWith("This is my spatial query!") + var nearestPeople = await (from f in context.People.TagWith("This is my spatial query!") orderby f.Location.Distance(myLocation) descending - select f).Take(5).ToList(); + select f).Take(5).ToListAsync(); #endregion } using (var context = new SpatialContext()) { #region ChainedQueryTags - var results = Limit(GetNearestPeople(context, new Point(1, 2)), 25).ToList(); + var results = await Limit(GetNearestPeople(context, new Point(1, 2)), 25).ToListAsync(); #endregion } using (var context = new SpatialContext()) { #region MultilineQueryTag - var results = Limit(GetNearestPeople(context, new Point(1, 2)), 25).TagWith( + var results = await Limit(GetNearestPeople(context, new Point(1, 2)), 25).TagWith( @"This is a multi-line -string").ToList(); +string").ToListAsync(); #endregion } } @@ -55,4 +56,4 @@ public class Person { public int Id { get; set; } public Point Location { get; set; } -} \ No newline at end of file +} diff --git a/samples/core/Querying/Tracking/Program.cs b/samples/core/Querying/Tracking/Program.cs index d5e39bc933..793e77067d 100644 --- a/samples/core/Querying/Tracking/Program.cs +++ b/samples/core/Querying/Tracking/Program.cs @@ -1,16 +1,17 @@ using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace EFQuerying.Tracking; internal class Program { - private static void Main(string[] args) + private static async Task Main(string[] args) { using (var context = new BloggingContext()) { - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } using (var context = new BloggingContext()) @@ -18,33 +19,33 @@ private static void Main(string[] args) // seeding database context.Blogs.Add(new Blog { Url = "http://sample.com/blog" }); context.Blogs.Add(new Blog { Url = "http://sample.com/another_blog" }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = new BloggingContext()) { #region Tracking - var blog = context.Blogs.SingleOrDefault(b => b.BlogId == 1); + var blog = await context.Blogs.SingleOrDefaultAsync(b => b.BlogId == 1); blog.Rating = 5; - context.SaveChanges(); + await context.SaveChangesAsync(); #endregion } using (var context = new BloggingContext()) { #region NoTracking - var blogs = context.Blogs + var blogs = await context.Blogs .AsNoTracking() - .ToList(); + .ToListAsync(); #endregion } using (var context = new BloggingContext()) { #region NoTrackingWithIdentityResolution - var blogs = context.Blogs + var blogs = await context.Blogs .AsNoTrackingWithIdentityResolution() - .ToList(); + .ToListAsync(); #endregion } @@ -53,7 +54,7 @@ private static void Main(string[] args) #region ContextDefaultTrackingBehavior context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; - var blogs = context.Blogs.ToList(); + var blogs = await context.Blogs.ToListAsync(); #endregion } @@ -90,11 +91,11 @@ private static void Main(string[] args) using (var context = new BloggingContext()) { #region ClientProjection - var blogs = context.Blogs + var blogs = await context.Blogs .OrderByDescending(blog => blog.Rating) .Select( blog => new { Id = blog.BlogId, Url = StandardizeUrl(blog) }) - .ToList(); + .ToListAsync(); #endregion } } @@ -112,4 +113,4 @@ public static string StandardizeUrl(Blog blog) return url; } #endregion -} \ No newline at end of file +} diff --git a/samples/core/Querying/UserDefinedFunctionMapping/Program.cs b/samples/core/Querying/UserDefinedFunctionMapping/Program.cs index a8057009fc..00ad3e3d38 100644 --- a/samples/core/Querying/UserDefinedFunctionMapping/Program.cs +++ b/samples/core/Querying/UserDefinedFunctionMapping/Program.cs @@ -1,17 +1,18 @@ using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace EFQuerying.UserDefinedFunctionMapping; internal class Program { - private static void Main(string[] args) + private static async Task Main(string[] args) { using var context = new BloggingContext(); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); - context.Database.ExecuteSqlRaw( + await context.Database.ExecuteSqlRawAsync( @"CREATE FUNCTION dbo.CommentedPostCountForBlog(@id int) RETURNS int AS @@ -24,7 +25,7 @@ FROM [Comments] AS [c] WHERE [p].[PostId] = [c].[PostId]) > 0)); END"); - context.Database.ExecuteSqlRaw( + await context.Database.ExecuteSqlRawAsync( @"CREATE FUNCTION [dbo].[ConcatStrings] (@prm1 nvarchar(max), @prm2 nvarchar(max)) RETURNS nvarchar(max) AS @@ -32,7 +33,7 @@ RETURNS nvarchar(max) RETURN @prm1 + @prm2; END"); - context.Database.ExecuteSqlRaw( + await context.Database.ExecuteSqlRawAsync( @"CREATE FUNCTION dbo.PostsWithPopularComments(@likeThreshold int) RETURNS TABLE AS @@ -51,13 +52,13 @@ FROM [Comments] AS [c] where context.ActivePostCountForBlog(b.BlogId) > 1 select b; #endregion - var result1 = query1.ToList(); + var result1 = await query1.ToListAsync(); #region HasTranslationQuery var query2 = from p in context.Posts select context.PercentageDifference(p.BlogId, 3); #endregion - var result2 = query2.ToList(); + var result2 = await query2.ToListAsync(); #region NullabilityPropagationExamples var query3 = context.Blogs.Where(e => context.ConcatStrings(e.Url, e.Rating.ToString()) != "https://mytravelblog.com/4"); @@ -65,8 +66,8 @@ where context.ActivePostCountForBlog(b.BlogId) > 1 e => context.ConcatStringsOptimized(e.Url, e.Rating.ToString()) != "https://mytravelblog.com/4"); #endregion - var result3 = query3.ToList(); - var result4 = query4.ToList(); + var result3 = await query3.ToListAsync(); + var result4 = await query4.ToListAsync(); #region TableValuedFunctionQuery var likeThreshold = 3; @@ -74,6 +75,6 @@ where context.ActivePostCountForBlog(b.BlogId) > 1 orderby p.Rating select p; #endregion - var result5 = query5.ToList(); + var result5 = await query5.ToListAsync(); } -} \ No newline at end of file +} diff --git a/samples/core/Saving/Basics/Sample.cs b/samples/core/Saving/Basics/Sample.cs index 6cbbf23793..73855c4fb7 100644 --- a/samples/core/Saving/Basics/Sample.cs +++ b/samples/core/Saving/Basics/Sample.cs @@ -1,15 +1,17 @@ using System.Linq; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; namespace EFSaving.Basics; public class Sample { - public static void Run() + public static async Task Run() { using (var context = new BloggingContext()) { - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } #region Add @@ -17,25 +19,25 @@ public static void Run() { var blog = new Blog { Url = "http://example.com" }; context.Blogs.Add(blog); - context.SaveChanges(); + await context.SaveChangesAsync(); } #endregion #region Update using (var context = new BloggingContext()) { - var blog = context.Blogs.Single(b => b.Url == "http://example.com"); + var blog = await context.Blogs.SingleAsync(b => b.Url == "http://example.com"); blog.Url = "http://example.com/blog"; - context.SaveChanges(); + await context.SaveChangesAsync(); } #endregion #region Remove using (var context = new BloggingContext()) { - var blog = context.Blogs.Single(b => b.Url == "http://example.com/blog"); + var blog = await context.Blogs.SingleAsync(b => b.Url == "http://example.com/blog"); context.Blogs.Remove(blog); - context.SaveChanges(); + await context.SaveChangesAsync(); } #endregion @@ -45,7 +47,7 @@ public static void Run() // seeding database context.Blogs.Add(new Blog { Url = "http://example.com/blog" }); context.Blogs.Add(new Blog { Url = "http://example.com/another_blog" }); - context.SaveChanges(); + await context.SaveChangesAsync(); } using (var context = new BloggingContext()) @@ -55,14 +57,14 @@ public static void Run() context.Blogs.Add(new Blog { Url = "http://example.com/blog_two" }); // update - var firstBlog = context.Blogs.First(); + var firstBlog = await context.Blogs.FirstAsync(); firstBlog.Url = ""; // remove - var lastBlog = context.Blogs.OrderBy(e => e.BlogId).Last(); + var lastBlog = await context.Blogs.OrderBy(e => e.BlogId).LastAsync(); context.Blogs.Remove(lastBlog); - context.SaveChanges(); + await context.SaveChangesAsync(); } #endregion } diff --git a/samples/core/Saving/CascadeDelete/BloggingContext.cs b/samples/core/Saving/CascadeDelete/BloggingContext.cs index 2c128250e9..b39ebca561 100644 --- a/samples/core/Saving/CascadeDelete/BloggingContext.cs +++ b/samples/core/Saving/CascadeDelete/BloggingContext.cs @@ -1,5 +1,7 @@ using System; using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Infrastructure; @@ -43,11 +45,11 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .OnDelete(DeleteBehavior) .IsRequired(RequiredRelationship); - public override int SaveChanges() + public override async Task SaveChangesAsync(CancellationToken cancellationToken = default) { LogMessages.Clear(); - return base.SaveChanges(); + return await base.SaveChangesAsync(cancellationToken); } public class DeleteBehaviorCacheKeyFactory : IModelCacheKeyFactory diff --git a/samples/core/Saving/CascadeDelete/Sample.cs b/samples/core/Saving/CascadeDelete/Sample.cs index ab3148f520..0daf63cdfb 100644 --- a/samples/core/Saving/CascadeDelete/Sample.cs +++ b/samples/core/Saving/CascadeDelete/Sample.cs @@ -1,46 +1,47 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace EFSaving.CascadeDelete; public class Sample { - public static void Run() + public static async Task Run() { - DeleteBehaviorSample(DeleteBehavior.Cascade, true); - DeleteBehaviorSample(DeleteBehavior.ClientSetNull, true); - DeleteBehaviorSample(DeleteBehavior.SetNull, true); - DeleteBehaviorSample(DeleteBehavior.Restrict, true); - - DeleteBehaviorSample(DeleteBehavior.Cascade, false); - DeleteBehaviorSample(DeleteBehavior.ClientSetNull, false); - DeleteBehaviorSample(DeleteBehavior.SetNull, false); - DeleteBehaviorSample(DeleteBehavior.Restrict, false); - - DeleteOrphansSample(DeleteBehavior.Cascade, true); - DeleteOrphansSample(DeleteBehavior.ClientSetNull, true); - DeleteOrphansSample(DeleteBehavior.SetNull, true); - DeleteOrphansSample(DeleteBehavior.Restrict, true); - - DeleteOrphansSample(DeleteBehavior.Cascade, false); - DeleteOrphansSample(DeleteBehavior.ClientSetNull, false); - DeleteOrphansSample(DeleteBehavior.SetNull, false); - DeleteOrphansSample(DeleteBehavior.Restrict, false); + await DeleteBehaviorSample(DeleteBehavior.Cascade, true); + await DeleteBehaviorSample(DeleteBehavior.ClientSetNull, true); + await DeleteBehaviorSample(DeleteBehavior.SetNull, true); + await DeleteBehaviorSample(DeleteBehavior.Restrict, true); + + await DeleteBehaviorSample(DeleteBehavior.Cascade, false); + await DeleteBehaviorSample(DeleteBehavior.ClientSetNull, false); + await DeleteBehaviorSample(DeleteBehavior.SetNull, false); + await DeleteBehaviorSample(DeleteBehavior.Restrict, false); + + await DeleteOrphansSample(DeleteBehavior.Cascade, true); + await DeleteOrphansSample(DeleteBehavior.ClientSetNull, true); + await DeleteOrphansSample(DeleteBehavior.SetNull, true); + await DeleteOrphansSample(DeleteBehavior.Restrict, true); + + await DeleteOrphansSample(DeleteBehavior.Cascade, false); + await DeleteOrphansSample(DeleteBehavior.ClientSetNull, false); + await DeleteOrphansSample(DeleteBehavior.SetNull, false); + await DeleteOrphansSample(DeleteBehavior.Restrict, false); } - private static void DeleteBehaviorSample(DeleteBehavior deleteBehavior, bool requiredRelationship) + private static async Task DeleteBehaviorSample(DeleteBehavior deleteBehavior, bool requiredRelationship) { Console.WriteLine( $"Test using DeleteBehavior.{deleteBehavior} with {(requiredRelationship ? "required" : "optional")} relationship:"); - InitializeDatabase(requiredRelationship); + await InitializeDatabase(requiredRelationship); using var context = new BloggingContext(deleteBehavior, requiredRelationship); #region DeleteBehaviorVariations - var blog = context.Blogs.Include(b => b.Posts).First(); + var blog = await context.Blogs.Include(b => b.Posts).FirstAsync(); var posts = blog.Posts.ToList(); DumpEntities(" After loading entities:", context, blog, posts); @@ -54,7 +55,7 @@ private static void DeleteBehaviorSample(DeleteBehavior deleteBehavior, bool req Console.WriteLine(); Console.WriteLine(" Saving changes:"); - context.SaveChanges(); + await context.SaveChangesAsync(); DumpSql(); @@ -73,17 +74,17 @@ private static void DeleteBehaviorSample(DeleteBehavior deleteBehavior, bool req Console.WriteLine(); } - private static void DeleteOrphansSample(DeleteBehavior deleteBehavior, bool requiredRelationship) + private static async Task DeleteOrphansSample(DeleteBehavior deleteBehavior, bool requiredRelationship) { Console.WriteLine( $"Test deleting orphans with DeleteBehavior.{deleteBehavior} and {(requiredRelationship ? "a required" : "an optional")} relationship:"); - InitializeDatabase(requiredRelationship); + await InitializeDatabase(requiredRelationship); using var context = new BloggingContext(deleteBehavior, requiredRelationship); #region DeleteOrphansVariations - var blog = context.Blogs.Include(b => b.Posts).First(); + var blog = await context.Blogs.Include(b => b.Posts).FirstAsync(); var posts = blog.Posts.ToList(); DumpEntities(" After loading entities:", context, blog, posts); @@ -97,7 +98,7 @@ private static void DeleteOrphansSample(DeleteBehavior deleteBehavior, bool requ Console.WriteLine(); Console.WriteLine(" Saving changes:"); - context.SaveChanges(); + await context.SaveChangesAsync(); DumpSql(); @@ -116,11 +117,11 @@ private static void DeleteOrphansSample(DeleteBehavior deleteBehavior, bool requ Console.WriteLine(); } - private static void InitializeDatabase(bool requiredRelationship) + private static async Task InitializeDatabase(bool requiredRelationship) { using var context = new BloggingContext(DeleteBehavior.ClientSetNull, requiredRelationship); - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); context.Blogs.Add( new Blog @@ -129,7 +130,7 @@ private static void InitializeDatabase(bool requiredRelationship) Posts = new List { new Post { Title = "Saving Data with EF" }, new Post { Title = "Cascade Delete with EF" } } }); - context.SaveChanges(); + await context.SaveChangesAsync(); } private static void DumpEntities(string message, BloggingContext context, Blog blog, IList posts) @@ -158,4 +159,4 @@ private static void DumpSql() Console.WriteLine(" " + logMessage); } } -} \ No newline at end of file +} diff --git a/samples/core/Saving/Concurrency/BasicSample.cs b/samples/core/Saving/Concurrency/BasicSample.cs index 933530b175..76f3b6037e 100644 --- a/samples/core/Saving/Concurrency/BasicSample.cs +++ b/samples/core/Saving/Concurrency/BasicSample.cs @@ -1,62 +1,63 @@ using System; using System.ComponentModel.DataAnnotations; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace EFSaving.Concurrency; public class BasicSample { - public static void Run() + public static async Task Run() { // Ensure database is created and has a person in it using (var setupContext = new PersonContext()) { - setupContext.Database.EnsureDeleted(); - setupContext.Database.EnsureCreated(); + await setupContext.Database.EnsureDeletedAsync(); + await setupContext.Database.EnsureCreatedAsync(); setupContext.People.Add(new Person { FirstName = "John", LastName = "Doe" }); setupContext.People.Add(new Person { FirstName = "Marie", LastName = "Jane" }); - setupContext.SaveChanges(); + await setupContext.SaveChangesAsync(); } - SuccessfulUpdate(); - ConcurrencyFailure(); + await SuccessfulUpdate(); + await ConcurrencyFailure(); } // This shows a successful update, where no concurrent change happens - private static void SuccessfulUpdate() + private static async Task SuccessfulUpdate() { using var context = new PersonContext(); - var person = context.People.Single(b => b.FirstName == "John"); + var person = await context.People.SingleAsync(b => b.FirstName == "John"); person.FirstName = "Paul"; - context.SaveChanges(); + await context.SaveChangesAsync(); Console.WriteLine("The change completed successfully."); } // This simulates a concurrency failure by modifying the row via another context after it was loaded. - private static void ConcurrencyFailure() + private static async Task ConcurrencyFailure() { using var context1 = new PersonContext(); - var person = context1.People.Single(b => b.FirstName == "Marie"); + var person = await context1.People.SingleAsync(b => b.FirstName == "Marie"); person.FirstName = "Stephanie"; // We loaded the Blog instance - along with its concurrency token - and made a change on it. // Let's simulate a concurrent change by updating the row from another context using (var context2 = new PersonContext()) { - var person2 = context2.People.Single(b => b.FirstName == "Marie"); + var person2 = await context2.People.SingleAsync(b => b.FirstName == "Marie"); person2.FirstName = "Rachel"; - context2.SaveChanges(); + await context2.SaveChangesAsync(); } // The tracked person in EF's change tracker has an out of date concurrency token, so calling SaveChanges will now throw // a DbUpdateConcurrencyException Console.WriteLine("SaveChanges should now throw:"); - context1.SaveChanges(); + await context1.SaveChangesAsync(); } public class PersonContext : DbContext diff --git a/samples/core/Saving/Concurrency/ConflictResolutionSample.cs b/samples/core/Saving/Concurrency/ConflictResolutionSample.cs index 4e6b1c8850..1b87155cca 100644 --- a/samples/core/Saving/Concurrency/ConflictResolutionSample.cs +++ b/samples/core/Saving/Concurrency/ConflictResolutionSample.cs @@ -1,32 +1,33 @@ using System; using System.ComponentModel.DataAnnotations; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace EFSaving.Concurrency; public class ConflictResolutionSample { - public static void Run() + public static async Task Run() { // Ensure database is created and has a person in it using (var setupContext = new PersonContext()) { - setupContext.Database.EnsureDeleted(); - setupContext.Database.EnsureCreated(); + await setupContext.Database.EnsureDeletedAsync(); + await setupContext.Database.EnsureCreatedAsync(); setupContext.People.Add(new Person { FirstName = "John", LastName = "Doe" }); - setupContext.SaveChanges(); + await setupContext.SaveChangesAsync(); } #region ConcurrencyHandlingCode using var context = new PersonContext(); // Fetch a person from database and change phone number - var person = context.People.Single(p => p.PersonId == 1); + var person = await context.People.SingleAsync(p => p.PersonId == 1); person.PhoneNumber = "555-555-5555"; // Change the person's name in the database to simulate a concurrency conflict - context.Database.ExecuteSqlRaw( + await context.Database.ExecuteSqlRawAsync( "UPDATE dbo.People SET FirstName = 'Jane' WHERE PersonId = 1"); var saved = false; @@ -35,7 +36,7 @@ public static void Run() try { // Attempt to save changes to the database - context.SaveChanges(); + await context.SaveChangesAsync(); saved = true; } catch (DbUpdateConcurrencyException ex) @@ -45,7 +46,7 @@ public static void Run() if (entry.Entity is Person) { var proposedValues = entry.CurrentValues; - var databaseValues = entry.GetDatabaseValues(); + var databaseValues = await entry.GetDatabaseValuesAsync(); foreach (var property in proposedValues.Properties) { diff --git a/samples/core/Saving/Disconnected/Sample.cs b/samples/core/Saving/Disconnected/Sample.cs index d89235ab7c..9da1d50fa8 100644 --- a/samples/core/Saving/Disconnected/Sample.cs +++ b/samples/core/Saving/Disconnected/Sample.cs @@ -1,32 +1,33 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace EFSaving.Disconnected; public class Sample { - public static void Run() + public static async Task Run() { using (var context = new BloggingContext()) { - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } - IsItNew(); - InsertAndUpdateSingleEntity(); - InsertOrUpdateSingleEntityStoreGenerated(); - InsertOrUpdateSingleEntityFind(); - InsertAndUpdateGraph(); - InsertOrUpdateGraphStoreGenerated(); - InsertOrUpdateGraphFind(); - InsertUpdateOrDeleteGraphFind(); - InsertUpdateOrDeleteTrackGraph(); + await IsItNew(); + await InsertAndUpdateSingleEntity(); + await InsertOrUpdateSingleEntityStoreGenerated(); + await InsertOrUpdateSingleEntityFind(); + await InsertAndUpdateGraph(); + await InsertOrUpdateGraphStoreGenerated(); + await InsertOrUpdateGraphFind(); + await InsertUpdateOrDeleteGraphFind(); + await InsertUpdateOrDeleteTrackGraph(); } - private static void IsItNew() + private static async Task IsItNew() { Console.WriteLine(); Console.WriteLine("Show entity-specific check for key set:"); @@ -38,7 +39,7 @@ private static void IsItNew() Console.WriteLine($" Blog entity is {(IsItNew(blog) ? "new" : "existing")}."); context.Add(blog); - context.SaveChanges(); + await context.SaveChangesAsync(); // Key is now set Console.WriteLine($" Blog entity is {(IsItNew(blog) ? "new" : "existing")}."); @@ -54,7 +55,7 @@ private static void IsItNew() Console.WriteLine($" Blog entity is {(IsItNew(context, (object)blog) ? "new" : "existing")}."); context.Add(blog); - context.SaveChanges(); + await context.SaveChangesAsync(); // Key is now set Console.WriteLine($" Blog entity is {(IsItNew(context, (object)blog) ? "new" : "existing")}."); @@ -81,16 +82,16 @@ private static void IsItNew() { var blog = new Blog { Url = "http://sample.com" }; - Console.WriteLine($" Blog entity is {(IsItNew(context, blog) ? "new" : "existing")}."); + Console.WriteLine($" Blog entity is {(await IsItNew(context, blog) ? "new" : "existing")}."); context.Add(blog); - context.SaveChanges(); + await context.SaveChangesAsync(); - Console.WriteLine($" Blog entity is {(IsItNew(context, blog) ? "new" : "existing")}."); + Console.WriteLine($" Blog entity is {(await IsItNew(context, blog) ? "new" : "existing")}."); } } - private static void InsertAndUpdateSingleEntity() + private static async Task InsertAndUpdateSingleEntity() { Console.WriteLine(); Console.WriteLine("Save single entity with explicit insert or update:"); @@ -99,28 +100,28 @@ private static void InsertAndUpdateSingleEntity() using (var context = new BloggingContext()) { Console.WriteLine($" Inserting with URL {blog.Url}"); - Insert(context, blog); + await Insert(context, blog); } using (var context = new BloggingContext()) { - Console.WriteLine($" Found with URL {context.Blogs.Single(b => b.BlogId == blog.BlogId).Url}"); + Console.WriteLine($" Found with URL {(await context.Blogs.SingleAsync(b => b.BlogId == blog.BlogId)).Url}"); } using (var context = new BloggingContext()) { blog.Url = "https://sample.com"; Console.WriteLine($" Updating with URL {blog.Url}"); - Update(context, blog); + await Update(context, blog); } using (var context = new BloggingContext()) { - Console.WriteLine($" Found with URL {(context.Blogs.Single(b => b.BlogId == blog.BlogId)).Url}"); + Console.WriteLine($" Found with URL {((await context.Blogs.SingleAsync(b => b.BlogId == blog.BlogId))).Url}"); } } - private static void InsertOrUpdateSingleEntityStoreGenerated() + private static async Task InsertOrUpdateSingleEntityStoreGenerated() { Console.WriteLine(); Console.WriteLine("Save single entity with auto-generated key:"); @@ -129,28 +130,28 @@ private static void InsertOrUpdateSingleEntityStoreGenerated() using (var context = new BloggingContext()) { Console.WriteLine($" Inserting with URL {blog.Url}"); - InsertOrUpdate(context, (object)blog); + await InsertOrUpdate(context, (object)blog); } using (var context = new BloggingContext()) { - Console.WriteLine($" Found with URL {context.Blogs.Single(b => b.BlogId == blog.BlogId).Url}"); + Console.WriteLine($" Found with URL {(await context.Blogs.SingleAsync(b => b.BlogId == blog.BlogId)).Url}"); } using (var context = new BloggingContext()) { blog.Url = "https://sample.com"; Console.WriteLine($" Updating with URL {blog.Url}"); - InsertOrUpdate(context, (object)blog); + await InsertOrUpdate(context, (object)blog); } using (var context = new BloggingContext()) { - Console.WriteLine($" Found with URL {(context.Blogs.Single(b => b.BlogId == blog.BlogId)).Url}"); + Console.WriteLine($" Found with URL {((await context.Blogs.SingleAsync(b => b.BlogId == blog.BlogId))).Url}"); } } - private static void InsertOrUpdateSingleEntityFind() + private static async Task InsertOrUpdateSingleEntityFind() { Console.WriteLine(); Console.WriteLine("Save single entity with any kind of key:"); @@ -159,28 +160,28 @@ private static void InsertOrUpdateSingleEntityFind() using (var context = new BloggingContext()) { Console.WriteLine($" Inserting with URL {blog.Url}"); - InsertOrUpdate(context, blog); + await InsertOrUpdate(context, blog); } using (var context = new BloggingContext()) { - Console.WriteLine($" Found with URL {context.Blogs.Single(b => b.BlogId == blog.BlogId).Url}"); + Console.WriteLine($" Found with URL {(await context.Blogs.SingleAsync(b => b.BlogId == blog.BlogId)).Url}"); } using (var context = new BloggingContext()) { blog.Url = "https://sample.com"; Console.WriteLine($" Updating with URL {blog.Url}"); - InsertOrUpdate(context, blog); + await InsertOrUpdate(context, blog); } using (var context = new BloggingContext()) { - Console.WriteLine($" Found with URL {context.Blogs.Single(b => b.BlogId == blog.BlogId).Url}"); + Console.WriteLine($" Found with URL {(await context.Blogs.SingleAsync(b => b.BlogId == blog.BlogId)).Url}"); } } - private static void InsertAndUpdateGraph() + private static async Task InsertAndUpdateGraph() { Console.WriteLine(); Console.WriteLine("Save graph with explicit insert or update:"); @@ -189,12 +190,12 @@ private static void InsertAndUpdateGraph() using (var context = new BloggingContext()) { Console.WriteLine($" Inserting with URL {blog.Url} and {blog.Posts[0].Title}, {blog.Posts[1].Title}"); - InsertGraph(context, blog); + await InsertGraph(context, blog); } using (var context = new BloggingContext()) { - var read = context.Blogs.Include(b => b.Posts).Single(b => b.BlogId == blog.BlogId); + var read = await context.Blogs.Include(b => b.Posts).SingleAsync(b => b.BlogId == blog.BlogId); Console.WriteLine($" Found with URL {read.Url} and {read.Posts[0].Title}, {read.Posts[1].Title}"); } @@ -205,17 +206,17 @@ private static void InsertAndUpdateGraph() blog.Posts[1].Title = "Post B"; Console.WriteLine($" Updating with URL {blog.Url}"); - UpdateGraph(context, blog); + await UpdateGraph(context, blog); } using (var context = new BloggingContext()) { - var read = context.Blogs.Include(b => b.Posts).Single(b => b.BlogId == blog.BlogId); + var read = await context.Blogs.Include(b => b.Posts).SingleAsync(b => b.BlogId == blog.BlogId); Console.WriteLine($" Found with URL {read.Url} and {read.Posts[0].Title}, {read.Posts[1].Title}"); } } - private static void InsertOrUpdateGraphStoreGenerated() + private static async Task InsertOrUpdateGraphStoreGenerated() { Console.WriteLine(); Console.WriteLine("Save graph with auto-generated key:"); @@ -224,12 +225,12 @@ private static void InsertOrUpdateGraphStoreGenerated() using (var context = new BloggingContext()) { Console.WriteLine($" Inserting with URL {blog.Url} and {blog.Posts[0].Title}, {blog.Posts[1].Title}"); - InsertOrUpdateGraph(context, (object)blog); + await InsertOrUpdateGraph(context, (object)blog); } using (var context = new BloggingContext()) { - var read = context.Blogs.Include(b => b.Posts).Single(b => b.BlogId == blog.BlogId); + var read = await context.Blogs.Include(b => b.Posts).SingleAsync(b => b.BlogId == blog.BlogId); Console.WriteLine($" Found with URL {read.Url} and {read.Posts[0].Title}, {read.Posts[1].Title}"); } @@ -241,17 +242,17 @@ private static void InsertOrUpdateGraphStoreGenerated() blog.Posts.Add(new Post { Title = "New Post" }); Console.WriteLine($" Updating with URL {blog.Url}"); - InsertOrUpdateGraph(context, (object)blog); + await InsertOrUpdateGraph(context, (object)blog); } using (var context = new BloggingContext()) { - var read = context.Blogs.Include(b => b.Posts).Single(b => b.BlogId == blog.BlogId); + var read = await context.Blogs.Include(b => b.Posts).SingleAsync(b => b.BlogId == blog.BlogId); Console.WriteLine($" Found with URL {read.Url} and {read.Posts[0].Title}, {read.Posts[1].Title}, {read.Posts[2].Title}"); } } - private static void InsertOrUpdateGraphFind() + private static async Task InsertOrUpdateGraphFind() { Console.WriteLine(); Console.WriteLine("Save graph with any kind of key:"); @@ -260,12 +261,12 @@ private static void InsertOrUpdateGraphFind() using (var context = new BloggingContext()) { Console.WriteLine($" Inserting with URL {blog.Url} and {blog.Posts[0].Title}, {blog.Posts[1].Title}"); - InsertOrUpdateGraph(context, blog); + await InsertOrUpdateGraph(context, blog); } using (var context = new BloggingContext()) { - var read = context.Blogs.Include(b => b.Posts).Single(b => b.BlogId == blog.BlogId); + var read = await context.Blogs.Include(b => b.Posts).SingleAsync(b => b.BlogId == blog.BlogId); Console.WriteLine($" Found with URL {read.Url} and {read.Posts[0].Title}, {read.Posts[1].Title}"); } @@ -277,17 +278,17 @@ private static void InsertOrUpdateGraphFind() blog.Posts.Add(new Post { Title = "New Post" }); Console.WriteLine($" Updating with URL {blog.Url}"); - InsertOrUpdateGraph(context, blog); + await InsertOrUpdateGraph(context, blog); } using (var context = new BloggingContext()) { - var read = context.Blogs.Include(b => b.Posts).Single(b => b.BlogId == blog.BlogId); + var read = await context.Blogs.Include(b => b.Posts).SingleAsync(b => b.BlogId == blog.BlogId); Console.WriteLine($" Found with URL {read.Url} and {read.Posts[0].Title}, {read.Posts[1].Title}, {read.Posts[2].Title}"); } } - private static void InsertUpdateOrDeleteGraphFind() + private static async Task InsertUpdateOrDeleteGraphFind() { Console.WriteLine(); Console.WriteLine("Save graph with deletes and any kind of key:"); @@ -296,12 +297,12 @@ private static void InsertUpdateOrDeleteGraphFind() using (var context = new BloggingContext()) { Console.WriteLine($" Inserting with URL {blog.Url} and {blog.Posts[0].Title}, {blog.Posts[1].Title}"); - InsertUpdateOrDeleteGraph(context, blog); + await InsertUpdateOrDeleteGraph(context, blog); } using (var context = new BloggingContext()) { - var read = context.Blogs.Include(b => b.Posts).Single(b => b.BlogId == blog.BlogId); + var read = await context.Blogs.Include(b => b.Posts).SingleAsync(b => b.BlogId == blog.BlogId); Console.WriteLine($" Found with URL {read.Url} and {read.Posts[0].Title}, {read.Posts[1].Title}"); } @@ -313,17 +314,17 @@ private static void InsertUpdateOrDeleteGraphFind() blog.Posts.Add(new Post { Title = "New Post" }); Console.WriteLine($" Updating with URL {blog.Url}"); - InsertUpdateOrDeleteGraph(context, blog); + await InsertUpdateOrDeleteGraph(context, blog); } using (var context = new BloggingContext()) { - var read = context.Blogs.Include(b => b.Posts).Single(b => b.BlogId == blog.BlogId); + var read = await context.Blogs.Include(b => b.Posts).SingleAsync(b => b.BlogId == blog.BlogId); Console.WriteLine($" Found with URL {read.Url} and {read.Posts[0].Title}, {read.Posts[1].Title}"); } } - private static void InsertUpdateOrDeleteTrackGraph() + private static async Task InsertUpdateOrDeleteTrackGraph() { Console.WriteLine(); Console.WriteLine("Save graph using TrackGraph:"); @@ -335,12 +336,12 @@ private static void InsertUpdateOrDeleteTrackGraph() using (var context = new BloggingContext()) { Console.WriteLine($" Inserting with URL {blog.Url} and {blog.Posts[0].Title}, {blog.Posts[1].Title}"); - SaveAnnotatedGraph(context, blog); + await SaveAnnotatedGraph(context, blog); } using (var context = new BloggingContext()) { - var read = context.Blogs.Include(b => b.Posts).Single(b => b.BlogId == blog.BlogId); + var read = await context.Blogs.Include(b => b.Posts).SingleAsync(b => b.BlogId == blog.BlogId); Console.WriteLine($" Found with URL {read.Url} and {read.Posts[0].Title}, {read.Posts[1].Title}"); } @@ -358,12 +359,12 @@ private static void InsertUpdateOrDeleteTrackGraph() blog.Posts.Add(new Post { Title = "New Post", IsNew = true }); Console.WriteLine($" Updating with URL {blog.Url}"); - SaveAnnotatedGraph(context, blog); + await SaveAnnotatedGraph(context, blog); } using (var context = new BloggingContext()) { - var read = context.Blogs.Include(b => b.Posts).Single(b => b.BlogId == blog.BlogId); + var read = await context.Blogs.Include(b => b.Posts).SingleAsync(b => b.BlogId == blog.BlogId); Console.WriteLine($" Found with URL {read.Url} and {read.Posts[0].Title}, {read.Posts[1].Title}"); } } @@ -379,36 +380,36 @@ public static bool IsItNew(DbContext context, object entity) #endregion #region IsItNewQuery - public static bool IsItNew(BloggingContext context, Blog blog) - => context.Blogs.Find(blog.BlogId) == null; + public static async Task IsItNew(BloggingContext context, Blog blog) + => (await context.Blogs.FindAsync(blog.BlogId)) == null; #endregion #region InsertAndUpdateSingleEntity - public static void Insert(DbContext context, object entity) + public static async Task Insert(DbContext context, object entity) { context.Add(entity); - context.SaveChanges(); + await context.SaveChangesAsync(); } - public static void Update(DbContext context, object entity) + public static async Task Update(DbContext context, object entity) { context.Update(entity); - context.SaveChanges(); + await context.SaveChangesAsync(); } #endregion #region InsertOrUpdateSingleEntity - public static void InsertOrUpdate(DbContext context, object entity) + public static async Task InsertOrUpdate(DbContext context, object entity) { context.Update(entity); - context.SaveChanges(); + await context.SaveChangesAsync(); } #endregion #region InsertOrUpdateSingleEntityWithFind - public static void InsertOrUpdate(BloggingContext context, Blog blog) + public static async Task InsertOrUpdate(BloggingContext context, Blog blog) { - var existingBlog = context.Blogs.Find(blog.BlogId); + var existingBlog = await context.Blogs.FindAsync(blog.BlogId); if (existingBlog == null) { context.Add(blog); @@ -418,7 +419,7 @@ public static void InsertOrUpdate(BloggingContext context, Blog blog) context.Entry(existingBlog).CurrentValues.SetValues(blog); } - context.SaveChanges(); + await context.SaveChangesAsync(); } #endregion @@ -435,35 +436,35 @@ private static Blog CreateBlogAndPosts() } #region InsertGraph - public static void InsertGraph(DbContext context, object rootEntity) + public static async Task InsertGraph(DbContext context, object rootEntity) { context.Add(rootEntity); - context.SaveChanges(); + await context.SaveChangesAsync(); } #endregion #region UpdateGraph - public static void UpdateGraph(DbContext context, object rootEntity) + public static async Task UpdateGraph(DbContext context, object rootEntity) { context.Update(rootEntity); - context.SaveChanges(); + await context.SaveChangesAsync(); } #endregion #region InsertOrUpdateGraph - public static void InsertOrUpdateGraph(DbContext context, object rootEntity) + public static async Task InsertOrUpdateGraph(DbContext context, object rootEntity) { context.Update(rootEntity); - context.SaveChanges(); + await context.SaveChangesAsync(); } #endregion #region InsertOrUpdateGraphWithFind - public static void InsertOrUpdateGraph(BloggingContext context, Blog blog) + public static async Task InsertOrUpdateGraph(BloggingContext context, Blog blog) { - var existingBlog = context.Blogs + var existingBlog = await context.Blogs .Include(b => b.Posts) - .FirstOrDefault(b => b.BlogId == blog.BlogId); + .FirstOrDefaultAsync(b => b.BlogId == blog.BlogId); if (existingBlog == null) { @@ -488,16 +489,16 @@ public static void InsertOrUpdateGraph(BloggingContext context, Blog blog) } } - context.SaveChanges(); + await context.SaveChangesAsync(); } #endregion #region InsertUpdateOrDeleteGraphWithFind - public static void InsertUpdateOrDeleteGraph(BloggingContext context, Blog blog) + public static async Task InsertUpdateOrDeleteGraph(BloggingContext context, Blog blog) { - var existingBlog = context.Blogs + var existingBlog = await context.Blogs .Include(b => b.Posts) - .FirstOrDefault(b => b.BlogId == blog.BlogId); + .FirstOrDefaultAsync(b => b.BlogId == blog.BlogId); if (existingBlog == null) { @@ -530,12 +531,12 @@ public static void InsertUpdateOrDeleteGraph(BloggingContext context, Blog blog) } } - context.SaveChanges(); + await context.SaveChangesAsync(); } #endregion #region TrackGraph - public static void SaveAnnotatedGraph(DbContext context, object rootEntity) + public static async Task SaveAnnotatedGraph(DbContext context, object rootEntity) { context.ChangeTracker.TrackGraph( rootEntity, @@ -551,7 +552,7 @@ public static void SaveAnnotatedGraph(DbContext context, object rootEntity) : EntityState.Unchanged; }); - context.SaveChanges(); + await context.SaveChangesAsync(); } #endregion -} \ No newline at end of file +} diff --git a/samples/core/Saving/Program.cs b/samples/core/Saving/Program.cs index 146b91759c..861e1463ee 100644 --- a/samples/core/Saving/Program.cs +++ b/samples/core/Saving/Program.cs @@ -1,21 +1,22 @@ -using EFSaving.Basics; +using System.Threading.Tasks; +using EFSaving.Basics; using EFSaving.Transactions; namespace EFSaving; internal class Program { - private static void Main(string[] args) + private static async Task Main(string[] args) { - Sample.Run(); - RelatedData.Sample.Run(); - CascadeDelete.Sample.Run(); - Concurrency.BasicSample.Run(); - Concurrency.ConflictResolutionSample.Run(); - ControllingTransaction.Run(); - ManagingSavepoints.Run(); - SharingTransaction.Run(); - ExternalDbTransaction.Run(); - Disconnected.Sample.Run(); + await Sample.Run(); + await RelatedData.Sample.Run(); + await CascadeDelete.Sample.Run(); + await Concurrency.BasicSample.Run(); + await Concurrency.ConflictResolutionSample.Run(); + await ControllingTransaction.Run(); + await ManagingSavepoints.Run(); + await SharingTransaction.Run(); + await ExternalDbTransaction.Run(); + await Disconnected.Sample.Run(); } } diff --git a/samples/core/Saving/RelatedData/Sample.cs b/samples/core/Saving/RelatedData/Sample.cs index 1ad2df56b1..83d03cda51 100644 --- a/samples/core/Saving/RelatedData/Sample.cs +++ b/samples/core/Saving/RelatedData/Sample.cs @@ -1,17 +1,18 @@ using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace EFSaving.RelatedData; public class Sample { - public static void Run() + public static async Task Run() { using (var context = new BloggingContext()) { - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } #region AddingGraphOfEntities @@ -29,18 +30,18 @@ public static void Run() }; context.Blogs.Add(blog); - context.SaveChanges(); + await context.SaveChangesAsync(); } #endregion #region AddingRelatedEntity using (var context = new BloggingContext()) { - var blog = context.Blogs.Include(b => b.Posts).First(); + var blog = await context.Blogs.Include(b => b.Posts).FirstAsync(); var post = new Post { Title = "Intro to EF Core" }; blog.Posts.Add(post); - context.SaveChanges(); + await context.SaveChangesAsync(); } #endregion @@ -48,21 +49,21 @@ public static void Run() using (var context = new BloggingContext()) { var blog = new Blog { Url = "http://blogs.msdn.com/visualstudio" }; - var post = context.Posts.First(); + var post = await context.Posts.FirstAsync(); post.Blog = blog; - context.SaveChanges(); + await context.SaveChangesAsync(); } #endregion #region RemovingRelationships using (var context = new BloggingContext()) { - var blog = context.Blogs.Include(b => b.Posts).First(); + var blog = await context.Blogs.Include(b => b.Posts).FirstAsync(); var post = blog.Posts.First(); blog.Posts.Remove(post); - context.SaveChanges(); + await context.SaveChangesAsync(); } #endregion } diff --git a/samples/core/Saving/Transactions/AmbientTransaction.cs b/samples/core/Saving/Transactions/AmbientTransaction.cs index b5ef4100be..55e9b29c88 100644 --- a/samples/core/Saving/Transactions/AmbientTransaction.cs +++ b/samples/core/Saving/Transactions/AmbientTransaction.cs @@ -1,4 +1,5 @@ using System; +using System.Threading.Tasks; using System.Transactions; using Microsoft.Data.SqlClient; using Microsoft.EntityFrameworkCore; @@ -7,7 +8,7 @@ namespace EFSaving.Transactions; public class AmbientTransaction { - public static void Run() + public static async Task Run() { var connectionString = @"Server=(localdb)\mssqllocaldb;Database=EFSaving.Transactions;Trusted_Connection=True;ConnectRetryCount=0"; @@ -17,8 +18,8 @@ public static void Run() .UseSqlServer(connectionString) .Options)) { - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } #region Transaction @@ -27,14 +28,14 @@ public static void Run() new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted })) { using var connection = new SqlConnection(connectionString); - connection.Open(); + await connection.OpenAsync(); try { // Run raw ADO.NET command in the transaction var command = connection.CreateCommand(); command.CommandText = "DELETE FROM dbo.Blogs"; - command.ExecuteNonQuery(); + await command.ExecuteNonQueryAsync(); // Run an EF Core command in the transaction var options = new DbContextOptionsBuilder() @@ -44,7 +45,7 @@ public static void Run() using (var context = new BloggingContext(options)) { context.Blogs.Add(new Blog { Url = "http://blogs.msdn.com/dotnet" }); - context.SaveChanges(); + await context.SaveChangesAsync(); } // Commit transaction if all commands succeed, transaction will auto-rollback diff --git a/samples/core/Saving/Transactions/CommitableTransaction.cs b/samples/core/Saving/Transactions/CommitableTransaction.cs index d68e285fd8..dd834bd477 100644 --- a/samples/core/Saving/Transactions/CommitableTransaction.cs +++ b/samples/core/Saving/Transactions/CommitableTransaction.cs @@ -1,4 +1,5 @@ using System; +using System.Threading.Tasks; using System.Transactions; using Microsoft.Data.SqlClient; using Microsoft.EntityFrameworkCore; @@ -7,7 +8,7 @@ namespace EFSaving.Transactions; public class CommitableTransaction { - public static void Run() + public static async Task Run() { var connectionString = @"Server=(localdb)\mssqllocaldb;Database=EFSaving.Transactions;Trusted_Connection=True;ConnectRetryCount=0"; @@ -17,8 +18,8 @@ public static void Run() .UseSqlServer(connectionString) .Options)) { - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } #region Transaction @@ -35,18 +36,18 @@ public static void Run() using (var context = new BloggingContext(options)) { - context.Database.OpenConnection(); + await context.Database.OpenConnectionAsync(); context.Database.EnlistTransaction(transaction); // Run raw ADO.NET command in the transaction var command = connection.CreateCommand(); command.CommandText = "DELETE FROM dbo.Blogs"; - command.ExecuteNonQuery(); + await command.ExecuteNonQueryAsync(); // Run an EF Core command in the transaction context.Blogs.Add(new Blog { Url = "http://blogs.msdn.com/dotnet" }); - context.SaveChanges(); - context.Database.CloseConnection(); + await context.SaveChangesAsync(); + await context.Database.CloseConnectionAsync(); } // Commit transaction if all commands succeed, transaction will auto-rollback diff --git a/samples/core/Saving/Transactions/ControllingTransaction.cs b/samples/core/Saving/Transactions/ControllingTransaction.cs index 363c66346d..e4b3ef5845 100644 --- a/samples/core/Saving/Transactions/ControllingTransaction.cs +++ b/samples/core/Saving/Transactions/ControllingTransaction.cs @@ -1,38 +1,39 @@ using System; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace EFSaving.Transactions; public class ControllingTransaction { - public static void Run() + public static async Task Run() { using (var setupContext = new BloggingContext()) { - setupContext.Database.EnsureDeleted(); - setupContext.Database.EnsureCreated(); + await setupContext.Database.EnsureDeletedAsync(); + await setupContext.Database.EnsureCreatedAsync(); } #region Transaction using var context = new BloggingContext(); - using var transaction = context.Database.BeginTransaction(); + using var transaction = await context.Database.BeginTransactionAsync(); try { context.Blogs.Add(new Blog { Url = "http://blogs.msdn.com/dotnet" }); - context.SaveChanges(); + await context.SaveChangesAsync(); context.Blogs.Add(new Blog { Url = "http://blogs.msdn.com/visualstudio" }); - context.SaveChanges(); + await context.SaveChangesAsync(); - var blogs = context.Blogs + var blogs = await context.Blogs .OrderBy(b => b.Url) - .ToList(); + .ToListAsync(); // Commit transaction if all commands succeed, transaction will auto-rollback // when disposed if either commands fails - transaction.Commit(); + await transaction.CommitAsync(); } catch (Exception) { diff --git a/samples/core/Saving/Transactions/ExternalDbTransaction.cs b/samples/core/Saving/Transactions/ExternalDbTransaction.cs index 62fe8a4aa2..d7fa2d3bb6 100644 --- a/samples/core/Saving/Transactions/ExternalDbTransaction.cs +++ b/samples/core/Saving/Transactions/ExternalDbTransaction.cs @@ -1,4 +1,5 @@ using System; +using System.Threading.Tasks; using Microsoft.Data.SqlClient; using Microsoft.EntityFrameworkCore; @@ -6,7 +7,7 @@ namespace EFSaving.Transactions; public class ExternalDbTransaction { - public static void Run() + public static async Task Run() { var connectionString = @"Server=(localdb)\mssqllocaldb;Database=EFSaving.Transactions;Trusted_Connection=True;ConnectRetryCount=0"; @@ -16,15 +17,15 @@ public static void Run() .UseSqlServer(connectionString) .Options)) { - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } #region Transaction using var connection = new SqlConnection(connectionString); - connection.Open(); + await connection.OpenAsync(); - using var transaction = connection.BeginTransaction(); + using var transaction = (SqlTransaction)await connection.BeginTransactionAsync(); try { // Run raw ADO.NET command in the transaction @@ -40,14 +41,14 @@ public static void Run() using (var context = new BloggingContext(options)) { - context.Database.UseTransaction(transaction); + await context.Database.UseTransactionAsync(transaction); context.Blogs.Add(new Blog { Url = "http://blogs.msdn.com/dotnet" }); - context.SaveChanges(); + await context.SaveChangesAsync(); } // Commit transaction if all commands succeed, transaction will auto-rollback // when disposed if either commands fails - transaction.Commit(); + await transaction.CommitAsync(); } catch (Exception) { diff --git a/samples/core/Saving/Transactions/ManagingSavepoints.cs b/samples/core/Saving/Transactions/ManagingSavepoints.cs index 20d8e47974..a8cc4a2d57 100644 --- a/samples/core/Saving/Transactions/ManagingSavepoints.cs +++ b/samples/core/Saving/Transactions/ManagingSavepoints.cs @@ -1,39 +1,40 @@ using System; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace EFSaving.Transactions; public class ManagingSavepoints { - public static void Run() + public static async Task Run() { using (var setupContext = new BloggingContext()) { - setupContext.Database.EnsureDeleted(); - setupContext.Database.EnsureCreated(); + await setupContext.Database.EnsureDeletedAsync(); + await setupContext.Database.EnsureCreatedAsync(); } #region Savepoints using var context = new BloggingContext(); - using var transaction = context.Database.BeginTransaction(); + using var transaction = await context.Database.BeginTransactionAsync(); try { context.Blogs.Add(new Blog { Url = "https://devblogs.microsoft.com/dotnet/" }); - context.SaveChanges(); + await context.SaveChangesAsync(); - transaction.CreateSavepoint("BeforeMoreBlogs"); + await transaction.CreateSavepointAsync("BeforeMoreBlogs"); context.Blogs.Add(new Blog { Url = "https://devblogs.microsoft.com/visualstudio/" }); context.Blogs.Add(new Blog { Url = "https://devblogs.microsoft.com/aspnet/" }); - context.SaveChanges(); + await context.SaveChangesAsync(); - transaction.Commit(); + await transaction.CommitAsync(); } catch (Exception) { // If a failure occurred, we rollback to the savepoint and can continue the transaction - transaction.RollbackToSavepoint("BeforeMoreBlogs"); + await transaction.RollbackToSavepointAsync("BeforeMoreBlogs"); // TODO: Handle failure, possibly retry inserting blogs } diff --git a/samples/core/Saving/Transactions/SharingTransaction.cs b/samples/core/Saving/Transactions/SharingTransaction.cs index ae680054e4..719c7a6163 100644 --- a/samples/core/Saving/Transactions/SharingTransaction.cs +++ b/samples/core/Saving/Transactions/SharingTransaction.cs @@ -1,5 +1,6 @@ using System; using System.Linq; +using System.Threading.Tasks; using Microsoft.Data.SqlClient; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Storage; @@ -8,7 +9,7 @@ namespace EFSaving.Transactions; public class SharingTransaction { - public static void Run() + public static async Task Run() { var connectionString = @"Server=(localdb)\mssqllocaldb;Database=EFSaving.Transactions;Trusted_Connection=True;ConnectRetryCount=0"; @@ -18,8 +19,8 @@ public static void Run() .UseSqlServer(connectionString) .Options)) { - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } #region Transaction @@ -29,27 +30,27 @@ public static void Run() .Options; using var context1 = new BloggingContext(options); - using var transaction = context1.Database.BeginTransaction(); + using var transaction = await context1.Database.BeginTransactionAsync(); try { context1.Blogs.Add(new Blog { Url = "http://blogs.msdn.com/dotnet" }); - context1.SaveChanges(); + await context1.SaveChangesAsync(); using (var context2 = new BloggingContext(options)) { - context2.Database.UseTransaction(transaction.GetDbTransaction()); + await context2.Database.UseTransactionAsync(transaction.GetDbTransaction()); - var blogs = context2.Blogs + var blogs = await context2.Blogs .OrderBy(b => b.Url) - .ToList(); + .ToListAsync(); context2.Blogs.Add(new Blog { Url = "http://dot.net" }); - context2.SaveChanges(); + await context2.SaveChangesAsync(); } // Commit transaction if all commands succeed, transaction will auto-rollback // when disposed if either commands fails - transaction.Commit(); + await transaction.CommitAsync(); } catch (Exception) { diff --git a/samples/core/Spatial/SqlServer/Program.cs b/samples/core/Spatial/SqlServer/Program.cs index 9f419d459f..49b1dc03b4 100644 --- a/samples/core/Spatial/SqlServer/Program.cs +++ b/samples/core/Spatial/SqlServer/Program.cs @@ -1,14 +1,15 @@ using System; using System.IO; using System.Linq; +using Microsoft.EntityFrameworkCore; using NetTopologySuite.Geometries; using NetTopologySuite.IO; using SqlServer.Models; using (var context = new WideWorldImportersContext()) { - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); context.AddRange( new City { CityName = "Bellemondville", Location = new Point(-122.128822, 47.643703) { SRID = 4326 } }, @@ -25,32 +26,32 @@ })) { SRID = 4326 } }); - context.SaveChanges(); + await context.SaveChangesAsync(); } var currentLocation = new Point(-122.128822, 47.643703) { SRID = 4326 }; using var db = new WideWorldImportersContext(); #region snippet_Distance // Find the nearest city -var nearestCity = db.Cities +var nearestCity = await db.Cities .OrderBy(c => c.Location.Distance(currentLocation)) - .FirstOrDefault(); + .FirstOrDefaultAsync(); #endregion Console.WriteLine($"Nearest city: {nearestCity.CityName}"); #region snippet_Contains // Find the containing country -var currentCountry = db.Countries - .FirstOrDefault(c => c.Border.Contains(currentLocation)); +var currentCountry = await db.Countries + .FirstOrDefaultAsync(c => c.Border.Contains(currentLocation)); #endregion Console.WriteLine($"Current country: {currentCountry.CountryName}"); // Find which states/provinces a route intersects var route = new GeoJsonReader().Read(File.ReadAllText("seattle-to-new-york.json")); route.SRID = 4326; -var statePorvincesIntersected = (from s in db.StateProvinces +var statePorvincesIntersected = await (from s in db.StateProvinces where s.Border.Intersects(route) orderby s.Border.Distance(currentLocation) - select s).ToList(); + select s).ToListAsync(); Console.WriteLine("States/provinces intersected:"); foreach (var state in statePorvincesIntersected) { diff --git a/samples/core/SqlServer/ValueGeneration/ExplicitIdentityValues.cs b/samples/core/SqlServer/ValueGeneration/ExplicitIdentityValues.cs index 0caac4a6b2..e9a26300ae 100644 --- a/samples/core/SqlServer/ValueGeneration/ExplicitIdentityValues.cs +++ b/samples/core/SqlServer/ValueGeneration/ExplicitIdentityValues.cs @@ -1,3 +1,4 @@ +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace SqlServer.ValueGeneration; @@ -13,12 +14,12 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) public class ExplicitIdentityValues { - public static void Run() + public static async Task Run() { using (var context = new ExplicitIdentityValuesContext()) { - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + await context.Database.EnsureDeletedAsync(); + await context.Database.EnsureCreatedAsync(); } #region ExplicitIdentityValues @@ -27,18 +28,18 @@ public static void Run() context.Blogs.Add(new Blog { BlogId = 100, Url = "http://blog1.somesite.com" }); context.Blogs.Add(new Blog { BlogId = 101, Url = "http://blog2.somesite.com" }); - context.Database.OpenConnection(); + await context.Database.OpenConnectionAsync(); try { - context.Database.ExecuteSqlRaw("SET IDENTITY_INSERT dbo.Blogs ON"); - context.SaveChanges(); - context.Database.ExecuteSqlRaw("SET IDENTITY_INSERT dbo.Blogs OFF"); + await context.Database.ExecuteSqlRawAsync("SET IDENTITY_INSERT dbo.Blogs ON"); + await context.SaveChangesAsync(); + await context.Database.ExecuteSqlRawAsync("SET IDENTITY_INSERT dbo.Blogs OFF"); } finally { - context.Database.CloseConnection(); + await context.Database.CloseConnectionAsync(); } } #endregion } -} \ No newline at end of file +} diff --git a/samples/core/Testing/BloggingWebApi/Controllers/BloggingController.cs b/samples/core/Testing/BloggingWebApi/Controllers/BloggingController.cs index e9c100b64c..a0f07a0321 100644 --- a/samples/core/Testing/BloggingWebApi/Controllers/BloggingController.cs +++ b/samples/core/Testing/BloggingWebApi/Controllers/BloggingController.cs @@ -1,5 +1,7 @@ -using System.Data; +using System.Collections.Generic; +using System.Data; using System.Linq; +using System.Threading.Tasks; using EF.Testing.BusinessLogic; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; @@ -17,23 +19,23 @@ public BloggingController(BloggingContext context) #region GetBlog [HttpGet] - public ActionResult GetBlog(string name) + public async Task> GetBlog(string name) { - var blog = _context.Blogs.FirstOrDefault(b => b.Name == name); + var blog = await _context.Blogs.FirstOrDefaultAsync(b => b.Name == name); return blog is null ? NotFound() : blog; } #endregion [HttpGet] - public ActionResult GetAllBlogs() - => _context.Blogs.OrderBy(b => b.Name).ToArray(); + public IAsyncEnumerable GetAllBlogs() + => _context.Blogs.OrderBy(b => b.Name).AsAsyncEnumerable(); #region AddBlog [HttpPost] - public ActionResult AddBlog(string name, string url) + public async Task AddBlog(string name, string url) { _context.Blogs.Add(new Blog { Name = name, Url = url }); - _context.SaveChanges(); + await _context.SaveChangesAsync(); return Ok(); } @@ -41,22 +43,22 @@ public ActionResult AddBlog(string name, string url) #region UpdateBlogUrl [HttpPost] - public ActionResult UpdateBlogUrl(string name, string url) + public async Task UpdateBlogUrl(string name, string url) { // Note: it isn't usually necessary to start a transaction for updating. This is done here for illustration purposes only. - using var transaction = _context.Database.BeginTransaction(IsolationLevel.Serializable); + using var transaction = await _context.Database.BeginTransactionAsync(IsolationLevel.Serializable); - var blog = _context.Blogs.FirstOrDefault(b => b.Name == name); + var blog = await _context.Blogs.FirstOrDefaultAsync(b => b.Name == name); if (blog is null) { return NotFound(); } blog.Url = url; - _context.SaveChanges(); + await _context.SaveChangesAsync(); - transaction.Commit(); + await transaction.CommitAsync(); return Ok(); } #endregion -} \ No newline at end of file +} diff --git a/samples/core/Testing/BloggingWebApi/Controllers/BloggingControllerWithRepository.cs b/samples/core/Testing/BloggingWebApi/Controllers/BloggingControllerWithRepository.cs index d5f2077445..f5d61ca109 100644 --- a/samples/core/Testing/BloggingWebApi/Controllers/BloggingControllerWithRepository.cs +++ b/samples/core/Testing/BloggingWebApi/Controllers/BloggingControllerWithRepository.cs @@ -1,6 +1,8 @@ using System; +using System.Collections.Generic; using System.Data; using System.Linq; +using System.Threading.Tasks; using EF.Testing.BusinessLogic; using Microsoft.AspNetCore.Mvc; @@ -17,35 +19,33 @@ public BloggingControllerWithRepository(IBloggingRepository repository) => _repository = repository; [HttpGet] - public Blog GetBlog(string name) - => _repository.GetBlogByName(name); + public async Task GetBlog(string name) + => await _repository.GetBlogByNameAsync(name); #endregion [HttpGet] - public ActionResult GetAllBlogs() - => _repository.GetAllBlogs().ToArray(); + public IAsyncEnumerable GetAllBlogs() + => _repository.GetAllBlogsAsync(); [HttpPost] - public ActionResult AddBlog(string name, string url) + public async Task AddBlog(string name, string url) { _repository.AddBlog(new Blog { Name = name, Url = url }); - _repository.SaveChanges(); - - return Ok(); + await _repository.SaveChangesAsync(); } [HttpPost] - public ActionResult UpdateBlogUrl(string name, string url) + public async Task UpdateBlogUrl(string name, string url) { - var blog = _repository.GetBlogByName(name); + var blog = await _repository.GetBlogByNameAsync(name); if (blog is null) { return NotFound(); } blog.Url = url; - _repository.SaveChanges(); + await _repository.SaveChangesAsync(); return Ok(); } -} \ No newline at end of file +} diff --git a/samples/core/Testing/BusinessLogic/BloggingRepository.cs b/samples/core/Testing/BusinessLogic/BloggingRepository.cs index 8c445fcf8a..9fdf05d074 100644 --- a/samples/core/Testing/BusinessLogic/BloggingRepository.cs +++ b/samples/core/Testing/BusinessLogic/BloggingRepository.cs @@ -1,5 +1,7 @@ using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; namespace EF.Testing.BusinessLogic; @@ -11,16 +13,16 @@ public class BloggingRepository : IBloggingRepository public BloggingRepository(BloggingContext context) => _context = context; - public Blog GetBlogByName(string name) - => _context.Blogs.FirstOrDefault(b => b.Name == name); + public async Task GetBlogByNameAsync(string name) + => await _context.Blogs.FirstOrDefaultAsync(b => b.Name == name); #endregion - public IEnumerable GetAllBlogs() - => _context.Blogs; + public IAsyncEnumerable GetAllBlogsAsync() + => _context.Blogs.AsAsyncEnumerable(); public void AddBlog(Blog blog) => _context.Add(blog); - public void SaveChanges() - => _context.SaveChanges(); -} \ No newline at end of file + public async Task SaveChangesAsync() + => await _context.SaveChangesAsync(); +} diff --git a/samples/core/Testing/BusinessLogic/IBloggingRepository.cs b/samples/core/Testing/BusinessLogic/IBloggingRepository.cs index 3be7df33ac..d96a45a788 100644 --- a/samples/core/Testing/BusinessLogic/IBloggingRepository.cs +++ b/samples/core/Testing/BusinessLogic/IBloggingRepository.cs @@ -1,16 +1,17 @@ using System.Collections.Generic; +using System.Threading.Tasks; namespace EF.Testing.BusinessLogic; #region IBloggingRepository public interface IBloggingRepository { - Blog GetBlogByName(string name); + Task GetBlogByNameAsync(string name); - IEnumerable GetAllBlogs(); + IAsyncEnumerable GetAllBlogsAsync(); void AddBlog(Blog blog); - void SaveChanges(); + Task SaveChangesAsync(); } -#endregion \ No newline at end of file +#endregion diff --git a/samples/core/Testing/TestingWithTheDatabase/BloggingControllerTest.cs b/samples/core/Testing/TestingWithTheDatabase/BloggingControllerTest.cs index abb2dc0695..82670b92cb 100644 --- a/samples/core/Testing/TestingWithTheDatabase/BloggingControllerTest.cs +++ b/samples/core/Testing/TestingWithTheDatabase/BloggingControllerTest.cs @@ -1,5 +1,7 @@ using System.Linq; +using System.Threading.Tasks; using EF.Testing.BloggingWebApi.Controllers; +using Microsoft.EntityFrameworkCore; using Xunit; namespace EF.Testing.IntegrationTests; @@ -15,12 +17,12 @@ public BloggingControllerTest(TestDatabaseFixture fixture) #region GetBlog [Fact] - public void GetBlog() + public async Task GetBlog() { using var context = Fixture.CreateContext(); var controller = new BloggingController(context); - var blog = controller.GetBlog("Blog2").Value; + var blog = (await controller.GetBlog("Blog2")).Value; Assert.Equal("http://blog2.com", blog.Url); } @@ -28,12 +30,12 @@ public void GetBlog() #region GetAllBlogs [Fact] - public void GetAllBlogs() + public async Task GetAllBlogs() { using var context = Fixture.CreateContext(); var controller = new BloggingController(context); - var blogs = controller.GetAllBlogs().Value; + var blogs = await controller.GetAllBlogs().ToListAsync(); Assert.Collection( blogs, @@ -44,19 +46,19 @@ public void GetAllBlogs() #region AddBlog [Fact] - public void AddBlog() + public async Task AddBlog() { using var context = Fixture.CreateContext(); context.Database.BeginTransaction(); var controller = new BloggingController(context); - controller.AddBlog("Blog3", "http://blog3.com"); + await controller.AddBlog("Blog3", "http://blog3.com"); context.ChangeTracker.Clear(); - var blog = context.Blogs.Single(b => b.Name == "Blog3"); + var blog = await context.Blogs.SingleAsync(b => b.Name == "Blog3"); Assert.Equal("http://blog3.com", blog.Url); } #endregion -} \ No newline at end of file +} diff --git a/samples/core/Testing/TestingWithTheDatabase/TestingWithTheDatabase.csproj b/samples/core/Testing/TestingWithTheDatabase/TestingWithTheDatabase.csproj index 7a17738a81..7a71dc5369 100644 --- a/samples/core/Testing/TestingWithTheDatabase/TestingWithTheDatabase.csproj +++ b/samples/core/Testing/TestingWithTheDatabase/TestingWithTheDatabase.csproj @@ -14,6 +14,7 @@ runtime; build; native; contentfiles; analyzers; buildtransitive all + diff --git a/samples/core/Testing/TestingWithTheDatabase/TransactionalBloggingControllerTest.cs b/samples/core/Testing/TestingWithTheDatabase/TransactionalBloggingControllerTest.cs index c6c63e92e3..b9b220446f 100644 --- a/samples/core/Testing/TestingWithTheDatabase/TransactionalBloggingControllerTest.cs +++ b/samples/core/Testing/TestingWithTheDatabase/TransactionalBloggingControllerTest.cs @@ -1,6 +1,8 @@ using System; using System.Linq; +using System.Threading.Tasks; using EF.Testing.BloggingWebApi.Controllers; +using Microsoft.EntityFrameworkCore; using Xunit; namespace EF.Testing.IntegrationTests; @@ -17,17 +19,17 @@ public TransactionalBloggingControllerTest(TransactionalTestDatabaseFixture fixt #region UpdateBlogUrl [Fact] - public void UpdateBlogUrl() + public async Task UpdateBlogUrl() { using (var context = Fixture.CreateContext()) { var controller = new BloggingController(context); - controller.UpdateBlogUrl("Blog2", "http://blog2_updated.com"); + await controller.UpdateBlogUrl("Blog2", "http://blog2_updated.com"); } using (var context = Fixture.CreateContext()) { - var blog = context.Blogs.Single(b => b.Name == "Blog2"); + var blog = await context.Blogs.SingleAsync(b => b.Name == "Blog2"); Assert.Equal("http://blog2_updated.com", blog.Url); } } @@ -37,4 +39,4 @@ public void UpdateBlogUrl() public void Dispose() => Fixture.Cleanup(); #endregion -} \ No newline at end of file +} diff --git a/samples/core/Testing/TestingWithoutTheDatabase/InMemoryBloggingControllerTest.cs b/samples/core/Testing/TestingWithoutTheDatabase/InMemoryBloggingControllerTest.cs index ba75766531..2c3744d999 100644 --- a/samples/core/Testing/TestingWithoutTheDatabase/InMemoryBloggingControllerTest.cs +++ b/samples/core/Testing/TestingWithoutTheDatabase/InMemoryBloggingControllerTest.cs @@ -1,4 +1,5 @@ using System.Linq; +using System.Threading.Tasks; using EF.Testing.BloggingWebApi.Controllers; using EF.Testing.BusinessLogic; using Microsoft.EntityFrameworkCore; @@ -34,24 +35,24 @@ public InMemoryBloggingControllerTest() #region GetBlog [Fact] - public void GetBlog() + public async Task GetBlog() { using var context = CreateContext(); var controller = new BloggingController(context); - var blog = controller.GetBlog("Blog2").Value; + var blog = (await controller.GetBlog("Blog2")).Value; Assert.Equal("http://blog2.com", blog.Url); } #endregion [Fact] - public void GetAllBlogs() + public async Task GetAllBlogs() { using var context = CreateContext(); var controller = new BloggingController(context); - var blogs = controller.GetAllBlogs().Value; + var blogs = await controller.GetAllBlogs().ToListAsync(); Assert.Collection( blogs, @@ -60,26 +61,26 @@ public void GetAllBlogs() } [Fact] - public void AddBlog() + public async Task AddBlog() { using var context = CreateContext(); var controller = new BloggingController(context); - controller.AddBlog("Blog3", "http://blog3.com"); + await controller.AddBlog("Blog3", "http://blog3.com"); - var blog = context.Blogs.Single(b => b.Name == "Blog3"); + var blog = await context.Blogs.SingleAsync(b => b.Name == "Blog3"); Assert.Equal("http://blog3.com", blog.Url); } [Fact] - public void UpdateBlogUrl() + public async Task UpdateBlogUrl() { using var context = CreateContext(); var controller = new BloggingController(context); - controller.UpdateBlogUrl("Blog2", "http://blog2_updated.com"); + await controller.UpdateBlogUrl("Blog2", "http://blog2_updated.com"); - var blog = context.Blogs.Single(b => b.Name == "Blog2"); + var blog = await context.Blogs.SingleAsync(b => b.Name == "Blog2"); Assert.Equal("http://blog2_updated.com", blog.Url); } @@ -90,4 +91,4 @@ public void UpdateBlogUrl() .ToInMemoryQuery(() => context.Blogs.Select(b => new UrlResource { Url = b.Url })); #endregion }); -} \ No newline at end of file +} diff --git a/samples/core/Testing/TestingWithoutTheDatabase/RepositoryBloggingControllerTest.cs b/samples/core/Testing/TestingWithoutTheDatabase/RepositoryBloggingControllerTest.cs index 29b3db5c79..5913a88539 100644 --- a/samples/core/Testing/TestingWithoutTheDatabase/RepositoryBloggingControllerTest.cs +++ b/samples/core/Testing/TestingWithoutTheDatabase/RepositoryBloggingControllerTest.cs @@ -1,3 +1,5 @@ +using System.Linq; +using System.Threading.Tasks; using EF.Testing.BloggingWebApi.Controllers; using EF.Testing.BusinessLogic; using Moq; @@ -9,83 +11,83 @@ public class RepositoryBloggingControllerTest { #region GetBlog [Fact] - public void GetBlog() + public async Task GetBlog() { // Arrange var repositoryMock = new Mock(); repositoryMock - .Setup(r => r.GetBlogByName("Blog2")) - .Returns(new Blog { Name = "Blog2", Url = "http://blog2.com" }); + .Setup(r => r.GetBlogByNameAsync("Blog2")) + .Returns(Task.FromResult(new Blog { Name = "Blog2", Url = "http://blog2.com" })); var controller = new BloggingControllerWithRepository(repositoryMock.Object); // Act - var blog = controller.GetBlog("Blog2"); + var blog = await controller.GetBlog("Blog2"); // Assert - repositoryMock.Verify(r => r.GetBlogByName("Blog2")); + repositoryMock.Verify(r => r.GetBlogByNameAsync("Blog2")); Assert.Equal("http://blog2.com", blog.Url); } #endregion [Fact] - public void GetAllBlogs() + public async Task GetAllBlogs() { // Arrange var repositoryMock = new Mock(); repositoryMock - .Setup(r => r.GetAllBlogs()) + .Setup(r => r.GetAllBlogsAsync()) .Returns(new[] { new Blog { Name = "Blog1", Url = "http://blog1.com" }, new Blog { Name = "Blog2", Url = "http://blog2.com" } - }); + }.ToAsyncEnumerable()); var controller = new BloggingControllerWithRepository(repositoryMock.Object); // Act - var blogs = controller.GetAllBlogs().Value; + var blogs = await controller.GetAllBlogs().ToListAsync(); // Assert - repositoryMock.Verify(r => r.GetAllBlogs()); + repositoryMock.Verify(r => r.GetAllBlogsAsync()); Assert.Equal("http://blog1.com", blogs[0].Url); Assert.Equal("http://blog2.com", blogs[1].Url); } [Fact] - public void AddBlog() + public async Task AddBlog() { // Arrange var repositoryMock = new Mock(); var controller = new BloggingControllerWithRepository(repositoryMock.Object); // Act - controller.AddBlog("Blog2", "http://blog2.com"); + await controller.AddBlog("Blog2", "http://blog2.com"); // Assert repositoryMock.Verify(r => r.AddBlog(It.IsAny())); - repositoryMock.Verify(r => r.SaveChanges()); + repositoryMock.Verify(r => r.SaveChangesAsync()); } [Fact] - public void UpdateBlogUrl() + public async Task UpdateBlogUrl() { var blog = new Blog { Name = "Blog2", Url = "http://blog2.com" }; // Arrange var repositoryMock = new Mock(); repositoryMock - .Setup(r => r.GetBlogByName("Blog2")) - .Returns(blog); + .Setup(r => r.GetBlogByNameAsync("Blog2")) + .Returns(Task.FromResult(blog)); var controller = new BloggingControllerWithRepository(repositoryMock.Object); // Act - controller.UpdateBlogUrl("Blog2", "http://blog2_updated.com"); + await controller.UpdateBlogUrl("Blog2", "http://blog2_updated.com"); // Assert - repositoryMock.Verify(r => r.GetBlogByName("Blog2")); - repositoryMock.Verify(r => r.SaveChanges()); + repositoryMock.Verify(r => r.GetBlogByNameAsync("Blog2")); + repositoryMock.Verify(r => r.SaveChangesAsync()); Assert.Equal("http://blog2_updated.com", blog.Url); } -} \ No newline at end of file +} diff --git a/samples/core/Testing/TestingWithoutTheDatabase/SqliteInMemoryBloggingControllerTest.cs b/samples/core/Testing/TestingWithoutTheDatabase/SqliteInMemoryBloggingControllerTest.cs index 9c2990e434..09806d0017 100644 --- a/samples/core/Testing/TestingWithoutTheDatabase/SqliteInMemoryBloggingControllerTest.cs +++ b/samples/core/Testing/TestingWithoutTheDatabase/SqliteInMemoryBloggingControllerTest.cs @@ -1,6 +1,7 @@ using System; using System.Data.Common; using System.Linq; +using System.Threading.Tasks; using EF.Testing.BloggingWebApi.Controllers; using EF.Testing.BusinessLogic; using Microsoft.Data.Sqlite; @@ -53,24 +54,24 @@ SELECT Url #region GetBlog [Fact] - public void GetBlog() + public async Task GetBlog() { using var context = CreateContext(); var controller = new BloggingController(context); - var blog = controller.GetBlog("Blog2").Value; + var blog = (await controller.GetBlog("Blog2")).Value; Assert.Equal("http://blog2.com", blog.Url); } #endregion [Fact] - public void GetAllBlogs() + public async Task GetAllBlogs() { using var context = CreateContext(); var controller = new BloggingController(context); - var blogs = controller.GetAllBlogs().Value; + var blogs = await controller.GetAllBlogs().ToListAsync(); Assert.Collection( blogs, @@ -79,26 +80,26 @@ public void GetAllBlogs() } [Fact] - public void AddBlog() + public async Task AddBlog() { using var context = CreateContext(); var controller = new BloggingController(context); - controller.AddBlog("Blog3", "http://blog3.com"); + await controller.AddBlog("Blog3", "http://blog3.com"); - var blog = context.Blogs.Single(b => b.Name == "Blog3"); + var blog = await context.Blogs.SingleAsync(b => b.Name == "Blog3"); Assert.Equal("http://blog3.com", blog.Url); } [Fact] - public void UpdateBlogUrl() + public async Task UpdateBlogUrl() { using var context = CreateContext(); var controller = new BloggingController(context); - controller.UpdateBlogUrl("Blog2", "http://blog2_updated.com"); + await controller.UpdateBlogUrl("Blog2", "http://blog2_updated.com"); - var blog = context.Blogs.Single(b => b.Name == "Blog2"); + var blog = await context.Blogs.SingleAsync(b => b.Name == "Blog2"); Assert.Equal("http://blog2_updated.com", blog.Url); } -} \ No newline at end of file +} diff --git a/samples/core/Testing/TestingWithoutTheDatabase/TestingWithoutTheDatabase.csproj b/samples/core/Testing/TestingWithoutTheDatabase/TestingWithoutTheDatabase.csproj index 88cfd81fe5..e7a5c084df 100644 --- a/samples/core/Testing/TestingWithoutTheDatabase/TestingWithoutTheDatabase.csproj +++ b/samples/core/Testing/TestingWithoutTheDatabase/TestingWithoutTheDatabase.csproj @@ -18,6 +18,7 @@ runtime; build; native; contentfiles; analyzers; buildtransitive all +