Skip to content

Commit 86cbdf9

Browse files
authored
Async conversion for change tracking code samples (#4922)
1 parent cd755ac commit 86cbdf9

File tree

188 files changed

+2422
-2267
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

188 files changed

+2422
-2267
lines changed

entity-framework/core/managing-schemas/ensure-created.md

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,39 +8,39 @@ uid: core/managing-schemas/ensure-created
88
---
99
# Create and Drop APIs
1010

11-
The <xref:Microsoft.EntityFrameworkCore.Storage.IDatabaseCreator.EnsureCreated> and <xref:Microsoft.EntityFrameworkCore.Storage.IDatabaseCreator.EnsureDeleted> 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.
11+
The <xref:Microsoft.EntityFrameworkCore.Storage.IDatabaseCreator.EnsureCreatedAsync*> and <xref:Microsoft.EntityFrameworkCore.Storage.IDatabaseCreator.EnsureDeletedAsync*> 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.
1212

13-
Some providers (especially non-relational ones) don't support Migrations. For these providers, `EnsureCreated` is often the easiest way to initialize the database schema.
13+
Some providers (especially non-relational ones) don't support Migrations. For these providers, `EnsureCreatedAsync` is often the easiest way to initialize the database schema.
1414

1515
> [!WARNING]
16-
> `EnsureCreated` and Migrations don't work well together. If you're using Migrations, don't use `EnsureCreated` to initialize the schema.
16+
> `EnsureCreatedAsync` and Migrations don't work well together. If you're using Migrations, don't use `EnsureCreatedAsync` to initialize the schema.
1717
18-
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`.
18+
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`.
1919

20-
## EnsureDeleted
20+
## EnsureDeletedAsync
2121

22-
The `EnsureDeleted` method will drop the database if it exists. If you don't have the appropriate permissions, an exception is thrown.
22+
The `EnsureDeletedAsync` method will drop the database if it exists. If you don't have the appropriate permissions, an exception is thrown.
2323

2424
```csharp
2525
// Drop the database if it exists
26-
dbContext.Database.EnsureDeleted();
26+
await dbContext.Database.EnsureDeletedAsync();
2727
```
2828

29-
## EnsureCreated
29+
## EnsureCreatedAsync
3030

31-
`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.
31+
`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.
3232

3333
```csharp
3434
// Create the database if it doesn't exist
35-
dbContext.Database.EnsureCreated();
35+
dbContext.Database.EnsureCreatedAsync();
3636
```
3737

3838
> [!TIP]
3939
> Async versions of these methods are also available.
4040
4141
## SQL Script
4242

43-
To get the SQL used by `EnsureCreated`, you can use the <xref:Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.GenerateCreateScript*> method.
43+
To get the SQL used by `EnsureCreatedAsync`, you can use the <xref:Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.GenerateCreateScript*> method.
4444

4545
```csharp
4646
var sql = dbContext.Database.GenerateCreateScript();

entity-framework/core/managing-schemas/migrations/applying.md

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -317,26 +317,26 @@ It's possible for the application itself to apply migrations programmatically, t
317317
* 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.
318318
* 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.
319319

320-
To apply migrations programmatically, call `context.Database.Migrate()`. For example, a typical ASP.NET application can do the following:
320+
To apply migrations programmatically, call `context.Database.MigrateAsync()`. For example, a typical ASP.NET application can do the following:
321321

322322
```csharp
323-
public static void Main(string[] args)
323+
public static async Task Main(string[] args)
324324
{
325325
var host = CreateHostBuilder(args).Build();
326326

327327
using (var scope = host.Services.CreateScope())
328328
{
329329
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
330-
db.Database.Migrate();
330+
await db.Database.MigrateAsync();
331331
}
332332

333333
host.Run();
334334
}
335335
```
336336

337-
Note that `Migrate()` builds on top of the `IMigrator` service, which can be used for more advanced scenarios. Use `myDbContext.GetInfrastructure().GetService<IMigrator>()` to access it.
337+
Note that `MigrateAsync()` builds on top of the `IMigrator` service, which can be used for more advanced scenarios. Use `myDbContext.GetInfrastructure().GetService<IMigrator>()` to access it.
338338

339339
> [!WARNING]
340340
>
341341
> * 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.
342-
> * Don't call `EnsureCreated()` before `Migrate()`. `EnsureCreated()` bypasses Migrations to create the schema, which causes `Migrate()` to fail.
342+
> * Don't call `EnsureCreatedAsync()` before `MigrateAsync()`. `EnsureCreatedAsync()` bypasses Migrations to create the schema, which causes `MigrateAsync()` to fail.

entity-framework/core/miscellaneous/connection-resiliency.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,9 +47,9 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
4747

4848
## Execution strategies and transactions
4949

50-
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.
50+
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.
5151

52-
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:
52+
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:
5353

5454
> 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.
5555

entity-framework/core/miscellaneous/nullable-reference-types.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -95,9 +95,9 @@ Another strategy is to use non-nullable auto-properties, but to initialize them
9595
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:
9696

9797
```csharp
98-
var order = context.Orders
98+
var order = await context.Orders
9999
.Where(o => o.OptionalInfo!.SomeProperty == "foo")
100-
.ToList();
100+
.ToListAsync();
101101
```
102102

103103
A similar issue occurs when including multiple levels of relationships across optional navigations:

entity-framework/core/modeling/data-seeding.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ These methods can be set up in the [options configuration step](/ef/core/dbconte
3939

4040
## Custom initialization logic
4141

42-
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:
42+
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:
4343

4444
[!code-csharp[Main](../../../samples/core/Modeling/DataSeeding/Program.cs?name=CustomSeeding)]
4545

@@ -85,7 +85,7 @@ Once the data has been added to the model, [migrations](xref:core/managing-schem
8585
> [!TIP]
8686
> 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.
8787
88-
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.
88+
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.
8989

9090
> [!NOTE]
9191
> 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.

entity-framework/core/performance/efficient-updating.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ foreach (var employee in context.Employees)
3030
{
3131
employee.Salary += 1000;
3232
}
33-
context.SaveChanges();
33+
await context.SaveChangesAsync();
3434
```
3535

3636
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
3939
* 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.
4040
* 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.
4141

42-
Starting with EF Core 7.0, you can use the `ExecuteUpdate` and `ExecuteDelete` methods to do the same thing far more efficiently:
42+
Starting with EF Core 7.0, you can use the `ExecuteUpdateAsync` and `ExecuteDeleteAsync` methods to do the same thing far more efficiently:
4343

4444
```c#
45-
context.Employees.ExecuteUpdate(s => s.SetProperty(e => e.Salary, e => e.Salary + 1000));
45+
await context.Employees.ExecuteUpdateAsync(s => s.SetProperty(e => e.Salary, e => e.Salary + 1000));
4646
```
4747

4848
This sends the following SQL statement to the database:

entity-framework/core/providers/cosmos/querying.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -123,11 +123,11 @@ A common way to implement pagination with databases is to use the `Skip` and `Ta
123123

124124
```csharp
125125
var position = 20;
126-
var nextPage = context.Session
126+
var nextPage = await context.Session
127127
.OrderBy(s => s.Id)
128128
.Skip(position)
129129
.Take(10)
130-
.ToList();
130+
.ToListAsync();
131131
```
132132

133133
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_:

entity-framework/core/providers/sql-server/value-generation.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ By default, IDENTITY columns start off at 1 (the seed), and increment by 1 each
2121

2222
### Inserting explicit values into IDENTITY columns
2323

24-
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:
24+
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:
2525

2626
[!code-csharp[Main](../../../../samples/core/SqlServer/ValueGeneration/ExplicitIdentityValues.cs?name=ExplicitIdentityValues)]
2727

entity-framework/core/querying/related-data/eager.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,10 +70,10 @@ Alternatively, identical operations can be applied for each navigation that is i
7070
Example:
7171

7272
```csharp
73-
var orders = context.Orders.Where(o => o.Id > 1000).ToList();
73+
var orders = await context.Orders.Where(o => o.Id > 1000).ToListAsync();
7474

7575
// customer entities will have references to all orders where Id > 1000, rather than > 5000
76-
var filtered = context.Customers.Include(c => c.Orders.Where(o => o.Id > 5000)).ToList();
76+
var filtered = await context.Customers.Include(c => c.Orders.Where(o => o.Id > 5000)).ToListAsync();
7777
```
7878

7979
> [!NOTE]

entity-framework/core/querying/single-split-queries.md

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,10 @@ When working against relational databases, EF loads related entities by introduc
1616
Let's examine the following LINQ query and its translated SQL equivalent:
1717

1818
```c#
19-
var blogs = ctx.Blogs
19+
var blogs = await ctx.Blogs
2020
.Include(b => b.Posts)
2121
.Include(b => b.Contributors)
22-
.ToList();
22+
.ToListAsync();
2323
```
2424

2525
```sql
@@ -35,10 +35,10 @@ In this example, since both `Posts` and `Contributors` are collection navigation
3535
Note that cartesian explosion does not occur when the two JOINs aren't at the same level:
3636

3737
```c#
38-
var blogs = ctx.Blogs
38+
var blogs = await ctx.Blogs
3939
.Include(b => b.Posts)
4040
.ThenInclude(p => p.Comments)
41-
.ToList();
41+
.ToListAsync();
4242
```
4343

4444
```sql
@@ -56,9 +56,9 @@ In this query, `Comments` is a collection navigation of `Post`, unlike `Contribu
5656
JOINs can create another type of performance issue. Let's examine the following query, which only loads a single collection navigation:
5757

5858
```c#
59-
var blogs = ctx.Blogs
59+
var blogs = await ctx.Blogs
6060
.Include(b => b.Posts)
61-
.ToList();
61+
.ToListAsync();
6262
```
6363

6464
```sql
@@ -73,14 +73,14 @@ Examining at the projected columns, each row returned by this query contains pro
7373
If you don't actually need the huge column, it's easy to simply not query for it:
7474

7575
```c#
76-
var blogs = ctx.Blogs
76+
var blogs = await ctx.Blogs
7777
.Select(b => new
7878
{
7979
b.Id,
8080
b.Name,
8181
b.Posts
8282
})
83-
.ToList();
83+
.ToListAsync();
8484
```
8585

8686
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.

0 commit comments

Comments
 (0)