You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardexpand all lines: docs/database/use-entity-framework-db-contexts.md
+15-15
Original file line number
Diff line number
Diff line change
@@ -23,15 +23,15 @@ The most commonly used .NET Aspire EF client integrations are:
23
23
> [!NOTE]
24
24
> In .NET Aspire, EF is implemented by client integrations, not hosting integrations. So, for example, to use EF with a SQL Server database, you'd use the SQL Server hosting integration to create the SQL Server container and add a database to it. In the consuming microservices, when you want to use EF, choose the SQL Server Entity Framework Core integration instead of the SQL Server client integration.
25
25
26
-
## Use .NET Aspire to create a database context
26
+
## Use .NET Aspire to create an EF context
27
27
28
28
In EF, a [**context**](/ef/core/dbcontext-configuration/) is a class used to interact with the database. Contexts inherit from the <xref:Microsoft.EntityFrameworkCore.DbContext> class. They provide access to the database through properties of type `DbSet<T>`, where each `DbSet` represents a table or collection of entities in the database. The context also manages database connections, tracks changes to entities, and handles operations like saving data and executing queries.
29
29
30
30
The .NET Aspire EF client integrations each include an extension method named `Add\<DatabaseSystem\>DbContext`, where **\<DatabaseSystem\>** is a string identifying the database product you are using. For example, for the SQL Server EF client integration, the method is named <xref:Microsoft.Extensions.Hosting.AspireSqlServerEFCoreSqlClientExtensions.AddSqlServerDbContext%2A> and for the PostgreSQL client integration, the method is named <xref:Microsoft.Extensions.Hosting.AspireEFPostgreSqlExtensions.AddNpgsqlDbContext%2A>.
31
31
32
32
These .NET Aspire add context methods:
33
33
34
-
- Check that a database context of the same type is not already registered in the Dependency Injection (DI) container.
34
+
- Check that a context of the same type is not already registered in the Dependency Injection (DI) container.
35
35
- Use the connection name you pass to the method to get the connection string from the application builder. This connection name must match the name used when adding the corresponding resource to the app host project.
36
36
- Apply the `DbContext` options, if you passed them.
37
37
- Add the specified `DbContext` to the DI container with context pooling enabled.
@@ -40,7 +40,7 @@ These .NET Aspire add context methods:
40
40
- Enable health checks.
41
41
- Enable connection resiliency.
42
42
43
-
Use these .NET Aspire add context methods when you want a simple way to create the database context and don't yet need advanced EF customization.
43
+
Use these .NET Aspire add context methods when you want a simple way to create a context and don't yet need advanced EF customization.
You have more flexibility when you create the database context in this way, for example:
136
+
You have more flexibility when you create the context in this way, for example:
137
137
138
138
- You can reuse existing configuration code for the context without rewriting it for .NET Aspire.
139
139
- You can choose not to use EF Core context pooling, which may be necessary in some circumstances. For more information, see [Use EF context pooling in .NET Aspire](#use-ef-context-pooling-in-net-aspire)
@@ -300,7 +300,7 @@ Most microservices always connect to the same database with the same credentials
300
300
- You might offer your service to multiple tenants and need to use a different database depending on which customer made the request.
301
301
- You might need to authenticate the request with a different database user account depending on which customer made the request.
302
302
303
-
For these requirements, you can use code to formulate a **dynamic connection string** and then use it to reach the database and run queries. However, this technique isn't supported by the .NET Aspire `Add\<DatabaseSystem\>DbContext` methods. Instead you must use the EF method to create the database context and then enrich it:
303
+
For these requirements, you can use code to formulate a **dynamic connection string** and then use it to reach the database and run queries. However, this technique isn't supported by the .NET Aspire `Add\<DatabaseSystem\>DbContext` methods. Instead you must use the EF method to create the context and then enrich it:
The above code replaces the place holder `{DatabaseName}` in the connection string with the string `ContosoDatabase`, at run time, before it creates the database context and enriches it.
390
+
The above code replaces the place holder `{DatabaseName}` in the connection string with the string `ContosoDatabase`, at run time, before it creates the context and enriches it.
391
391
392
392
### Use EF Core context factories in .NET Aspire
393
393
394
394
An EF context is an object designed to be used for a single unit of work. For example, if you want to add a new customer to the database, you might need to add a row in the **Customers** table and a row in the **Addresses** table. You should get the EF context, add the new customer and address entities to it, call <xref:Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync*>, and then dispose the context.
395
395
396
-
In many types of web application, such as ASP.NET applications, each HTTP request closely corresponds to a single unit of work against the database. If your .NET Aspire microservice is an ASP.NET application or a similar web application, you can use the standard EF <xref:Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.AddDbContextPool*> method described above to register a context that is tied to the current HTTP request. Remember to call the .NET Aspire `Enrich\<DatabaseSystem\>DbContext` method to gain health checks, tracing, and other features. When you use this approach, the database context lifetime is tied to the web request. You don't have to call the <xref:Microsoft.EntityFrameworkCore.DbContext.Dispose*> method when the unit of work is complete.
396
+
In many types of web application, such as ASP.NET applications, each HTTP request closely corresponds to a single unit of work against the database. If your .NET Aspire microservice is an ASP.NET application or a similar web application, you can use the standard EF <xref:Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.AddDbContextPool*> method described above to register a context that is tied to the current HTTP request. Remember to call the .NET Aspire `Enrich\<DatabaseSystem\>DbContext` method to gain health checks, tracing, and other features. When you use this approach, the context lifetime is tied to the web request. You don't have to call the <xref:Microsoft.EntityFrameworkCore.DbContext.Dispose*> method when the unit of work is complete.
397
397
398
-
Other application types, such as ASP.NET Core Blazor, don't necessarily align each request with a unit of work, because they use dependency injection with a different service scope. In such apps, you may need to perform multiple units of work, each with a different database context, within a single HTTP request and response. To implement this approach, you can register a context factory, by calling the EF <xref:Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.AddPooledDbContextFactory*> method. This method also partners well with the .NET Aspire `Enrich\<DatabaseSystem\>DbContext` methods:
398
+
Other application types, such as ASP.NET Core Blazor, don't necessarily align each request with a unit of work, because they use dependency injection with a different service scope. In such apps, you may need to perform multiple units of work, each with a different context, within a single HTTP request and response. To implement this approach, you can register a context factory, by calling the EF <xref:Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.AddPooledDbContextFactory*> method. This method also partners well with the .NET Aspire `Enrich\<DatabaseSystem\>DbContext` methods:
??thrownewInvalidOperationException("Connection string 'database' not found.")));
454
454
455
455
builder.EnrichMySqlDbContext<ExampleDbContext>(
@@ -478,13 +478,13 @@ Contexts created from factories in this way aren't disposed of automatically bec
478
478
479
479
## Use EF context pooling in .NET Aspire
480
480
481
-
In EF Core a database context is relatively quick to create and dispose of so most applications can set them up as needed without impacting their performance. However, the overhead is not zero so, if your microservice intensively creates contexts, you may observe suboptimal performance. In such situations, consider using a database context pool.
481
+
In EF Core a context is relatively quick to create and dispose of so most applications can set them up as needed without impacting their performance. However, the overhead is not zero so, if your microservice intensively creates contexts, you may observe suboptimal performance. In such situations, consider using a context pool.
482
482
483
483
Context pooling is a feature of EF Core. Contexts are created as normal but, when you dispose of one, it isn't destroyed but reset and stored in a pool. The next time your code creates a context, the stored one is returned to avoid the extra overhead of creating a new one.
484
484
485
485
In a .NET Aspire consuming project, there are three ways to use context pooling:
486
486
487
-
- Use the .NET Aspire `Add\<DatabaseSystem\>DbContext` methods to create the database context. These methods create a context pool automatically.
487
+
- Use the .NET Aspire `Add\<DatabaseSystem\>DbContext` methods to create the context. These methods create a context pool automatically.
488
488
- Call the EF <xref:Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.AddDbContextPool*> method instead of the EF <xref:Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.AddDbContext*> method.
489
489
490
490
:::zone pivot="sql-server-ef"
@@ -563,7 +563,7 @@ In a .NET Aspire consuming project, there are three ways to use context pooling:
0 commit comments