콘텐츠로 이동
Docs Try Aspire
Docs Try

Connect to Azure Cosmos DB with EF Core

이 콘텐츠는 아직 번역되지 않았습니다.

Azure Cosmos DB logo

This page describes how C# consuming apps connect to an Azure Cosmos DB resource using Entity Framework Core. For the AppHost API surface — adding a Cosmos DB account, databases, containers, the emulator, and more — see Set up Azure Cosmos DB in the AppHost (EF Core).

Add the Aspire EF Core Azure Cosmos DB client integration to your C# consuming app to register a DbContext through dependency injection with automatic health checks and telemetry.

Install the 📦 Aspire.Microsoft.EntityFrameworkCore.Cosmos NuGet package in the client-consuming project:

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

In Program.cs, call AddCosmosDbContext on your IHostApplicationBuilder to register a DbContext for use via the dependency injection container:

C# — Program.cs
builder.AddCosmosDbContext<MyDbContext>("cosmosdb", "databaseName");

Alternatively, the database name can be inferred from the connection when there is a single database in the connection string:

C# — Program.cs
builder.AddCosmosDbContext<MyDbContext>("cosmosdb");

Resolve the DbContext through dependency injection:

C# — ExampleService.cs
public class ExampleService(MyDbContext context)
{
// Use context to interact with Cosmos DB...
}

For more information on using Entity Framework Core with Azure Cosmos DB, see the EF Core Azure Cosmos DB provider documentation.

To register multiple DbContext instances with different connection names, use AddKeyedCosmosDbContext:

C# — Program.cs
builder.AddKeyedCosmosDbContext<CatalogDbContext>(name: "catalog", databaseName: "catalogdb");
builder.AddKeyedCosmosDbContext<OrdersDbContext>(name: "orders", databaseName: "ordersdb");

Then resolve each instance by key:

C# — ExampleService.cs
public class ExampleService(
[FromKeyedServices("catalog")] CatalogDbContext catalogContext,
[FromKeyedServices("orders")] OrdersDbContext ordersContext)
{
// Use contexts...
}

Aspire exposes each Cosmos DB resource property as an environment variable named [RESOURCE]_[PROPERTY]. The EF Core client integration reads these automatically from the resource name you pass to AddCosmosDbContext.

Property NameEnvironment VariableDescription
ConnectionString[RESOURCE]_CONNECTIONSTRINGThe account endpoint URI. When access key authentication is enabled, also includes AccountKey={key};.
AccountKey[RESOURCE]_ACCOUNTKEYThe account key (only available when running the emulator or when access key authentication is enabled).

Inherits Cosmos DB account properties, plus:

Property NameEnvironment VariableDescription
DatabaseName[RESOURCE]_DATABASENAMEThe name of the database.

Inherits Cosmos DB database properties, plus:

Property NameEnvironment VariableDescription
ContainerName[RESOURCE]_CONTAINERNAMEThe name of the container.

The Aspire EF Core Azure Cosmos DB integration offers multiple ways to provide configuration.

When using a connection string from the ConnectionStrings configuration section, pass the connection name to AddCosmosDbContext:

C# — Program.cs
builder.AddCosmosDbContext<MyDbContext>("CosmosConnection");

The connection string is resolved from the ConnectionStrings section:

JSON — appsettings.json
{
"ConnectionStrings": {
"CosmosConnection": "AccountEndpoint=https://{account_name}.documents.azure.com:443/;AccountKey={account_key};"
}
}

For more information, see the ConnectionString documentation.

The integration supports Microsoft.Extensions.Configuration. It loads EntityFrameworkCoreCosmosSettings from appsettings.json (or any other configuration source) by using the Aspire:Microsoft:EntityFrameworkCore:Cosmos key:

JSON — appsettings.json
{
"Aspire": {
"Microsoft": {
"EntityFrameworkCore": {
"Cosmos": {
"DisableTracing": true
}
}
}
}
}

For the complete JSON schema, see Aspire.Microsoft.EntityFrameworkCore.Cosmos/ConfigurationSchema.json.

Pass an Action<EntityFrameworkCoreCosmosSettings> to configure settings inline, for example to disable tracing:

C# — Program.cs
builder.AddCosmosDbContext<MyDbContext>(
"cosmosdb",
settings => settings.DisableTracing = true);

The Aspire EF Core Azure Cosmos DB integration currently doesn’t implement health checks, though this may change in future releases.

The Aspire EF Core Azure Cosmos DB integration automatically configures logging, tracing, and metrics through OpenTelemetry.

Log categories:

  • Azure-Cosmos-Operation-Request-Diagnostics
  • Microsoft.EntityFrameworkCore.ChangeTracking
  • Microsoft.EntityFrameworkCore.Database.Command
  • Microsoft.EntityFrameworkCore.Infrastructure
  • Microsoft.EntityFrameworkCore.Query

Tracing activities:

  • Azure.Cosmos.Operation
  • OpenTelemetry.Instrumentation.EntityFrameworkCore

Metrics emitted through 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