Ir al contenido

Azure SQL EF Core Client integration reference

Esta página aún no está disponible en tu idioma.

Azure SQL Database logo

To get started with the Aspire Azure SQL EF Core integrations, follow the Get started with Azure SQL integrations guide.

This article includes full details about the Aspire Azure SQL EF Core Client integration, which allows you to connect to and interact with Azure SQL databases from your Aspire consuming projects using Entity Framework Core.

To get started with the Aspire Azure SQL Server Entity Framework Core client integration, install the 📦 Aspire.Microsoft.EntityFrameworkCore.SqlServer NuGet package in the client-consuming project, that is, the project for the application that uses the Azure SQL Server EF Core client.

.NET CLI — Add Aspire.Microsoft.EntityFrameworkCore.SqlServer package
dotnet add package Aspire.Microsoft.EntityFrameworkCore.SqlServer

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.

C# — Program.cs
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.

When you use the WithReference method to pass an Azure SQL server or database resource from the AppHost project to a consuming client project, several properties are available to use in the consuming project.

Aspire exposes each property as an environment variable named [RESOURCE]_[PROPERTY]. For instance, the Uri property of a resource called sqldb becomes SQLDB_URI.

The Azure SQL server resource exposes the following connection properties:

Property NameDescription
HostThe hostname or IP address of the Azure SQL Server
PortThe port number the SQL Server is listening on
UsernameThe username for authentication
PasswordThe password for authentication
UriThe connection URI in mssql:// format, with the format mssql://{Username}:{Password}@{Host}:{Port}
JdbcConnectionStringJDBC-format connection string, with the format jdbc:sqlserver://{Host}:{Port};trustServerCertificate=true. User and password credentials are provided as separate Username and Password properties.

Example connection strings:

Uri: mssql://sa:p%40ssw0rd1@myserver.database.windows.net:1433
JdbcConnectionString: jdbc:sqlserver://myserver.database.windows.net:1433;trustServerCertificate=true

The Azure SQL database resource inherits all properties from its parent AzureSqlServerResource and adds:

Property NameDescription
UriThe connection URI in mssql:// format, with the format mssql://{Username}:{Password}@{Host}:{Port}/{DatabaseName}
JdbcConnectionStringJDBC connection string with database name, with the format jdbc:sqlserver://{Host}:{Port};trustServerCertificate=true;databaseName={DatabaseName}. User and password credentials are provided as separate Username and Password properties.
DatabaseNameThe name of the database

Example connection strings:

Uri: mssql://sa:p%40ssw0rd1@myserver.database.windows.net:1433/catalog
JdbcConnectionString: jdbc:sqlserver://myserver.database.windows.net:1433;trustServerCertificate=true;databaseName=catalog

You may prefer to use the standard Entity Framework method to obtain a database context and add it to the dependency injection container:

C# — Program.cs
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:

C# — Program.cs
builder.EnrichSqlServerDbContext<ExampleDbContext>(
configureSettings: settings =>
{
settings.DisableRetry = false;
settings.CommandTimeout = 30; // seconds
});

The settings parameter is an instance of the MicrosoftEntityFrameworkCoreSqlServerSettings class.

The Aspire SQL Server Entity Framework Core integration provides multiple configuration approaches and options to meet the requirements and conventions of your project.

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.

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:

JSON — appsettings.json
{
"Aspire": {
"Microsoft": {
"EntityFrameworkCore": {
"SqlServer": {
"ConnectionString": "YOUR_CONNECTIONSTRING",
"DbContextPooling": true,
"DisableHealthChecks": true,
"DisableTracing": true,
"DisableMetrics": false
}
}
}
}
}

You can also pass the Action<MicrosoftEntityFrameworkCoreSqlServerSettings> delegate to set up some or all the options inline, for example to turn off the metrics:

C# — Program.cs
builder.AddSqlServerDbContext<YourDbContext>(
"sql",
static settings =>
settings.DisableMetrics = true);

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:

JSON — appsettings.json
{
"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.

C# — Program.cs
builder.AddSqlServerDbContext<AnotherDbContext>("another-sql");

Here are the configurable options with corresponding default values:

NameDescription
ConnectionStringThe connection string of the SQL Server database to connect to.
DbContextPoolingA boolean value that indicates whether the db context will be pooled or explicitly created every time it’s requested
MaxRetryCountThe maximum number of retry attempts. Default value is 6, set it to 0 to disable the retry mechanism.
DisableHealthChecksA boolean value that indicates whether the database health check is disabled or not.
DisableTracingA boolean value that indicates whether the OpenTelemetry tracing is disabled or not.
DisableMetricsA boolean value that indicates whether the OpenTelemetry metrics are disabled or not.
TimeoutThe 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’s CanConnectAsync method. The name of the health check is the name of the TContext type.
  • Integrates with the /health HTTP endpoint, which specifies all registered health checks must pass for app to be considered ready to accept traffic

Aspire integrations automatically set up Logging, Tracing, and Metrics configurations.

The Aspire SQL Server Entity Framework Core integration uses the following Log categories:

  • Microsoft.EntityFrameworkCore.ChangeTracking
  • Microsoft.EntityFrameworkCore.Database.Command
  • Microsoft.EntityFrameworkCore.Database.Connection
  • Microsoft.EntityFrameworkCore.Database.Transaction
  • Microsoft.EntityFrameworkCore.Infrastructure
  • Microsoft.EntityFrameworkCore.Migrations
  • Microsoft.EntityFrameworkCore.Model
  • Microsoft.EntityFrameworkCore.Model.Validation
  • Microsoft.EntityFrameworkCore.Query
  • Microsoft.EntityFrameworkCore.Update

The Aspire SQL Server Entity Framework Core integration will emit the following Tracing activities using OpenTelemetry:

  • OpenTelemetry.Instrumentation.EntityFrameworkCore

The Aspire SQL Server Entity Framework Core integration will emit the following metrics using OpenTelemetry:

  • Microsoft.EntityFrameworkCore:
    • ec_Microsoft_EntityFrameworkCore_active_db_contexts
    • ec_Microsoft_EntityFrameworkCore_total_queries
    • ec_Microsoft_EntityFrameworkCore_queries_per_second
    • ec_Microsoft_EntityFrameworkCore_total_save_changes
    • ec_Microsoft_EntityFrameworkCore_save_changes_per_second
    • ec_Microsoft_EntityFrameworkCore_compiled_query_cache_hit_rate
    • ec_Microsoft_Entity_total_execution_strategy_operation_failures
    • ec_Microsoft_E_execution_strategy_operation_failures_per_second
    • ec_Microsoft_EntityFramew_total_optimistic_concurrency_failures
    • ec_Microsoft_EntityF_optimistic_concurrency_failures_per_second