# Connect to Oracle with EF Core

<Image
  src={oracleIcon}
  alt="Oracle Database logo"
  width={100}
  height={100}
  class:list={'float-inline-left icon'}
  data-zoom-off
/>

This page describes how consuming C# apps connect to an Oracle resource that's already modeled in your AppHost. For the AppHost API surface — adding an Oracle server, databases, volumes, and more — see [Set up Oracle in the AppHost](../oracle-host/).

When you reference an Oracle database resource from your AppHost, Aspire injects the connection information into the consuming app as environment variables. In C#, use the Aspire Oracle Entity Framework Core client integration for automatic `DbContext` registration, health checks, retries, and telemetry.

## Connection properties

Aspire exposes each property as an environment variable named `[RESOURCE]_[PROPERTY]`. For instance, the `Uri` property of a resource called `oracledb` becomes `ORACLEDB_URI`.

### Oracle server

The Oracle server resource exposes the following connection properties:

| Property Name          | Description |
| ---------------------- | ----------- |
| `Host`                 | The hostname or IP address of the Oracle server |
| `Port`                 | The port number the Oracle server is listening on |
| `Username`             | The username for authentication |
| `Password`             | The password for authentication |
| `Uri`                  | The connection URI in oracle:// format, with the format `oracle://{Username}:{Password}@{Host}:{Port}` |
| `JdbcConnectionString` | JDBC-format connection string, with the format `jdbc:oracle:thin:@//{Host}:{Port}`. User and password credentials are provided as separate `Username` and `Password` properties. |

**Example connection strings:**

```
Uri: oracle://system:p%40ssw0rd1@localhost:1521
JdbcConnectionString: jdbc:oracle:thin:@//localhost:1521
```

### Oracle database

The Oracle database resource inherits all properties from its parent server resource and adds:

| Property Name          | Description |
| ---------------------- | ----------- |
| `Uri`                  | The connection URI with the database name, with the format `oracle://{Username}:{Password}@{Host}:{Port}/{DatabaseName}` |
| `JdbcConnectionString` | JDBC connection string with database name, with the format `jdbc:oracle:thin:@//{Host}:{Port}/{DatabaseName}`. User and password credentials are provided as separate `Username` and `Password` properties. |
| `DatabaseName`         | The name of the database |

**Example connection strings:**

```
Uri: oracle://system:p%40ssw0rd1@localhost:1521/FREEPDB1
JdbcConnectionString: jdbc:oracle:thin:@//localhost:1521/FREEPDB1
```

## Connect from your app

Add the Aspire Oracle EF Core client integration to your C# consuming app to register a `DbContext` for Oracle Database with automatic health checks and telemetry.

#### Install the client integration

Install the [📦 Aspire.Oracle.EntityFrameworkCore](https://www.nuget.org/packages/Aspire.Oracle.EntityFrameworkCore) NuGet package in the client-consuming project:

<InstallDotNetPackage packageName="Aspire.Oracle.EntityFrameworkCore" />

#### Add Oracle database context

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

```csharp title="C# — Program.cs"
builder.AddOracleDatabaseDbContext<ExampleDbContext>(connectionName: "oracledb");
```
**Tip:** The `connectionName` parameter must match the name used when adding the Oracle database resource in the AppHost project. For more information, see [Add Oracle server and database resources](../oracle-host/#add-oracle-server-and-database-resources).

Resolve the `DbContext` instance through dependency injection. For example, to retrieve the context from an example service:

```csharp title="C# — ExampleService.cs"
public class ExampleService(ExampleDbContext context)
{
    // Use database context...
}
```

For more information on dependency injection, see [.NET dependency injection](https://learn.microsoft.com/dotnet/core/extensions/dependency-injection).

#### Enrich Oracle database context

You may prefer to use the standard Entity Framework Core method to register a database context and then enhance it with Aspire features. Register the context first:

```csharp title="C# — Program.cs"
builder.Services.AddDbContext<ExampleDbContext>(options =>
    options.UseOracle(builder.Configuration.GetConnectionString("oracledb")
        ?? throw new InvalidOperationException("Connection string 'oracledb' not found.")));
```
**Note:** The connection string name passed to `GetConnectionString` must match the name used when adding the Oracle resource in the AppHost project. For more information, see [Add Oracle server and database resources](../oracle-host/#add-oracle-server-and-database-resources).

Using this approach, you have more flexibility:

- Reuse existing `DbContext` configuration code without rewriting it for Aspire.
- Use Entity Framework Core interceptors to modify database operations.
- Choose not to use Entity Framework Core context pooling, which may perform better in some circumstances.

Then call `EnrichOracleDatabaseDbContext` to add Aspire-style retries, health checks, logging, and telemetry:

```csharp title="C# — Program.cs"
builder.EnrichOracleDatabaseDbContext<ExampleDbContext>(
    configureSettings: settings =>
    {
        settings.DisableRetry = false;
        settings.CommandTimeout = 30; // seconds
    });
```

The `settings` parameter is an instance of `OracleEntityFrameworkCoreSettings`.

#### Configuration

The Aspire Oracle Entity Framework Core integration provides multiple configuration approaches to meet the requirements and conventions of your project.

##### Use a connection string

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

```csharp title="C# — Program.cs"
builder.AddOracleDatabaseDbContext<ExampleDbContext>("oracleConnection");
```

The connection string is resolved from the `ConnectionStrings` section:

```json title="JSON — appsettings.json"
{
  "ConnectionStrings": {
    "oracleConnection": "Data Source=TORCL;User Id=OracleUser;Password=Non-default-P@ssw0rd;"
  }
}
```

The `EnrichOracleDatabaseDbContext` method won't use the `ConnectionStrings` configuration section because it expects a `DbContext` to already be registered.

For more information, see the [ODP.NET documentation](https://www.oracle.com/database/technologies/appdev/dotnet/odp.html).

##### Use configuration providers

The integration supports `Microsoft.Extensions.Configuration` from configuration files such as `appsettings.json` by using the `Aspire:Oracle:EntityFrameworkCore` key:

```json title="JSON — appsettings.json"
{
  "Aspire": {
    "Oracle": {
      "EntityFrameworkCore": {
        "DisableHealthChecks": true,
        "DisableTracing": true,
        "DisableRetry": false,
        "CommandTimeout": 30
      }
    }
  }
}
```
**Tip:** The `CommandTimeout` property is in seconds. When set as shown in the preceding example, the timeout is 30 seconds.

##### Use inline delegates

Pass an `Action<OracleEntityFrameworkCoreSettings>` to configure settings inline, for example to disable health checks:

```csharp title="C# — Program.cs"
builder.AddOracleDatabaseDbContext<ExampleDbContext>(
    "oracle",
    static settings => settings.DisableHealthChecks = true);
```

or

```csharp title="C# — Program.cs"
builder.EnrichOracleDatabaseDbContext<ExampleDbContext>(
    static settings => settings.DisableHealthChecks = true);
```

##### Configuration options

Here are the configurable options with corresponding default values:

| Name | Description |
|--|--|
| `ConnectionString` | The connection string of the Oracle 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. |
| `DisableRetry` | A boolean value that indicates whether command retries should be disabled or not. |
| `CommandTimeout` | The time in seconds to wait for the command to execute. |

#### Client integration health checks

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

By default, the Aspire Oracle Entity Framework Core integration handles the following:

- Checks if `OracleEntityFrameworkCoreSettings.DisableHealthChecks` is `true`.
- If so, adds the `DbContextHealthCheck`, which calls EF Core's `CanConnectAsync` method. The name of the health check is the name of the `TContext` type.

#### 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](#configuration) section.

##### Logging

The Aspire Oracle Entity Framework Core integration 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.Migrations`
- `Microsoft.EntityFrameworkCore.Model`
- `Microsoft.EntityFrameworkCore.Model.Validation`
- `Microsoft.EntityFrameworkCore.Query`
- `Microsoft.EntityFrameworkCore.Update`

##### Tracing

The Aspire Oracle Entity Framework Core integration emits the following tracing activities using OpenTelemetry:

- `OpenTelemetry.Instrumentation.EntityFrameworkCore`

##### Metrics

The Aspire Oracle Entity Framework Core integration currently supports the following metrics:

- `Microsoft.EntityFrameworkCore`

## See also

- [Oracle Database](https://www.oracle.com/database/)
- [Oracle Database Documentation](https://docs.oracle.com/en/database/oracle/oracle-database/index.html)
- [Entity Framework Core docs](https://learn.microsoft.com/ef/core)
- [Aspire integrations](/integrations/overview/)
- [Aspire GitHub repo](https://github.com/microsoft/aspire)