Connect to Azure Cosmos DB with EF Core
이 콘텐츠는 아직 번역되지 않았습니다.
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).
Connect from your app
Section titled “Connect from your app”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 client integration
Section titled “Install the client integration”Install the 📦 Aspire.Microsoft.EntityFrameworkCore.Cosmos NuGet package in the client-consuming project:
dotnet add package Aspire.Microsoft.EntityFrameworkCore.Cosmos#:package Aspire.Microsoft.EntityFrameworkCore.Cosmos@*<PackageReference Include="Aspire.Microsoft.EntityFrameworkCore.Cosmos" Version="*" />Add Cosmos DB context
Section titled “Add Cosmos DB context”In Program.cs, call AddCosmosDbContext on your IHostApplicationBuilder to register a DbContext for use via the dependency injection container:
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:
builder.AddCosmosDbContext<MyDbContext>("cosmosdb");Resolve the DbContext through dependency injection:
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.
Add keyed Cosmos DB contexts
Section titled “Add keyed Cosmos DB contexts”To register multiple DbContext instances with different connection names, use AddKeyedCosmosDbContext:
builder.AddKeyedCosmosDbContext<CatalogDbContext>(name: "catalog", databaseName: "catalogdb");builder.AddKeyedCosmosDbContext<OrdersDbContext>(name: "orders", databaseName: "ordersdb");Then resolve each instance by key:
public class ExampleService( [FromKeyedServices("catalog")] CatalogDbContext catalogContext, [FromKeyedServices("orders")] OrdersDbContext ordersContext){ // Use contexts...}Connection properties
Section titled “Connection properties”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.
Cosmos DB account
Section titled “Cosmos DB account”| Property Name | Environment Variable | Description |
|---|---|---|
ConnectionString | [RESOURCE]_CONNECTIONSTRING | The account endpoint URI. When access key authentication is enabled, also includes AccountKey={key};. |
AccountKey | [RESOURCE]_ACCOUNTKEY | The account key (only available when running the emulator or when access key authentication is enabled). |
Cosmos DB database
Section titled “Cosmos DB database”Inherits Cosmos DB account properties, plus:
| Property Name | Environment Variable | Description |
|---|---|---|
DatabaseName | [RESOURCE]_DATABASENAME | The name of the database. |
Cosmos DB container
Section titled “Cosmos DB container”Inherits Cosmos DB database properties, plus:
| Property Name | Environment Variable | Description |
|---|---|---|
ContainerName | [RESOURCE]_CONTAINERNAME | The name of the container. |
Configuration
Section titled “Configuration”The Aspire EF Core Azure Cosmos DB integration offers multiple ways to provide configuration.
Use a connection string
Section titled “Use a connection string”When using a connection string from the ConnectionStrings configuration section, pass the connection name to AddCosmosDbContext:
builder.AddCosmosDbContext<MyDbContext>("CosmosConnection");The connection string is resolved from the ConnectionStrings section:
{ "ConnectionStrings": { "CosmosConnection": "AccountEndpoint=https://{account_name}.documents.azure.com:443/;AccountKey={account_key};" }}For more information, see the ConnectionString documentation.
Use configuration providers
Section titled “Use configuration providers”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:
{ "Aspire": { "Microsoft": { "EntityFrameworkCore": { "Cosmos": { "DisableTracing": true } } } }}For the complete JSON schema, see Aspire.Microsoft.EntityFrameworkCore.Cosmos/ConfigurationSchema.json.
Use inline delegates
Section titled “Use inline delegates”Pass an Action<EntityFrameworkCoreCosmosSettings> to configure settings inline, for example to disable tracing:
builder.AddCosmosDbContext<MyDbContext>( "cosmosdb", settings => settings.DisableTracing = true);Client integration health checks
Section titled “Client integration health checks”The Aspire EF Core Azure Cosmos DB integration currently doesn’t implement health checks, though this may change in future releases.
Observability and telemetry
Section titled “Observability and telemetry”The Aspire EF Core Azure Cosmos DB integration automatically configures logging, tracing, and metrics through OpenTelemetry.
Logging
Section titled “Logging”Log categories:
Azure-Cosmos-Operation-Request-DiagnosticsMicrosoft.EntityFrameworkCore.ChangeTrackingMicrosoft.EntityFrameworkCore.Database.CommandMicrosoft.EntityFrameworkCore.InfrastructureMicrosoft.EntityFrameworkCore.Query
Tracing
Section titled “Tracing”Tracing activities:
Azure.Cosmos.OperationOpenTelemetry.Instrumentation.EntityFrameworkCore
Metrics
Section titled “Metrics”Metrics emitted through OpenTelemetry:
Microsoft.EntityFrameworkCoreec_Microsoft_EntityFrameworkCore_active_db_contextsec_Microsoft_EntityFrameworkCore_total_queriesec_Microsoft_EntityFrameworkCore_queries_per_secondec_Microsoft_EntityFrameworkCore_total_save_changesec_Microsoft_EntityFrameworkCore_save_changes_per_secondec_Microsoft_EntityFrameworkCore_compiled_query_cache_hit_rateec_Microsoft_Entity_total_execution_strategy_operation_failuresec_Microsoft_E_execution_strategy_operation_failures_per_secondec_Microsoft_EntityFramew_total_optimistic_concurrency_failuresec_Microsoft_EntityF_optimistic_concurrency_failures_per_second