Connect C# to Oracle with Entity Framework Core

This tutorial shows how to use Entity Framework Core to perform operations in .NET applications. With dotConnect for Oracle, we'll create EF Core models using Scaffold-DbContext and Entity Developer, build a Blazor web application, and implement CRUD operations using a robust connection class.

Why dotConnect for Oracle?

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

Banner with a link to the dotConnect for Oracle overview page

Prerequisites

  • Visual Studio 2022: Our IDE of choice. If you don't have it on your computer, go to the official website to download and install it. We'll use the Community edition, so you can get it too.
  • dotConnect for Oracle: A feature-rich ADO.NET provider with Entity Framework, NHibernate, and LinqConnect support. For installation instructions, refer to the next section.
  • Entity Developer: An ORM designer for .NET ORM frameworks with powerful code generation. For now, just download the installer.

Download and activate dotConnect for Oracle

Visit the dotConnect for Oracle download page. You can start with a free trial version, which gives you 30 days to explore all features. To continue using dotConnect for Oracle after the trial period, you can purchase its full version.

Download and install the trial version

To get the trial version, download and install dotConnect for Oracle on your computer. No license key is required for the trial, so you can start exploring the product immediately.

Purchase and access the full version

If you're ready to purchase the full version of dotConnect for Oracle, click Buy Now, add it to your cart, and complete the purchase.

Then, go to Your Licenses in the user menu. Locate your dotConnect for Oracle license in the list and click Details next to it. On the page that opens, you can find your license details, including the activation key.

Your Licenses page with purchased products
Download the full version

Click Download Product Versions to view the list of available product versions. Select the most recent version and download the installer.

Available versions of dotConnect for Oracle

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

Create a Blazor Web App project

1. Open Visual Studio and select Create a new project. In the search box, enter Blazor Web App, select the corresponding search result, and click Next.

2. Give your project a name. For this tutorial, let it be Oracle_EF_Core.

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

4. To install dotConnect for Oracle in your project, go to Tools, point to NuGet Package Manager, and select Manage NuGet Packages for Solution.

Expanded Tools menu in Visual Studio

5. Click Browse and search for Devart.Data.Oracle.EFCore. Select the matching result, then select your project, and click Install.

Package Manager with a selected search result to be installed

6. Run the application by pressing F5 to open the scaffolded webpage.

Create an EF Core model

Once you have configured the database, you can move on to the next step—creating an EF Core model. You can do this in two ways: using Scaffold-DbContext or via Entity Developer.

Create an EF Core model using Scaffold-DbContext

1. Ensure the EF Core Tools are installed in your development environment. To install them globally, run this command in the .NET command-line interface (CLI):

dotnet tool install --global dotnet-ef

2. Install Scaffold-DbContext using the Package Manager Console. For this, in Visual Studio, go to Tools > NuGet Package Manager > Package Manager Console and run this command:

Install-Package Microsoft.EntityFrameworkCore.Tools
Package Manager Console with the entered command

3. When the package is installed, you can use Scaffold-DbContext to generate DbContext and entity classes for your Oracle database. Run the following command in the Package Manager Console, replacing values with your actual credentials:

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

After you execute this command, the ModelContext file and the Models folder containing the table entity classes get generated. You should see them in the Solution Explorer. This means our migration has been applied, and the Actor table has been created.

Opened ModelContext file and Solution Explorer showing created files

Create an EF Core model via Entity Developer

1. Before installing Entity Developer, close your Visual Studio instance.

2. Install Entity Developer following the on-screen instructions.

3. Open the Oracle_EF_Core project in Visual Studio again.

4. Right-click the Oracle_EF_Core project in the Solution Explorer and select Add > New Item.

Opened shortcut menu for the project

5. Go to Installed > C# > ASP.NET Core > Data, select Devart EF Core Model, and click Add.

Add New Item dialog with a new model to be created

6. In the Create Model Wizard, select Database First and click Next.

Create Model Wizard showing two creation options

7. Fill in the details of your Oracle database connection and click Next.

Set up data connection properties page of the Create Model Wizard

8. Select Generate From Database and click Next.

Choose Model Components page of the Create Model Wizard

9. Choose the database objects you want to scaffold. You can select all, but since we've been using the Actor table, let's select only it.

Select database objects page of the Create Model Wizard

10. Define the naming convention for the property names in the database object and click Next. We suggest keeping the default settings this time.

Set up naming rules page of the Create Model Wizard

11. On the Model properties page, change only the Target Framework field. Select .NET 8 (or a different framework your project uses) and click Next.

Model properties page of the Create Model Wizard

12. Choose the model diagram contents. You can use all entities, split the entities by database, or do a custom selection. For this tutorial, select All Entities and click Next.

Choose Model Diagram Contents page of the Create Model Wizard

13. Choose code generation templates for your objects. You can define different parameters you want the object to follow. Let's use the default settings for this tutorial. Click Next.

Choose Code Generation Templates page of the Create Model Wizard

Your model is ready now.

14. Clear the Download 'Devart.Data.Oracle.EFCore' NuGet package checkbox because we've already added this package to the project; then, click Finish.

Create Model Wizard with a message about successful creation of the model

Your created model opens.

DataModel file opened in Visual Studio

Now, move on to creating a connection class.

Create a connection class

Using the generated context, let's create the services we'll use with our database.

1. Right-click the Oracle_EF_Core project, select Add > Class, and add a class named DatabaseConnectionClass.

2. Paste this code into the created file:

public class DatabaseConnectionClass
{
    private readonly ModelContext _context;

    public DatabaseConnectionClass()
    {
        _context = new ModelContext();
    }
    public decimal AddActor(Actor actor)
    {
        actor.LastUpdate = DateTime.Now;
        _context.Actors.Add(actor);
        _context.SaveChanges();
        return actor.ActorId;
    }
    public bool DeleteActor(int Id)
    {
        var actor = _context.Actors.FirstOrDefault(a => a.ActorId == Id);
        if (actor != null)
        {
            _context.Actors.Remove(actor);
            _context.SaveChanges();
            return true;
        }
        return false;
    }

    public IEnumerable<Actor> GetActorById(int Id)
    {
        return _context.Actors.Where(a => a.ActorId == Id).ToList();
    }

    public List<Actor> GetActors()
    {
        return _context.Actors.ToList();
    }

    public Actor UpdateActor(Actor actor)
    {
        actor.LastUpdate = DateTime.Now;
        _context.Actors.Update(actor);
        _context.SaveChanges();
        return actor;
    }
}

Read data from Oracle

Let's try to read data from the database table using the implementation we've just created.

1. In the Controllers folder, add a new class named ActorsController.

2. In the created file, inside namespace Oracle_EF_Core.Controllers, add the following code:

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

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

    [HttpGet]
    public IEnumerable<Actor> GetActors()
    {
        return _context.GetActors();
    }
}
Code added to the ActorsController class in Visual Studio

3. Run your application by pressing F5.

4. Go to the GetActors endpoint, click Try it out, and then click Execute.

The query result appears in the response body.

Response to a GET request for the GetActors endpoint

Insert new data into Oracle

Next, let's try to insert a new record into the Actors table.

1. In the ActorsController class, add this piece of code:

[HttpPost]
public decimal AddActor(Actor actor)
{
    return _context.AddActor(actor);
}

This uses the helper method in DatabaseConnectionClass to insert a new record.

2. Run the application again. We can see that the new endpoint—AddActor—has appeared.

3. Click the expander arrow and add this JSON object to the request body:

{
    "actorId": 201,
    "firstName": "John",
    "lastName": "Lewis",
    "filmActors": []
}

4. Click Execute.

JSON object added to the body of a POST request for the AddActor endpoint

The response should be the ID you assigned to the added data.

Response to a POST request for the AddActor endpoint

Update Oracle data

Imagine that John Lewis has decided to change his surname. Let's update the data.

1. In the ActorController class, add the following method:

[HttpPut]
public Actor UpdateActor(Actor actor)
{
    return _context.UpdateActor(actor);
}

This uses the helper method in DatabaseConnectionClass to update a particular record.

2. Run the application, select UpdateActor, and add this JSON object to the request body:

{
    "actorId":201,
    "firstName": "John",
    "lastName": "Mcginnis",
    "filmActors": []
}

3. Click Execute.

JSON object added to the body of a PUT request for the UpdateActor endpoint

In the response body, you'll see the record with the updated last name.

Response to a PUT request for the UpdateActor endpoint

Delete data from Oracle

Assume that John has left the acting business. Let's delete his record from the table.

1. Add these two methods to the ActorController class:

[HttpDelete("{Id}")]
public bool DeleteActor(int Id)
{
    return _context.DeleteActor(Id);
}
[HttpGet("{Id}")]
public IEnumerable<Actor> GetActorsById(int Id)
{
    return _context.GetActorById(Id);
}

The DeleteActor method will delete a row from the table and return true if the request is successful. If no record for that particular ID exists or an error occurs, it'll return false.

The GetActorsById method will verify the actor no longer exists.

2. Run the application, select the DeleteActor endpoint, and enter the ID of the previously created record.

3. Click Execute.

Response to a DELETE request for the DeleteActor endpoint

This should return true, and the record gets removed.

4. To verify this, try to get the record with that ID using the GetActorsById endpoint.

Executed GET request for the GetActorsById endpoint

The request returns an empty array, which means the record no longer exists.

Conclusion

In this tutorial, we've demonstrated how integrating Entity Framework Core with Oracle with the help of dotConnect for Oracle streamlines data operations in .NET applications. The rich features of dotConnect for Oracle, combined with the simplicity of Entity Framework Core, provide a powerful and efficient way to handle database interactions in Oracle-powered applications. With these tools and techniques, you can confidently build scalable and maintainable .NET solutions that leverage Oracle databases.

dotConnect for Oracle

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