Connect to MySQL with EF Core
Dieser Inhalt ist noch nicht in deiner Sprache verfügbar.
This page describes how C# consuming apps connect to a MySQL resource that’s already modeled in your AppHost using Entity Framework Core (EF Core). For the AppHost API surface — adding a MySQL server, databases, phpMyAdmin, volumes, and more — see MySQL Hosting integration.
The Aspire MySQL Pomelo EF Core client integration registers a DbContext subclass through dependency injection and adds health checks and telemetry automatically.
Connect from your app
Section titled “Connect from your app”Add the Aspire Pomelo MySQL EF Core client integration to your C# consuming app to register a DbContext for MySQL with automatic health checks and telemetry.
Install the client integration
Section titled “Install the client integration”Install the 📦 Aspire.Pomelo.EntityFrameworkCore.MySql NuGet package in the client-consuming project:
dotnet add package Aspire.Pomelo.EntityFrameworkCore.MySql#:package Aspire.Pomelo.EntityFrameworkCore.MySql@*<PackageReference Include="Aspire.Pomelo.EntityFrameworkCore.MySql" Version="*" />For an introduction to the MySQL EF Core integration, see Get started with the MySQL EF Core integration.
Add MySQL database context
Section titled “Add MySQL database context”In the Program.cs file of your client-consuming project, call the AddMySqlDbContext extension method on any IHostApplicationBuilder to register a DbContext for use via the dependency injection container. The method takes a connection name parameter.
builder.AddMySqlDbContext<MyDbContext>(connectionName: "mysqldb");You can then retrieve the MyDbContext instance using dependency injection. For example, to retrieve the data source from an example service:
public class ExampleService(MyDbContext context){ // Use the MySQL database context...}For more information on dependency injection, see .NET dependency injection.
Enrich MySQL database context
Section titled “Enrich MySQL 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.UseMySql(builder.Configuration.GetConnectionString("mysqldb") ?? throw new InvalidOperationException("Connection string 'mysqldb' not found."), ServerVersion.AutoDetect(builder.Configuration.GetConnectionString("mysqldb"))));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 EnrichMySqlDbContext method:
builder.EnrichMySqlDbContext<ExampleDbContext>( configureSettings: settings => { settings.DisableRetry = false; settings.CommandTimeout = 30; // seconds });The settings parameter is an instance of the MySqlEntityFrameworkCoreSettings class.
Connection properties
Section titled “Connection properties”When you use the WithReference method to pass a MySQL server or database resource from the AppHost project to a consuming project, Aspire exposes each property as an environment variable named [RESOURCE]_[PROPERTY]. For instance, the ConnectionString property of a resource called mysqldb becomes MYSQLDB_CONNECTIONSTRING.
MySQL server
Section titled “MySQL server”The MySQL server resource exposes the following connection properties:
| Property Name | Description |
|---|---|
Host | The hostname or IP address of the MySQL server |
Port | The port number the MySQL server is listening on |
Username | The username for authentication (typically root) |
Password | The password for authentication |
Example connection properties:
Host: localhostPort: 3306Username: rootPassword: <generated-password>MySQL database
Section titled “MySQL database”The MySQL database resource inherits all properties from its parent MySqlServerResource and adds:
| Property Name | Description |
|---|---|
DatabaseName | The MySQL database name |
ConnectionString | The full connection string in the format Server={Host};Port={Port};User ID={Username};Password={Password};Database={DatabaseName} |
Example connection string:
Server=localhost;Port=3306;User ID=root;Password=<generated-password>;Database=mysqldbConfiguration
Section titled “Configuration”The Aspire MySQL Pomelo EF Core integration provides multiple configuration approaches and options to meet the requirements and conventions of your project.
Use a connection string
Section titled “Use a connection string”When using a connection string from the ConnectionStrings configuration section, you provide the name of the connection string when calling builder.AddMySqlDbContext():
builder.AddMySqlDbContext<ExampleDbContext>(connectionName: "mysqldb");The connection string is retrieved from the ConnectionStrings configuration section:
{ "ConnectionStrings": { "mysql": "Server=mysql;Database=mysqldb" }}For more information on how to format this connection string, see MySqlConnector: ConnectionString documentation.
Use configuration providers
Section titled “Use configuration providers”The Aspire MySQL EF Core integration supports Microsoft.Extensions.Configuration from configuration files such as appsettings.json by using the Aspire:Pomelo:EntityFrameworkCore:MySql key:
{ "Aspire": { "Pomelo": { "EntityFrameworkCore": { "MySql": { "ConnectionString": "Server=myserver;Database=mysqldb", "DisableHealthChecks": false, "DisableTracing": false } } } }}Use inline delegates
Section titled “Use inline delegates”You can also pass the Action<MySqlEntityFrameworkCoreSettings> delegate to set up some or all the options inline, for example to disable health checks from code:
builder.AddMySqlDbContext<ExampleDbContext>( "mysqldb", static settings => settings.DisableHealthChecks = true);Configuration options
Section titled “Configuration options”Here are the configurable options with corresponding default values:
| Name | Description |
|---|---|
ConnectionString | The connection string of the MySQL database to connect to |
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 |
Health checks
Section titled “Health checks”By default, Aspire integrations enable health checks for all services. For more information, see Aspire integrations overview.
The Aspire MySQL EF Core integration handles the following:
- Adds the health check when
MySqlEntityFrameworkCoreSettings.DisableHealthChecksisfalse, which verifies that a connection can be made and commands can be run against the MySQL database. - Integrates with the
/healthHTTP endpoint, which specifies all registered health checks must pass for the 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, which are sometimes known as the pillars of observability. Telemetry features can be disabled using the techniques presented in the Configuration section.
Logging
Section titled “Logging”The Aspire MySQL EF Core client 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 MySQL EF Core client integration emits the following tracing activities using OpenTelemetry:
MySqlConnector
Metrics
Section titled “Metrics”The Aspire MySQL EF Core integration emits the following metrics using OpenTelemetry:
OpenTelemetry.Instrumentation.EntityFrameworkCore