Salta ai contenuti

Aspire Oracle Entity Framework Core integration

Questi contenuti non sono ancora disponibili nella tua lingua.

Oracle Database logo

Oracle Database is a widely-used relational database management system owned and developed by Oracle. The Aspire Oracle Entity Framework Core integration enables you to connect to existing Oracle servers or create new servers from the Aspire AppHost.

The Aspire Oracle hosting integration models the server as the OracleDatabaseServerResource type and the database as the OracleDatabaseResource type. To access these types and APIs, add the 📦 Aspire.Oracle.EntityFrameworkCore NuGet package in the AppHost project.

Aspire CLI — Aggiungi pacchetto Aspire.Oracle.EntityFrameworkCore
aspire add aspire-oracle-entityframeworkcore

La CLI Aspire è interattiva; seleziona il risultato corretto quando richiesto:

Aspire CLI — Output di esempio
Select an integration to add:
> aspire-oracle-entityframeworkcore (Aspire.Oracle.EntityFrameworkCore)
> Other results listed as selectable options...

In your AppHost project, call AddOracle to add and return an Oracle server resource builder. Chain a call to the returned resource builder to AddDatabase, to add an Oracle database to the server resource:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var oracle = builder.AddOracle("oracle")
.WithLifetime(ContainerLifetime.Persistent);
var oracledb = oracle.AddDatabase("oracledb");
builder.AddProject<Projects.ExampleProject>()
.WithReference(oracledb);
.WaitFor(oracledb);
// After adding all resources, run the app...

When Aspire adds a container image to the AppHost, as shown in the preceding example with the container-registry.oracle.com/database/free image, it creates a new Oracle server on your local machine. A reference to your Oracle resource builder (the oracle variable) is used to add a database. The database is named oracledb and then added to the ExampleProject. The Oracle resource includes a random password generated using the CreateDefaultPasswordParameter method.

The WithReference method configures a connection in the ExampleProject named "oracledb".md#container-resource-lifecycle).

Add Oracle resource with password parameter

Section titled “Add Oracle resource with password parameter”

The Oracle resource includes default credentials with a random password. Oracle supports configuration-based default passwords by using the environment variable ORACLE_PWD. When you want to provide a password explicitly, you can provide it as a parameter:

C# — AppHost.cs
var password = builder.AddParameter("password", secret: true);
var oracle = builder.AddOracle("oracle", password)
.WithLifetime(ContainerLifetime.Persistent);
var oracledb = oracle.AddDatabase("oracledb");
var myService = builder.AddProject<Projects.ExampleProject>()
.WithReference(oracledb)
.WaitFor(oracledb);

The preceding code gets a parameter to pass to the AddOracle API, and internally assigns the parameter to the ORACLE_PWD environment variable of the Oracle container. The password parameter is usually specified as a user secret:

~/.microsoft/usersecrets/<user_secrets_id>/secrets.json
{
"Parameters": {
"password": "Non-default-P@ssw0rd"
}
}

To add a data volume to the Oracle resource, call the WithDataVolume method:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var oracle = builder.AddOracle("oracle")
.WithDataVolume()
.WithLifetime(ContainerLifetime.Persistent);
var oracledb = oracle.AddDatabase("oracle");
builder.AddProject<Projects.ExampleProject>()
.WithReference(oracledb)
.WaitFor(oracledb);
// After adding all resources, run the app...

The data volume is used to persist the Oracle data outside the lifecycle of its container. The data volume is mounted at the /opt/oracle/oradata path in the Oracle container and when a name parameter isn’t provided, the name is generated at random. For more information on data volumes and details on why they’re preferred over bind mounts, see Docker docs: Volumes.

To add a data bind mount to the Oracle resource, call the WithDataBindMount method:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var oracle = builder.AddOracle("oracle")
.WithDataBindMount(source: @"C:\Oracle\Data");
var oracledb = oracle.AddDatabase("oracledb");
builder.AddProject<Projects.ExampleProject>()
.WithReference(oracledb)
.WaitFor(oracledb);
// After adding all resources, run the app...

Data bind mounts rely on the host machine’s filesystem to persist the Oracle data across container restarts. The data bind mount is mounted at the C:\Oracle\Data on Windows (or /Oracle/Data on Unix) path on the host machine in the Oracle container. For more information on data bind mounts, see Docker docs: Bind mounts.

The Oracle hosting integration automatically adds a health check for the Oracle resource. The health check verifies that the Oracle server is running and that a connection can be established to it.

The hosting integration relies on the 📦 AspNetCore.HealthChecks.Oracle NuGet package.

You need an Oracle database and connection string for accessing the database. To get started with the Aspire Oracle client integration, install the 📦 Aspire.Oracle.EntityFrameworkCore NuGet package in the client-consuming project, that is, the project for the application that uses the Oracle client. The Oracle client integration registers a System.Data.Entity.DbContext instance that you can use to interact with Oracle.

.NET CLI — Add Aspire.Oracle.EntityFrameworkCore package
dotnet add package Aspire.Oracle.EntityFrameworkCore

In the Program.cs file of your client-consuming project, call the AddOracleDatabaseDbContext extension method on any IHostApplicationBuilder to register a DbContext for use via the dependency injection container. The method takes a connection name parameter.

builder.AddOracleDatabaseDbContext<ExampleDbContext>(
connectionName: "oracledb");

You can then retrieve the DbContext instance using dependency injection. For example, to retrieve the connection from an example service:

public class ExampleService(ExampleDbContext context)
{
// Use database context...
}

For more information on dependency injection, see .NET dependency injection.

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.UseOracle(builder.Configuration.GetConnectionString("oracledb")
?? throw new InvalidOperationException("Connection string 'oracledb' not found.")));

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 EnrichOracleDatabaseDbContext method:

builder.EnrichOracleDatabaseDbContext<ExampleDbContext>(
configureSettings: settings =>
{
settings.DisableRetry = false;
settings.CommandTimeout = 30 // seconds
});

The settings parameter is an instance of the OracleEntityFrameworkCoreSettings class.

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

When using a connection string from the ConnectionStrings configuration section, you provide the name of the connection string when calling builder.AddOracleDatabaseDbContext<TContext>():

builder.AddOracleDatabaseDbContext<ExampleDbContext>("oracleConnection");

The connection string is retrieved from the ConnectionStrings configuration section:

{
"ConnectionStrings": {
"oracleConnection": "Data Source=TORCL;User Id=OracleUser;Password=Non-default-P@ssw0rd;"
}
}

The EnrichOracleDatabaseDbContext won’t make use of the ConnectionStrings configuration section since it expects a DbContext to be registered at the point it is called.

For more information, see the ODP.NET documentation.

The Aspire Oracle Entity Framework Core integration supports Microsoft.Extensions.Configuration from configuration files such as appsettings.json by using the Aspire:Oracle:EntityFrameworkCore key. If you have set up your configurations in the Aspire:Oracle:EntityFrameworkCore section you can just call the method without passing any parameter.

The following is an example of an appsettings.json that configures some of the available options:

JSON — appsettings.json
{
"Aspire": {
"Oracle": {
"EntityFrameworkCore": {
"DisableHealthChecks": true,
"DisableTracing": true,
"DisableRetry": false,
"CommandTimeout": 30
}
}
}
}

You can also pass the Action<OracleEntityFrameworkCoreSettings> delegate to set up some or all the options inline, for example to disable health checks from code:

builder.AddOracleDatabaseDbContext<ExampleDbContext>(
"oracle",
static settings => settings.DisableHealthChecks = true);

— or —

builder.EnrichOracleDatabaseDbContext<ExampleDbContext>(
static settings => settings.DisableHealthChecks = true);

Here are the configurable options with corresponding default values:

NameDescription
ConnectionStringThe connection string of the Oracle database to connect to.
DisableHealthChecksA boolean value that indicates whether the database health check is disabled or not.
DisableTracingA boolean value that indicates whether the OpenTelemetry tracing is disabled or not.
DisableRetryA boolean value that indicates whether command retries should be disabled or not.
CommandTimeoutThe time in seconds to wait for the command to execute.

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

  • Checks if the 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.

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

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

  • OpenTelemetry.Instrumentation.EntityFrameworkCore

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

  • Microsoft.EntityFrameworkCore
Domande & RisposteCollaboraCommunityDiscuteGuarda