ASP.NET Core Web API With Oracle Database And Dapper

This article will focus on how to create Asp.Net Core Web API to get data from Oracle database using Dapper ORM. First thing, here we are not using SQL, because of so many articles available on Internet where mostly SQL server is using for demonstration. So, we think, let write one article where we will use Oracle as a database. To reduce the complexity of database access logic we are using Dapper ORM. So, let's move to practical demonstration.

This article will focus on how to create ASP.NET Core Web API to get the data from an Oracle database using Dapper ORM. First things first, here, we are not using SQL because there already are so many articles available on the internet that mostly use SQL Server for demonstration. So, I thought of writing an article where we will use Oracle as a database. To reduce the complexity of the database access logic, we are using Dapper ORM. So, let's move to the practical demonstration.

Create ASP.NET Core Web API Project

To create a new project in ASP.NET Core Web API, just open Visual Studio 2017 version 15.3 and we have to follow the below steps.

  1. Go to the File menu and click New >> Project.
  2. From the New Project window, first, you have to choose .NET Framework 4.6 or above versions and then, from the left panel, choose Visual C# and then .NET Core.
  3. From the right panel, choose “.NET Core Web Application” and provide the Save location where you want to save the project and click OK.
  4. From the next window which will provide you different kinds of the template, you have to choose Web API.

Now, click OK. It will take a few minutes to configure ASP.NET Core Web API project.

Setup Oracle Table and Stored Procedures

To create database and tables for this demonstration, we are using Oracle Developer Tools. It is very lightweight and flexible which helps us to work with databases smoothly.  

As per Oracle

Oracle SQL Developer is a free, integrated development environment that simplifies the development and management of Oracle Database in both traditional and Cloud deployments. SQL Developer offers complete end-to-end development of your PL/SQL applications, a worksheet for running queries and scripts, a DBA console for managing the database, a reports interface, a complete data modeling solution, and a migration platform for moving your 3rd party databases to Oracle. 

Create a database name call it "TEST_DB" and inside that create a table name as "EMPLOYEE". You can use the following syntax to create the table inside "TEST_DB" database.

  1.  CREATE TABLE "TEST_DB"."EMPLOYEE"   
  2.   (   
  3.    "ID" NUMBER(10,0) GENERATED BY DEFAULT ON NULL AS IDENTITY MINVALUE 1 MAXVALUE 9999999999999999999999999999 INCREMENT BY 1 START WITH 100 CACHE 20 NOORDER  NOCYCLE ,   
  4. "NAME" VARCHAR2(255 BYTE),   
  5. "SALARY" NUMBER(10,0),   
  6. "ADDRESS" VARCHAR2(500 BYTE)  
  7.   ) SEGMENT CREATION IMMEDIATE   
  8.  PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255   
  9. NOCOMPRESS LOGGING  
  10.  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645  
  11.  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1  
  12.  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)  
  13.  TABLESPACE "TEST_DATA" ;  

We need to add some dummy records inside the tables, so that we can directly get the data from PostMan. So, we are adding four records here as follows.

  1. Insert into TEST_DB.EMPLOYEE (ID,NAME,SALARY,ADDRESS) values (100,'Mukesh',20000,'India');  
  2. Insert into TEST_DB.EMPLOYEE (ID,NAME,SALARY,ADDRESS) values (101,'Rion',28000,'US');  
  3. Insert into TEST_DB.EMPLOYEE (ID,NAME,SALARY,ADDRESS) values (102,'Mahesh',10000,'India');  
  4. Insert into TEST_DB.EMPLOYEE (ID,NAME,SALARY,ADDRESS) values (103,'Banky',20000,'India');  

Now it's time to create one SP which will bring the list of employees records. Here we are using Cursor for returning list of data as an output parameter.

  1. CREATE OR REPLACE PROCEDURE "TEST_DB"."USP_GETEMPLOYEES" (  
  2.     EMPCURSOR OUT SYS_REFCURSOR  
  3. )  
  4. AS  
  5. Begin  
  6. Open EMPCURSOR For  
  7. SELECT ID, NAME, SALARY,ADDRESS FROM Employee;  
  8. End;  

Now we're going to create one SP which will get the individual record for an employee based on their employee id. 

  1. CREATE OR REPLACE PROCEDURE "TEST_DB"."USP_GETEMPLOYEEDETAILS"   
  2. (  
  3.   EMP_ID IN INT,  
  4.   EMP_DETAIL_CURSOR OUT SYS_REFCURSOR    
  5. AS   
  6. BEGIN  
  7.     OPEN EMP_DETAIL_CURSOR FOR  
  8.     SELECT ID, NAME, SALARY,ADDRESS FROM Employee WHERE ID = EMP_ID;  
  9. END;  

Install Dapper ORM

Open "Package Manager Console" from the "Nuget Package Manager" of Tools menu and type the following command and press enter to install dapper and its dependencies if have.

Install-Package Dapper -Version 1.50.5

After installation, you can check with references section of the project. One reference as "Dapper" has added inside that.

Install Oracle Manage Data Access for Core

We are using Asp.Net Core Web API application with Oracle and need to access Oracle database from the Core application. To use Oracle database with .Net Core application, we have Oracle library which will help us to manage the logic of database access. So, we have to install the following package that is in beta version. 

Install-Package Oracle.ManagedDataAccess.Core -Version 2.12.0-beta2

Add Oracle Connection

Now we have everything ready related to the database like the database, tables, and SPs etc. To access the database from Web API, we have to create connection string as usual inside the "appsettings.json" file. 

  1. {  
  2.   "Logging": {  
  3.     "IncludeScopes"false,  
  4.     "Debug": {  
  5.       "LogLevel": {  
  6.         "Default""Warning"  
  7.       }  
  8.     },  
  9.     "Console": {  
  10.       "LogLevel": {  
  11.         "Default""Warning"  
  12.       }  
  13.     }  
  14.   },  
  15.   "ConnectionStrings": {  
  16.     "EmployeeConnection""data source=mukesh:1531;password=**********;user id=mukesh;Incr Pool Size=5;Decr Pool Size=2;"  
  17.   }  
  18. }  

Create Repositories

To keep the separation of concern in mind, we are using Repository here. Create a new folder as "Repositories" inside the Web API project and create an interface as "IEmployeeRepository" and a class as "EmployeeRepository" which will implement to IEmployeeRepository. 

  1. namespace Core2API.Repositories  
  2. {  
  3.     public interface IEmployeeRepository  
  4.     {  
  5.         object GetEmployeeList();  
  6.   
  7.         object GetEmployeeDetails(int empId);  
  8.           
  9.     }  
  10. }  

Following is the EmployeeRepository class which is implementing IEmployeeRepository. To access configuration, we are injecting IConfiguration in the constructor. So, we have configuration object is ready to use. Apart from that we have GetConnection() method which will get the connection string from the appsettings.json and provide it to OracleConnection to create a connection and finally return connection. We have implemented "IEmployeeRepository" which have two methods as GetEmployeeDetails and GetEmployeeList.

  1. using Core2API.Oracle;  
  2. using Dapper;  
  3. using Microsoft.Extensions.Configuration;  
  4. using Oracle.ManagedDataAccess.Client;  
  5. using System;  
  6. using System.Data;  
  7.   
  8.   
  9. namespace Core2API.Repositories  
  10. {  
  11.     public class EmployeeRepository : IEmployeeRepository  
  12.     {  
  13.         IConfiguration configuration;  
  14.         public EmployeeRepository(IConfiguration _configuration)  
  15.         {  
  16.             configuration = _configuration;  
  17.         }  
  18.         public object GetEmployeeDetails(int empId)  
  19.         {  
  20.             object result = null;  
  21.             try  
  22.             {  
  23.                 var dyParam = new OracleDynamicParameters();  
  24.                 dyParam.Add("EMP_ID", OracleDbType.Int32, ParameterDirection.Input, empId);  
  25.                 dyParam.Add("EMP_DETAIL_CURSOR", OracleDbType.RefCursor, ParameterDirection.Output);  
  26.   
  27.                 var conn = this.GetConnection();  
  28.                 if (conn.State == ConnectionState.Closed)  
  29.                 {  
  30.                     conn.Open();  
  31.                 }  
  32.   
  33.                 if (conn.State == ConnectionState.Open)  
  34.                 {  
  35.                     var query = "USP_GETEMPLOYEEDETAILS";  
  36.   
  37.                     result = SqlMapper.Query(conn, query, param: dyParam, commandType: CommandType.StoredProcedure);  
  38.                 }  
  39.             }  
  40.             catch (Exception ex)  
  41.             {  
  42.                 throw ex;  
  43.             }  
  44.   
  45.             return result;  
  46.         }  
  47.   
  48.         public object GetEmployeeList()  
  49.         {  
  50.             object result = null;  
  51.             try  
  52.             {  
  53.                 var dyParam = new OracleDynamicParameters();  
  54.   
  55.                 dyParam.Add("EMPCURSOR", OracleDbType.RefCursor, ParameterDirection.Output);  
  56.   
  57.                 var conn = this.GetConnection();  
  58.                 if(conn.State == ConnectionState.Closed)  
  59.                 {  
  60.                     conn.Open();  
  61.                 }  
  62.   
  63.                 if (conn.State == ConnectionState.Open)  
  64.                 {  
  65.                     var query = "USP_GETEMPLOYEES";  
  66.   
  67.                     result = SqlMapper.Query(conn, query, param: dyParam, commandType: CommandType.StoredProcedure);  
  68.                 }  
  69.             }  
  70.             catch (Exception ex)  
  71.             {  
  72.                 throw ex;  
  73.             }  
  74.   
  75.             return result;  
  76.         }  
  77.   
  78.         public IDbConnection GetConnection()  
  79.         {  
  80.             var connectionString = configuration.GetSection("ConnectionStrings").GetSection("EmployeeConnection").Value;  
  81.             var conn = new OracleConnection(connectionString);             
  82.             return conn;  
  83.         }  
  84.     }  
  85. }  
  86.    
  87. public IDbConnection GetConnection()  
  88. {  
  89.      var connectionString = configuration.GetSection("ConnectionStrings").GetSection("EmployeeConnection").Value;  
  90.      var conn = new OracleConnection(connectionString);             
  91.      return conn;  
  92. }  

To use Oracle datatypes with .Net Core, we are using OracleDyamicParameters class which will provide the list of functions to manage Oracle parameters behaviors. 

  1. using Dapper;  
  2. using Oracle.ManagedDataAccess.Client;  
  3. using System.Collections.Generic;  
  4. using System.Data;  
  5.   
  6. namespace Core2API.Oracle  
  7. {  
  8.     public class OracleDynamicParameters : SqlMapper.IDynamicParameters  
  9.     {  
  10.         private readonly DynamicParameters dynamicParameters = new DynamicParameters();  
  11.         private readonly List<OracleParameter> oracleParameters = new List<OracleParameter>();  
  12.   
  13.         public void Add(string name, OracleDbType oracleDbType, ParameterDirection direction, object value = nullint? size = null)  
  14.         {  
  15.             OracleParameter oracleParameter;  
  16.             if (size.HasValue)  
  17.             {  
  18.                 oracleParameter = new OracleParameter(name, oracleDbType, size.Value, value, direction);  
  19.             }  
  20.             else  
  21.             {  
  22.                 oracleParameter = new OracleParameter(name, oracleDbType, value, direction);  
  23.             }  
  24.   
  25.             oracleParameters.Add(oracleParameter);  
  26.         }  
  27.   
  28.         public void Add(string name, OracleDbType oracleDbType, ParameterDirection direction)  
  29.         {  
  30.             var oracleParameter = new OracleParameter(name, oracleDbType, direction);  
  31.             oracleParameters.Add(oracleParameter);  
  32.         }  
  33.   
  34.         public void AddParameters(IDbCommand command, SqlMapper.Identity identity)  
  35.         {  
  36.             ((SqlMapper.IDynamicParameters)dynamicParameters).AddParameters(command, identity);  
  37.   
  38.             var oracleCommand = command as OracleCommand;  
  39.   
  40.             if (oracleCommand != null)  
  41.             {  
  42.                 oracleCommand.Parameters.AddRange(oracleParameters.ToArray());  
  43.             }  
  44.         }  
  45.     }  
  46. }  

Configure Dependencies in Startup.cs

To access the dependencies on the controller or repository classes, we have to configure or we can say register our dependency classes with interfaces inside the ConfigureServices method of Startup class. 

  1. using Core2API.Repositories;  
  2. using Microsoft.AspNetCore.Builder;  
  3. using Microsoft.AspNetCore.Hosting;  
  4. using Microsoft.Extensions.Configuration;  
  5. using Microsoft.Extensions.DependencyInjection;  
  6.   
  7. namespace Core2API  
  8. {  
  9.     public class Startup  
  10.     {  
  11.         public Startup(IConfiguration configuration)  
  12.         {  
  13.             Configuration = configuration;  
  14.         }  
  15.   
  16.         public IConfiguration Configuration { get; }  
  17.   
  18.         // This method gets called by the runtime. Use this method to add services to the container.  
  19.         public void ConfigureServices(IServiceCollection services)  
  20.         {  
  21.             services.AddTransient<IEmployeeRepository, EmployeeRepository>();  
  22.             services.AddSingleton<IConfiguration>(Configuration);  
  23.             services.AddMvc();  
  24.         }  
  25.   
  26.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  27.         public void Configure(IApplicationBuilder app, IHostingEnvironment env)  
  28.         {  
  29.             if (env.IsDevelopment())  
  30.             {  
  31.                 app.UseDeveloperExceptionPage();  
  32.             }  
  33.   
  34.             app.UseMvc();  
  35.         }  
  36.     }  
  37. }  

Add EmployeeController

Now it's time to finally create API call in EmployeeControler. First, we have added IEmployeeRepository inside the constructor to use dependencies. Secondly, we have to create API call with Route attribute for both methods.

  1. using Core2API.Repositories;  
  2. using Microsoft.AspNetCore.Mvc;  
  3.   
  4. namespace CoreAPI.Controllers  
  5. {  
  6.     [Produces("application/json")]      
  7.     public class EmployeeController : Controller  
  8.     {  
  9.         IEmployeeRepository employeeRepository;  
  10.         public EmployeeController(IEmployeeRepository _employeeRepository)  
  11.         {  
  12.             employeeRepository = _employeeRepository;  
  13.         }  
  14.   
  15.         [Route("api/GetEmployeeList")]  
  16.         public ActionResult GetEmployeeList()  
  17.         {  
  18.             var result = employeeRepository.GetEmployeeList();  
  19.             if (result == null)  
  20.             {  
  21.                 return NotFound();  
  22.             }  
  23.             return Ok(result);              
  24.         }  
  25.   
  26.         [Route("api/GetEmployeeDetails/{empId}")]  
  27.         public ActionResult GetEmployeeDetails(int empId)  
  28.         {  
  29.             var result = employeeRepository.GetEmployeeDetails(empId);  
  30.             if (result == null)  
  31.             {  
  32.                 return NotFound();  
  33.             }  
  34.             return Ok(result);  
  35.         }  
  36.     }  
  37. }  

Now we have everything ready,  like repository is ready, connection with Oracle database is ready and finally, API call is also ready inside the controller. So, it's time to run the API and see the result in PostMan. Just press F5 to run the Web API and open PostMan to test the result. 

To test in PostMan, first, choose "Get" as a method and provide the URL to get the list of employee records and click to SEND button which will make a request to our API and get the list of employees which we have added at the beginning while creating the database scripts. 

ASP.NET Core

 

To get the single employee record, just pass the following URL as you can see in the image. You can see here, we want to see the record for employee id 103. Once you send the request, you can see the output something like as below. 

ASP.NET Core

Conclusion

So, today, we have learned how to create ASP.NET Core Web API project and use Dapper with Oracle database.

I hope this post will help you. Please put your feedback using comment which helps me to improve myself for next post. If you have any doubts, please ask your doubts or query in the comment section and if you like this post, please share it with your friends.