.NET Aspire SqlServer Entity Framework Core component

In this article, you learn how to use the .NET Aspire SqlServer Entity Framework Core component. The Aspire.Microsoft.EntityFrameworkCore.SqlServer library is used to:

  • Registers EntityFrameworkCore DbContext service for connecting to a SQL database.
  • Automatically configures the following:
    • Connection pooling to efficiently managed HTTP requests and database connections
    • Health checks, logging and telemetry to improve app monitoring and diagnostics

Prerequisites

  • SQL database and connection string for accessing the database.

Get started

To get started with the .NET Aspire SQL Server Entity Framework Core component, install the Aspire.Microsoft.EntityFrameworkCore.SqlServer NuGet package.

dotnet add package Aspire.Microsoft.EntityFrameworkCore.SqlServer --prerelease

For more information, see dotnet add package or Manage package dependencies in .NET applications.

Example usage

In the Program.cs file of your component-consuming project, call the AddSqlServerDbContext extension to register a DbContext for use via the dependency injection container.

builder.AddSqlServerDbContext<YourDbContext>("sql");

To retrieve YourDbContext object from a service:

public class ExampleService(YourDbContext client)
{
    // Use client...
}

App host usage

In your app host project, register a SqlServer database and consume the connection using the following methods, such as AddSqlServer:

var sql = builder.AddSqlServer("sql")
                 .AddDatabase("sqldata");

var myService = builder.AddProject<Projects.MyService>()
                       .WithReference(sql);

The WithReference method configures a connection in the MyService project named sqldata. In the Program.cs file of MyService, the sql connection can be consumed using:

builder.AddSqlServerDbContext<MyDbContext>("sqldata");

Configuration

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

Use configuration providers

The .NET Aspire SQL Server Entity Framework Core component 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,
          "HealthChecks": false,
          "Tracing": false,
          "Metrics": true
        }
      }
    }
  }
}

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.ConnectionString = "YOUR_CONNECTIONSTRING");

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,
            "HealthChecks": false,
            "Tracing": false,
            "Metrics": true,
          "AnotherDbContext": {
            "ConnectionString": "AnotherDbContext_CONNECTIONSTRING",
            "Tracing": true
          }
        }
      }
    }
  }
}

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

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.
HealthChecks A boolean value that indicates whether the database health check is enabled or not.
Tracing A boolean value that indicates whether the OpenTelemetry tracing is enabled or not.
Metrics A boolean value that indicates whether the OpenTelemetry metrics are enabled or not.
Timeout The time in seconds to wait for the command to execute.

Health checks

By default, .NET Aspire components enable health checks for all services. For more information, see .NET Aspire components overview.

By default, the .NET Aspire Sql Server Entity Framework Core component 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

Observability and telemetry

.NET Aspire components automatically set up Logging, Tracing, and Metrics configurations, which are sometimes known as the pillars of observability. For more information about component observability and telemetry, see .NET Aspire components overview. Depending on the backing service, some components may only support some of these features. For example, some components support logging and tracing, but not metrics. Telemetry features can also be disabled using the techniques presented in the Configuration section.

Logging

The .NET Aspire SQL Server Entity Framework Core component 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.Infrastructure
  • Microsoft.EntityFrameworkCore.Migrations
  • Microsoft.EntityFrameworkCore.Model
  • Microsoft.EntityFrameworkCore.Model.Validation
  • Microsoft.EntityFrameworkCore.Query
  • Microsoft.EntityFrameworkCore.Update

Tracing

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

  • "OpenTelemetry.Instrumentation.EntityFrameworkCore"

Metrics

The .NET Aspire SQL Server Entity Framework Core component 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
  • Azure SQL Database documentation

  • .NET Aspire components

  • .NET Aspire GitHub repo