Azure SQL Entity Framework Core integration
Esta página aún no está disponible en tu idioma.
Azure SQL is a family of relational database management systems that run in the Azure cloud. The database systems are Platform-as-a-Service (PaaS) products that enable database administrators to implement highly scalable and available databases without maintaining complex infrastructures themselves. The Aspire Azure SQL Server Hosting integration provides methods to create a new Azure Database server and databases from code in your Aspire AppHost project. In a consuming project, you can use the Aspire SQL Server client integration as you would for any other SQL Server instance.
Hosting integration
Section titled “Hosting integration”The Aspire Azure SQL Database hosting integration models the SQL Server as the AzureSqlServerResource type and SQL databases as the AzureSqlDatabaseResource type. To access these types and APIs for expressing them within your AppHost project, install the 📦 Aspire.Hosting.Azure.Sql NuGet package:
aspire add azure-sqlLa CLI de Aspire es interactiva; asegúrate de seleccionar el resultado adecuado cuando se te pida:
Select an integration to add:
> azure-sql (Aspire.Hosting.Azure.Sql)> Other results listed as selectable options...#:package Aspire.Hosting.Azure.Sql@*<PackageReference Include="Aspire.Hosting.Azure.Sql" Version="*" />Add Azure SQL server resource and database resource
Section titled “Add Azure SQL server resource and database resource”In your AppHost project, call AddAzureSqlServer to add and return an Azure SQL server resource builder. Chain a call to the returned resource builder to AddDatabase, to add an Azure SQL database resource:
var builder = DistributedApplication.CreateBuilder(args);
var azureSql = builder.AddAzureSqlServer("azuresql") .AddDatabase("database");
var myService = builder.AddProject<Projects.MyService>() .WithReference(azureSql);The preceding call to AddAzureSqlServer configures the Azure SQL server resource to be deployed as an Azure SQL Database server.
Connect to an existing Azure SQL server
Section titled “Connect to an existing Azure SQL server”You might have an existing Azure SQL Database service that you want to connect to. You can chain a call to annotate that your AzureSqlServerResource is an existing resource:
var builder = DistributedApplication.CreateBuilder(args);
var existingSqlServerName = builder.AddParameter("existingSqlServerName");var existingSqlServerResourceGroup = builder.AddParameter("existingSqlServerResourceGroup");
var sqlserver = builder.AddAzureSqlServer("sqlserver") .AsExisting(existingSqlServerName, existingSqlServerResourceGroup) .AddDatabase("database");
builder.AddProject<Projects.ExampleProject>() .WithReference(sqlserver);
// After adding all resources, run the app...For more information on treating Azure SQL resources as existing resources, see Use existing Azure resources.
Run Azure SQL server resource as a container
Section titled “Run Azure SQL server resource as a container”The Azure SQL Server hosting integration supports running the Azure SQL server as a local container. This is beneficial for situations where you want to run the Azure SQL server locally for development and testing purposes, avoiding the need to provision an Azure resource or connect to an existing Azure SQL server.
To run the Azure SQL server as a container, call the RunAsContainer method:
var builder = DistributedApplication.CreateBuilder(args);
var azureSql = builder.AddAzureSqlServer("azuresql") .RunAsContainer();
var azureSqlData = azureSql.AddDatabase("database");
var exampleProject = builder.AddProject<Projects.ExampleProject>() .WithReference(azureSqlData);The preceding code configures an Azure SQL Database resource to run locally in a container.
Client integration
Section titled “Client integration”To get started with the Aspire SQL Server Entity Framework Core integration, install the 📦 Aspire.Microsoft.EntityFrameworkCore.SqlServer NuGet package in the client-consuming project, that is, the project for the application that uses the SQL Server Entity Framework Core client.
dotnet add package Aspire.Microsoft.EntityFrameworkCore.SqlServer#:package Aspire.Microsoft.EntityFrameworkCore.SqlServer@*<PackageReference Include="Aspire.Microsoft.EntityFrameworkCore.SqlServer" Version="*" />Add SQL Server database context
Section titled “Add SQL Server database context”In the Program.cs file of your client-consuming project, call the AddSqlServerDbContext extension method on any IHostApplicationBuilder to register a Microsoft.EntityFrameworkCore.DbContext for use via the dependency injection container. The method takes a connection name parameter.
builder.AddSqlServerDbContext<ExampleDbContext>( connectionName: "database");To retrieve ExampleDbContext object from a service:
public class ExampleService(ExampleDbContext context){ // Use context...}For more information on dependency injection, see .NET dependency injection.
Enrich a SQL Server database context
Section titled “Enrich a SQL Server database context”You may prefer to use the standard Entity Framework method to obtain a database context and add it to the dependency injection container:
builder.Services.AddDbContext<ExampleDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("database") ?? throw new InvalidOperationException("Connection string 'database' not found.")));You have more flexibility when you create the database context in this way, for example:
- You can reuse existing configuration code for the database context without rewriting it for Aspire.
- You can use Entity Framework Core interceptors to modify database operations.
- You can choose not to use Entity Framework Core context pooling, which may perform better in some circumstances.
If you use this method, you can enhance the database context with Aspire-style retries, health checks, logging, and telemetry features by calling the EnrichSqlServerDbContext method:
builder.EnrichSqlServerDbContext<ExampleDbContext>( configureSettings: settings => { settings.DisableRetry = false; settings.CommandTimeout = 30; // seconds });The settings parameter is an instance of the MicrosoftEntityFrameworkCoreSqlServerSettings class.
Configuration
Section titled “Configuration”The Aspire SQL Server Entity Framework Core integration provides multiple configuration approaches and options to meet the requirements and conventions of your project.
Use connection string
Section titled “Use connection string”When using a connection string from the ConnectionStrings configuration section, you provide the name of the connection string when calling builder.AddSqlServerDbContext<TContext>():
builder.AddSqlServerDbContext<ExampleDbContext>("sql");The connection string is retrieved from the ConnectionStrings configuration section:
{ "ConnectionStrings": { "sql": "Data Source=myserver;Initial Catalog=master" }}The EnrichSqlServerDbContext won’t make use of the ConnectionStrings configuration section since it expects a DbContext to be registered at the point it’s called.
For more information, see the ConnectionString.
Use configuration providers
Section titled “Use configuration providers”The Aspire SQL Server Entity Framework Core integration supports Microsoft.Extensions.Configuration. It loads the MicrosoftEntityFrameworkCoreSqlServerSettings from configuration files such as appsettings.json by using the Aspire:Microsoft:EntityFrameworkCore:SqlServer key. If you have set up your configurations in the Aspire:Microsoft:EntityFrameworkCore:SqlServer section you can just call the method without passing any parameter.
The following is an example of an appsettings.json file that configures some of the available options:
{ "Aspire": { "Microsoft": { "EntityFrameworkCore": { "SqlServer": { "ConnectionString": "YOUR_CONNECTIONSTRING", "DbContextPooling": true, "DisableHealthChecks": true, "DisableTracing": true, "DisableMetrics": false } } } }}Use inline configurations
Section titled “Use inline configurations”You can also pass the Action<MicrosoftEntityFrameworkCoreSqlServerSettings> delegate to set up some or all the options inline, for example to turn off the metrics:
builder.AddSqlServerDbContext<YourDbContext>( "sql", static settings => settings.DisableMetrics = true);Configure multiple DbContext connections
Section titled “Configure multiple DbContext connections”If you want to register more than one DbContext with different configuration, you can use $"Aspire.Microsoft.EntityFrameworkCore.SqlServer:{typeof(TContext).Name}" configuration section name. The json configuration would look like:
{ "Aspire": { "Microsoft": { "EntityFrameworkCore": { "SqlServer": { "ConnectionString": "YOUR_CONNECTIONSTRING", "DbContextPooling": true, "DisableHealthChecks": true, "DisableTracing": true, "DisableMetrics": false, "AnotherDbContext": { "ConnectionString": "AnotherDbContext_CONNECTIONSTRING", "DisableTracing": false } } } } }}Then calling the AddSqlServerDbContext method with AnotherDbContext type parameter would load the settings from Aspire:Microsoft:EntityFrameworkCore:SqlServer:AnotherDbContext section.
builder.AddSqlServerDbContext<AnotherDbContext>("another-sql");Configuration options
Section titled “Configuration options”Here are the configurable options with corresponding default values:
| Name | Description |
|---|---|
ConnectionString | The connection string of the SQL Server database to connect to. |
DbContextPooling | A boolean value that indicates whether the db context will be pooled or explicitly created every time it’s requested |
MaxRetryCount | The maximum number of retry attempts. Default value is 6, set it to 0 to disable the retry mechanism. |
DisableHealthChecks | A boolean value that indicates whether the database health check is disabled or not. |
DisableTracing | A boolean value that indicates whether the OpenTelemetry tracing is disabled or not. |
DisableMetrics | A boolean value that indicates whether the OpenTelemetry metrics are disabled or not. |
Timeout | The time in seconds to wait for the command to execute. |
By default, the Aspire Sql Server Entity Framework Core integration handles the following:
- Adds the
DbContextHealthCheck, which calls EF Core’sCanConnectAsyncmethod. The name of the health check is the name of theTContexttype. - Integrates with the
/healthHTTP endpoint, which specifies all registered health checks must pass for app to be considered ready to accept traffic
Observability and telemetry
Section titled “Observability and telemetry”Aspire integrations automatically set up Logging, Tracing, and Metrics configurations.
Logging
Section titled “Logging”The Aspire SQL Server Entity Framework Core integration uses the following Log categories:
Microsoft.EntityFrameworkCore.ChangeTrackingMicrosoft.EntityFrameworkCore.Database.CommandMicrosoft.EntityFrameworkCore.Database.ConnectionMicrosoft.EntityFrameworkCore.Database.TransactionMicrosoft.EntityFrameworkCore.InfrastructureMicrosoft.EntityFrameworkCore.MigrationsMicrosoft.EntityFrameworkCore.ModelMicrosoft.EntityFrameworkCore.Model.ValidationMicrosoft.EntityFrameworkCore.QueryMicrosoft.EntityFrameworkCore.Update
Tracing
Section titled “Tracing”The Aspire SQL Server Entity Framework Core integration will emit the following Tracing activities using OpenTelemetry:
OpenTelemetry.Instrumentation.EntityFrameworkCore
Metrics
Section titled “Metrics”The Aspire SQL Server Entity Framework Core integration will emit the following metrics using OpenTelemetry:
- Microsoft.EntityFrameworkCore:
ec_Microsoft_EntityFrameworkCore_active_db_contextsec_Microsoft_EntityFrameworkCore_total_queriesec_Microsoft_EntityFrameworkCore_queries_per_secondec_Microsoft_EntityFrameworkCore_total_save_changesec_Microsoft_EntityFrameworkCore_save_changes_per_secondec_Microsoft_EntityFrameworkCore_compiled_query_cache_hit_rateec_Microsoft_Entity_total_execution_strategy_operation_failuresec_Microsoft_E_execution_strategy_operation_failures_per_secondec_Microsoft_EntityFramew_total_optimistic_concurrency_failuresec_Microsoft_EntityF_optimistic_concurrency_failures_per_second