Skip to content

Add Azure SQL integration articles #3217

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions docs/database/azure-sql-entity-framework-integration.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
---
title: .NET Aspire Azure SQL Entity Framework Core integration
description: Learn how to use the .NET Aspire Azure SQL integration with Entity Framework Core, which includes both hosting and client integrations.
ms.date: 04/30/2025
uid: database/azure-sql-entity-framework-integration
---

# .NET Aspire Azure SQL Entity Framework Core integration

[!INCLUDE [includes-hosting-and-client](../includes/includes-hosting-and-client.md)]

[Azure SQL](https://azure.microsoft.com/products/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 .NET Aspire Azure SQL Server Hosting integration provides methods to create a new Azure Database server and databases from code in your .NET Aspire app host project. In a consuming project, you can use the .NET Aspire SQL Server Entity Framework Core client integration as you would for any other SQL Server instance.

## Hosting integration

[!INCLUDE [azure-sql-hosting](includes/azure-sql-hosting.md)]

## Client integration

[!INCLUDE [sql-server-ef-client](includes/sql-server-ef-client.md)]

## See also

- [Azure SQL Database](/azure/azure-sql/database)
- [.NET Aspire database containers sample](/samples/dotnet/aspire-samples/aspire-database-containers/)
- [.NET Aspire integrations](../fundamentals/integrations-overview.md)
- [.NET Aspire GitHub repo](https://github.com/dotnet/aspire)
- [Azure SQL & SQL Server Aspire Samples](https://github.com/Azure-Samples/azure-sql-db-aspire)
28 changes: 28 additions & 0 deletions docs/database/azure-sql-integration.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
---
title: .NET Aspire Azure SQL integration
description: Learn how to use the .NET Aspire Azure SQL integration, which includes both hosting and client integrations.
ms.date: 04/30/2025
uid: database/azure-sql-integration
---

# .NET Aspire Azure SQL integration

[!INCLUDE [includes-hosting-and-client](../includes/includes-hosting-and-client.md)]

[Azure SQL](https://azure.microsoft.com/products/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 .NET Aspire Azure SQL Server Hosting integration provides methods to create a new Azure Database server and databases from code in your .NET Aspire app host project. In a consuming project, you can use the .NET Aspire SQL Server client integration as you would for any other SQL Server instance.

## Hosting integration

[!INCLUDE [azure-sql-hosting](includes/azure-sql-hosting.md)]

## Client integration

[!INCLUDE [sql-server-client](includes/sql-server-client.md)]

## See also

- [Azure SQL Database](/azure/azure-sql/database)
- [.NET Aspire database containers sample](/samples/dotnet/aspire-samples/aspire-database-containers/)
- [.NET Aspire integrations](../fundamentals/integrations-overview.md)
- [.NET Aspire GitHub repo](https://github.com/dotnet/aspire)
- [Azure SQL & SQL Server Aspire Samples](https://github.com/Azure-Samples/azure-sql-db-aspire)
96 changes: 96 additions & 0 deletions docs/database/includes/azure-sql-hosting.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
---
ms.topic: include
---

The Azure SQL hosting integration models the Azure SQL server as the <xref:Aspire.Hosting.Azure.AzureSqlServerResource> type and the database as the <xref:Aspire.Hosting.Azure.AzureSqlDatabaseResource> type. To access these types and APIs, add the [📦 Aspire.Hosting.Azure.Sql](https://www.nuget.org/packages/Aspire.Hosting.Azure.Sql) NuGet package in the [app host](xref:dotnet/aspire/app-host) project.

### [.NET CLI](#tab/dotnet-cli)

```dotnetcli
dotnet add package Aspire.Hosting.Azure.Sql
```

### [PackageReference](#tab/package-reference)

```xml
<PackageReference Include="Aspire.Hosting.Azure.Sql"
Version="*" />
```

---

For more information, see [dotnet add package](/dotnet/core/tools/dotnet-add-package) or [Manage package dependencies in .NET applications](/dotnet/core/tools/dependencies).

The Azure SQL hosting integration takes a dependency on the [📦 Aspire.Hosting.SqlServer](https://www.nuget.org/packages/Aspire.Hosting.SqlServer/) NuGet package, extending it to support Azure. Everything that you can do with the [.NET Aspire SQL Server integration](../sql-server-integration.md) and [.NET Aspire SQL Server Entity Framework Core integration](../sql-server-entity-framework-integration.md) you can also do with this integration.

### Add Azure SQL server resource and database resource

In your app host project, call <xref:Aspire.Hosting.AzureSqlExtensions.AddAzureSqlServer*> to add and return an Azure SQL server resource builder. Chain a call to the returned resource builder to <xref:Aspire.Hosting.AzureSqlExtensions.AddDatabase*>, to add an Azure SQL database resource:

```csharp
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](/azure/azure-sql/database/sql-database-paas-overview).

> [!IMPORTANT]
> By default, `AddAzureSqlServer` configures [Microsoft Entra ID](/azure/azure-sql/database/authentication-aad-overview) authentication. This requires changes to applications that need to connect to these resources. For more information, see [Client integration](#client-integration).

> [!TIP]
> When you call <xref:Aspire.Hosting.AzureSqlExtensions.AddAzureSqlServer*>, it implicitly calls <xref:Aspire.Hosting.AzureProvisionerExtensions.AddAzureProvisioning*> — which adds support for generating Azure resources dynamically during app startup. The app must configure the appropriate subscription and location. For more information, see [Local provisioning: Configuration](../../azure/local-provisioning.md#configuration).

### Connect to an existing Azure SQL server

You might have an existing Azure SQL database that you want to connect to. Instead of representing a new Azure SQL server resource, you can add a connection string to the app host. To add a connection to an existing Azure SQL server, call the <xref:Aspire.Hosting.ParameterResourceBuilderExtensions.AddConnectionString*> method:

```csharp
var builder = DistributedApplication.CreateBuilder(args);

var azureSql = builder.AddConnectionString("database");

builder.AddProject<Projects.WebApplication>("web")
.WithReference(azureSql);

// After adding all resources, run the app...
```

[!INCLUDE [connection-strings-alert](../../includes/connection-strings-alert.md)]

The connection string is configured in the app host's configuration, typically under [User Secrets](/aspnet/core/security/app-secrets), under the `ConnectionStrings` section. The app host injects this connection string as an environment variable into all dependent resources, for example:

```json
{
"ConnectionStrings": {
"database": "Server=tcp:<Azure-SQL-server-name>.database.windows.net,1433;Initial Catalog=<database-name>;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;User ID=<username>;"
}
}
```

The dependent resource can access the injected connection string by calling the <xref:Microsoft.Extensions.Configuration.ConfigurationExtensions.GetConnectionString*> method, and passing the connection name as the parameter, in this case `"database"`. The `GetConnectionString` API is shorthand for `IConfiguration.GetSection("ConnectionStrings")[name]`.

### 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 <xref:Aspire.Hosting.AzureSqlExtensions.RunAsContainer*> method:

```csharp
var builder = DistributedApplication.CreateBuilder(args);

var azureSql = builder.AddAzureSqlServer("azuresql")
.RunAsContainer();

var azureSqlData = postgres.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.

> [!TIP]
> The `RunAsContainer` method is useful for local development and testing. The API exposes an optional delegate that enables you to customize the underlying <xref:Aspire.Hosting.ApplicationModel.SqlServerServerResource> configuration. For example, you can add a data volume or data bind mount. For more information, see the [.NET Aspire SQL Server hosting integration](../sql-server-integration.md#add-sql-server-resource-with-data-volume) section.
166 changes: 166 additions & 0 deletions docs/database/includes/sql-server-client.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
---
ms.topic: include
---

To get started with the .NET Aspire SQL Server client integration, install the [📦 Aspire.Microsoft.Data.SqlClient](https://www.nuget.org/packages/Aspire.Microsoft.Data.SqlClient) NuGet package in the client-consuming project, that is, the project for the application that uses the SQL Server client. The SQL Server client integration registers a <xref:System.Data.SqlClient.SqlConnection> instance that you can use to interact with SQL Server.

### [.NET CLI](#tab/dotnet-cli)

```dotnetcli
dotnet add package Aspire.Microsoft.Data.SqlClient
```

### [PackageReference](#tab/package-reference)

```xml
<PackageReference Include="Aspire.Microsoft.Data.SqlClient"
Version="*" />
```

---

### Add SQL Server client

In the _:::no-loc text="Program.cs":::_ file of your client-consuming project, call the <xref:Microsoft.Extensions.Hosting.AspireSqlServerSqlClientExtensions.AddSqlServerClient*> extension method on any <xref:Microsoft.Extensions.Hosting.IHostApplicationBuilder> to register a `SqlConnection` for use via the dependency injection container. The method takes a connection name parameter.

```csharp
builder.AddSqlServerClient(connectionName: "database");
```

> [!TIP]
> The `connectionName` parameter must match the name used when adding the SQL Server database resource in the app host project. In other words, when you call `AddDatabase` and provide a name of `database` that same name should be used when calling `AddSqlServerClient`. For more information, see [Add SQL Server resource and database resource](../sql-server-integration.md#add-sql-server-resource-and-database-resource).

You can then retrieve the <xref:Microsoft.Data.SqlClient.SqlConnection> instance using dependency injection. For example, to retrieve the connection from an example service:

```csharp
public class ExampleService(SqlConnection connection)
{
// Use connection...
}
```

For more information on dependency injection, see [.NET dependency injection](/dotnet/core/extensions/dependency-injection).

### Add keyed SQL Server client

There might be situations where you want to register multiple `SqlConnection` instances with different connection names. To register keyed SQL Server clients, call the <xref:Microsoft.Extensions.Hosting.AspireSqlServerSqlClientExtensions.AddKeyedSqlServerClient*> method:

```csharp
builder.AddKeyedSqlServerClient(name: "mainDb");
builder.AddKeyedSqlServerClient(name: "loggingDb");
```

> [!IMPORTANT]
> When using keyed services, it's expected that your SQL Server resource configured two named databases, one for the `mainDb` and one for the `loggingDb`.

Then you can retrieve the `SqlConnection` instances using dependency injection. For example, to retrieve the connection from an example service:

```csharp
public class ExampleService(
[FromKeyedServices("mainDb")] SqlConnection mainDbConnection,
[FromKeyedServices("loggingDb")] SqlConnection loggingDbConnection)
{
// Use connections...
}
```

For more information on keyed services, see [.NET dependency injection: Keyed services](/dotnet/core/extensions/dependency-injection#keyed-services).

### Configuration

The .NET Aspire SQL Server integration provides multiple options to configure the connection based on the requirements and conventions of your project.

#### Use a connection string

When using a connection string from the `ConnectionStrings` configuration section, you can provide the name of the connection string when calling the <xref:Microsoft.Extensions.Hosting.AspireSqlServerSqlClientExtensions.AddSqlServerClient*> method:

```csharp
builder.AddSqlServerClient(connectionName: "sql");
```

Then the connection string is retrieved from the `ConnectionStrings` configuration section:

```json
{
"ConnectionStrings": {
"database": "Data Source=myserver;Initial Catalog=master"
}
}
```

For more information on how to format this connection string, see the [ConnectionString](/dotnet/api/system.data.sqlclient.sqlconnection.connectionstring#remarks).

#### Use configuration providers

The .NET Aspire SQL Server integration supports <xref:Microsoft.Extensions.Configuration>. It loads the <xref:Aspire.Microsoft.Data.SqlClient.MicrosoftDataSqlClientSettings> from configuration by using the `Aspire:Microsoft:Data:SqlClient` key. The following snippet is an example of a _:::no-loc text="appsettings.json":::_ file that configures some of the options:

```json
{
"Aspire": {
"Microsoft": {
"Data": {
"SqlClient": {
"ConnectionString": "YOUR_CONNECTIONSTRING",
"DisableHealthChecks": false,
"DisableMetrics": true
}
}
}
}
}
```

For the complete SQL Server client integration JSON schema, see [Aspire.Microsoft.Data.SqlClient/ConfigurationSchema.json](https://github.com/dotnet/aspire/blob/v8.2.2/src/Components/Aspire.Microsoft.Data.SqlClient/ConfigurationSchema.json).

#### Use inline delegates

Also you can pass the `Action<MicrosoftDataSqlClientSettings> configureSettings` delegate to set up some or all the options inline, for example to disable health checks from code:

```csharp
builder.AddSqlServerClient(
"database",
static settings => settings.DisableHealthChecks = true);
```

### Client integration health checks

By default, .NET Aspire integrations enable [health checks](../../fundamentals/health-checks.md) for all services. For more information, see [.NET Aspire integrations overview](../../fundamentals/integrations-overview.md).

The .NET Aspire SQL Server integration:

- Adds the health check when <xref:Aspire.Microsoft.Data.SqlClient.MicrosoftDataSqlClientSettings.DisableHealthChecks?displayProperty=nameWithType> is `false`, which attempts to connect to the SQL Server.
- Integrates with the `/health` HTTP endpoint, which specifies all registered health checks must pass for app to be considered ready to accept traffic.

[!INCLUDE [integration-observability-and-telemetry](../../includes/integration-observability-and-telemetry.md)]

#### Logging

The .NET Aspire SQL Server integration currently doesn't enable logging by default due to limitations of the <xref:Microsoft.Data.SqlClient>.

#### Tracing

The .NET Aspire SQL Server integration emits the following tracing activities using OpenTelemetry:

- `OpenTelemetry.Instrumentation.SqlClient`

#### Metrics

The .NET Aspire SQL Server integration will emit the following metrics using OpenTelemetry:

- Microsoft.Data.SqlClient.EventSource
- `active-hard-connections`
- `hard-connects`
- `hard-disconnects`
- `active-soft-connects`
- `soft-connects`
- `soft-disconnects`
- `number-of-non-pooled-connections`
- `number-of-pooled-connections`
- `number-of-active-connection-pool-groups`
- `number-of-inactive-connection-pool-groups`
- `number-of-active-connection-pools`
- `number-of-inactive-connection-pools`
- `number-of-active-connections`
- `number-of-free-connections`
- `number-of-stasis-connections`
- `number-of-reclaimed-connections`
Loading
Loading