How to Connect to Oracle in .NET with C#

This tutorial provides a deep dive into connecting a .NET application to an Oracle database.

We're going to use Oracle Database, a powerful and feature-rich relational database management system renowned for its scalability, performance, and robust security features. As a leading choice for enterprise-level applications, Oracle Database is ideal for critical business solutions as it supports high transaction volumes and large datasets. Its advanced capabilities, such as Real Application Clusters (RAC) and comprehensive data management tools, ensure high availability and reliability.

Why choose dotConnect for Oracle?

dotConnect for Oracle is an ideal data provider for all Oracle-related operations. It offers on-the-fly connector creation, flexible configuration, seamless integration into Visual Studio, and enhanced ORM support.

Download Now dotConnect for Oracle

Requirements

  • Visual Studio 2022: The IDE of choice. Download and install it if you don't have it. We're going to use the community version, so you can get it as well.
  • dotConnect for Oracle: A feature-rich ADO.NET provider with Entity Framework, NHibernate, and LinqConnect support.
  • Entity Developer: An ORM designer for .NET ORM Frameworks with powerful code generation.
  • Sakila database: A sample database for learning and testing. Download the folder and unzip the file to use it.

Download and activate dotConnect for Oracle

For the trial version, simply download and install dotConnect for Oracle on your machine. No license key is required and you can start exploring the product immediately.

Purchase and access the full Version

After purchasing the full version, go to your profile's Licenses page. You'll find a list of your licenses, including dotConnect for Oracle purchase.

Click Details next to your dotConnect for Oracle license. Here, you'll find the license details and the Activation Key.

Purchase and access the full Version

Download the full version

To access the list of available product versions, click Download Product Versions. Select the most recent version and download the installer.

Download the full version

Execute the downloaded file and follow the on-screen instructions to install dotConnect for Oracle on your machine. This process will install the software and activate all features associated with your license key.

Create a project

The first step is to configure a new .NET Application project.

1. In Visual Studio, click Create New Project. In the Search Template field, type ASP.NET Core Web Application and click the corresponding search result.

2. Name your project. For example, ours is called Oracle_ASP.NET.

3. Select .NET 8 as the target framework and click Create.

4. Install dotConnect for Oracle in the project. To do that, navigate to Tools > NuGet Package Manager > Manage NuGet Packages for Solution.

NuGet Package Manager

5. The NuGet Package Manager page opens. Click Browse and search for Devart.Data.Oracle. Then, select your project and
click Install.

Select the project

6. To open the scaffolded web page, run the application by pressing F5.

Create a connection class

A connection class is required to simulate a link between our application and an Oracle database. To create the class, right-click the project, point to Add, and select Class. After that, name the class, for example, DatabaseConnectionClass.

In this tutorial, we'll use the Actor table from the oracle-sakila-db schema, which is seeded into the test database. The table has the following schema:

| ACTOR_ID: number(22)
| FIRST_NAME: varchar(45)
| LAST_NAME: varchar(45)
| LAST_UPDATE: timestamp

We can create the class based on this information. To add the Actor.cs class, right-click the solution again, and paste this code to the created class:

public class Actor
    {
        public int ActorId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime LastUpdate { get; set; }
    }

Connect in Direct mode

To add a method to DatabaseConnectionClass, insert this code into the class:

public static DataTable GetActorTableDirectModes()
 {
     try
     {
         OracleConnectionStringBuilder oraCSB = new OracleConnectionStringBuilder();
         oraCSB.Direct = true;
         oraCSB.Server = "127.0.0.1";
         oraCSB.Port = 1521;
         oraCSB.ServiceName = "XE";
         oraCSB.UserId = "TestUser";
         oraCSB.Password = "TestPassword";
         oraCSB.LicenseKey = "**********";
         DataTable table;
         using (var myConnection = new OracleConnection(oraCSB.ConnectionString))
         {
             myConnection.Open();
             string query = "SELECT * FROM actor WHERE ROWNUM <= 10";
             OracleDataAdapter adapter = new OracleDataAdapter(query, myConnection);
             DataSet dataSet = new DataSet();
             adapter.Fill(dataSet, "actor");
             table = dataSet.Tables["actor"];
             myConnection.Close();
         }
         return table;
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
         return null;
     }
 }

Don't forget to use Devart.Data.Oracle at the top of your file. Adjust Oracle connection strings to your credentials.

Connect using SSL/TLS

You can also connect to an Oracle database with the help of an SSL/TLS connection. This code will show you how:

public static DataTable GetActorTableUsingSSL()
{
    try
    {
        DataTable table = new DataTable();
        Devart.Data.Oracle.OracleConnectionStringBuilder oraCSB = new Devart.Data.Oracle.OracleConnectionStringBuilder();
        oraCSB.Server = "127.0.0.1";
        oraCSB.Port = 1521;
        oraCSB.ServiceName = "XE";
        oraCSB.UserId = "TestUser";
        oraCSB.Password = "TestPassword";
        oraCSB.MaxPoolSize = 150;
        oraCSB.ConnectionTimeout = 30;
        oraCSB.SslKey = "/server.key";
        oraCSB.SslCert = "/server.crt";
        oraCSB.LicenseKey = "**********";
        OracleConnection myConnection = new OracleConnection(oraCSB.ConnectionString);

        OracleCommand command = new Devart.Data.Oracle.OracleCommand("SELECT * FROM actor WHERE ROWNUM <= 10;", myConnection);
        myConnection.Open();
        using (OracleDataReader reader = command.ExecuteReader())
        {
            table.Load(reader);
        }
        myConnection.Close();
        return table;
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
        return null;
    }
}

Connect via SSH

Alternatively, it's possible to connect via SSH. This code can assist with that:

public static DataTable GetActorTableUsingSSH()
{
	try
	{
    	DataTable table = new DataTable();
    	OracleConnection myConnection = new OracleConnection("" +
        	"Direct=True;" +
        	"Host=ssh://127.0.0.1;" +
        	"Port=1521;" +
        	"ServiceName=XE;" +
        	"UserID=TestUser;" +
        	"Password=TestPassword;" +
        	"LicenseKey=**********"
        	);
    	myConnection.SshOptions.AuthenticationType = Devart.Data.Oracle.SshAuthenticationType.Password;
    	myConnection.SshOptions.Host = "OracleSSH";
    	myConnection.SshOptions.User = "sshUser";
    	myConnection.SshOptions.Password = "sshPassword";
    	OracleCommand command = new Devart.Data.Oracle.OracleCommand("SELECT * FROM actor WHERE ROWNUM <= 10", myConnection);
    	myConnection.Open();
    	using (OracleDataReader reader = command.ExecuteReader())
    	{
        	table.Load(reader);
    	}
    	myConnection.Close();
    	return table;
	}
	catch (Exception ex)
	{
    	Console.WriteLine(ex.Message);
    	return null;
	}
}

Connect with the help of a proxy

Proxy authentication allows middle-tier applications to control security by preserving database user identities and privileges. Oracle enables the creation of a proxy database user, which connects and authenticates against the database on behalf of database users. Proxy authentication is not supported in Direct mode. Here's an example using our code:

public static DataTable GetDataActorProxy()
{
	try
	{
    	DataTable table;
    	using (OracleConnection proxyConnection = new
            	OracleConnection("" +
            	"Host=127.0.0.1;" +
            	"Port=1521;" +
            	"ServiceName=XE;" +
            	"UserId=TestUser;" +
            	"ProxyUserId=ProxyUser;" +
            	"ProxyPassword=ProxyPassword;" +
            	"LicenseKey=**********"
            	))
    	{
        	proxyConnection.Open();

        	string query = "SELECT * FROM actor WHERE ROWNUM <= 10";
        	OracleDataAdapter adapter = new OracleDataAdapter(query, proxyConnection);
        	DataSet dataSet = new DataSet();
        	adapter.Fill(dataSet, "actor");
        	table = dataSet.Tables["actor"];
        	proxyConnection.Close();
    	}
    	return table;
	}
	catch (Exception ex)
	{
    	Console.WriteLine(ex.Message);
    	return null;
	}
}

Connect using the OracleCredential class

The OracleCredential class allows providing a password for connecting to Oracle more securely than specifying it in plain text in a connection string or assigning the System.String instance to the OracleConnection.Password property. The class uses the SecureString class to store and specify the password. Here's an example:

public static DataTable GetDataActorOracleCredential(string userName, SecureString securePwd)
{
	try
	{
    	string connectionString = "" +
        	"Host=127.0.0.1;" +
        	"Port=1521;" +
        	"ServiceName=XE;" +
        	"UserId=TestUser;" +
        	"Password=TestPassword;" +
        	"LicenseKey=**********";
    	DataTable table;
    	using (var connection = new OracleConnection(connectionString))
    	{
        	connection.Open();
        	connection.Credential = new OracleCredential(userName, securePwd);
        	string query = "SELECT * FROM actor WHERE ROWNUM <= 10";
        	OracleDataAdapter adapter = new OracleDataAdapter(query, connection);
        	DataSet dataSet = new DataSet();
        	adapter.Fill(dataSet, "actor");
        	table = dataSet.Tables["actor"];
        	connection.Close();
    	}
    	return table;
	}
	catch (Exception ex)
	{
    	Console.WriteLine(ex.Message);
    	return null;
	}
}

Connect using the Unicode property

You can also use Unicode connection strings to ensure that the data retrieved from and sent to an Oracle database is in Unicode format, which supports a wide range of characters. Here's an example:

public static DataTable GetDataActorUnicode()
{
	try
	{
    	string connectionString = "" +
        	"Host=127.0.0.1;" +
        	"Port=1521;" +
        	"ServiceName=XE;" +
        	"UserId=TestUser;" +
        	"Password=TestPassword;";
    	DataTable table;
    	using (var connection = new OracleConnection(connectionString))
    	{
        	connection.Open();
        	connection.Unicode = true;
        	string query = "SELECT * FROM actor WHERE ROWNUM <= 10";
        	OracleDataAdapter adapter = new OracleDataAdapter(query, connection);
        	DataSet dataSet = new DataSet();
        	adapter.Fill(dataSet, "actor");
        	table = dataSet.Tables["actor"];
        	connection.Close();
    	}
    	return table;
	}
	catch (Exception ex)
	{
    	Console.WriteLine(ex.Message);
    	return null;
	}
}

You can then choose the connection mode that best suits your use case.

Test the project

It's necessary to be able to visualize the returned data. In Solution Explorer, click Controllers, select Add New Class, and add the ActorsController class. In the Oracle_ASP.NET_ASP.NET.Controllers namespace, modify the class using this code:

[ApiController]
[Route("api/[controller]/[action]")]
public class ActorsController : ControllerBase
{
    [HttpGet]
    public IEnumerable GetActors()
    {
        List actorList = new();
        DataTable dataTable = DatabaseConnectionClass.GetActorTableDirectModes();

        foreach (DataRow row in dataTable.Rows)
        {
            Actor obj = new Actor
            {
                ActorId = Convert.ToInt32(row["actor_id"]),
                FirstName = Convert.ToString(row["first_name"]),
                LastName = Convert.ToString(row["last_name"]),
                LastUpdate = Convert.ToDateTime(row["last_update"])
            };
            actorList.Add(obj);
        }

        return actorList;
    }
}

When you run the project, click the drop-down for GetActors, select Try it now, and then click Execute. After that, the desired list will be displayed:

Desired list

Great! We have successfully established the connection to the Oracle database.

Connect with EF Core using Scaffold-DbContext

Now, connect the .NET application to the Oracle database via EF Core. Let's see how to implement it using dotConnect for Oracle.

First, add a separate project to the solution to illustrate the case. To do this, right-click the current Oracle_ASP.NET solution in the Visual Studio Solution Explorer and go to Add > New project. In our case, this additional project is called Oracle_EF_Core_ASP.NET, and we added it in the same way as we did at the beginning of this tutorial. Right-click it and set it as a startup project.

Then, ensure that you have the EF Core tools installed in your development environment. You can install them globally using the .NET CLI from the command line:

dotnet tool install --global dotnet-ef

Next, open NuGet Package Manager for the project in Visual Studio, select Devart.Data.Oracle.EFCore, and click Install.

Select the project

To install Scaffold-DbContext via the Package Manager Console, navigate to Tools > Package Manager Console and select Oracle_EF_Core_ASP.NET as the project. When the console opens, execute the following command:

Install-Package Microsoft.EntityFrameworkCore.Tools

Install the package

Once installed, you can use Scaffold-DbContext to create the Models folder and generate DbContext and entity classes for the Oracle database. Execute the following command from the Package Manager Console:

Scaffold-DbContext
"DataSource=127.0.0.1;Port:1521;ServiceName=XE;UserId=TestUser;Password=
TestPassword;LicenseKey=your_license_key;" -provider 
Devart.Data.Oracle.Entity.EFCore -OutputDir Models 

Remember to provide the relevant credentials for your password. After that, dbContext will be renamed to ModelContext, and the entity classes in the table should be generated. They will be available in Solution Explorer.

ModelContext

Let's use the Actors class again. We'll query this entity table using LINQ. Right-click the Oracle_EF_Core_ASP.NET project, select the option to add a class, and add DatabaseConnectionClass as we did earlier. Then, paste this code into the class:

public class DatabaseConnectionClass
{
    private readonly ModelContext _context;

    public DatabaseConnectionClass()
    {
        _context = new ModelContext();
    }

    public List GetActors()
    {
        return _context.Actors.Take(10).ToList();
    }
}

We used ModelContext to retrieve the entity of actors and returned it as a list. Like before, we need a way to visualize the data, so add a new class called ActorsController into the Controllers folder. Modify the class with the code below in the Oracle_EF_Core_ASP.NET.Controllers namespace:

 [ApiController]
    [Route("api/[controller]/[action]")]
    public class ActorsController : ControllerBase
    {
        private readonly DatabaseConnectionClass _context;

        public ActorsController()
        {
            _context = new DatabaseConnectionClass();
        }

        [HttpGet]
        public IEnumerable GetActors()
        {
            return _context.GetActors();
        }
    }

ActorsController

Run the application by pressing F5, go to the GetActors endpoint, click Try it out, and then Execute. You will see the query results in the response body, as shown previously.

ActorsController

If you want to learn more about working with EF Core, refer to the Entity Framework documentation, which includes instructions for executing INSERT, UPDATE, and DELETE operations.

Connect using Entity Developer

Another way to create an EF Core model from the Oracle database is through Entity Developer.

Close the Visual Studio instance, then download and install Entity Developer. After that, open the Oracle_EF_Core project in Visual Studio again. Next, right-click the solution and navigate to Add > New Item.

Add a new item

Then, in the model pane, select Data and click Devart EF Core Model.

Devart EF Core Model

In the Entity Developer Model wizard, select Database First and click Next.

Database First

The Setup data connection properties window pops up. Fill in the details of your Oracle database connection.

Connection properties window

Click Next to proceed further. Then, select Generate From Database and click Next.

Generate From Database

Next, choose the database objects you want to scaffold. Since we have been using the Actors table, you can select all of them.

Select the required objects

Now, define the naming convention you want the property names in the database object to follow. We will leave it as the default and click Next.

Naming rules

On the next page, set up model properties like the namespace and entity container. The only thing that will change on this page is the Target Framework. We are using .NET 8, so choose that (or the framework your project uses) and click Next.

Model properties

After that, you will be asked to choose the contents of the Model diagram. You can use all entities, split the entities by database, or do a custom selection. For this tutorial, we will use All Entities, so select this option and click Next.

Model diagram

Then, choose code generation templates for the model. Here, you can define different parameters you want the object to follow. We will use the default settings.

Choose code generation templates for the model

After that, your model will be fully created. There is a checkbox to download Devart.Data.Oracle.EFCore, but since we have previously added it to the project, you can clear it and click Finish.

Created model

Check the created model.

Data model

Video tutorial: How to connect .NET console application to Oracle database

Conclusion

This article provides detailed guides on connecting a .NET application to Oracle databases in various ways. It explores multiple connection methods, including Direct Mode, SSH, secure SSL/TLS, and using Entity Framework Core with Scaffold-DbContext and Entity Developer

These are just a few of the things dotConnect can do for you. To experience a seamless, high-performance data connectivity solution tailored for .NET developers, download dotConnect for Oracle.

dotConnect for Oracle

Get an enhanced ORM-enabled data provider for Oracle and develop .NET applications working with Oracle data quickly and easily!