.Net Core With Oracle Database Using Dapper

We start off by creating a project of .net core 3.1. Go to the NuGet Manager and try downloading and installing the following packages,
  • Dapper [ Latest stable version ]
  • Oracle.ManagedDataAccess.Core [ Latest Stable Version ] 
The installed arena of Nuget package Manager should like something like this,
 
.Net Core With Oracle Database
 
Lets begin by creating a static class named Connection Manager. Here first we have to create our connection string which would look something like this. 
  1. private static string connString = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=host id)(PORT=specified port number)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=service name)));User Id = user Id; Password = your password; ";  
We have to create our method which should connect to the database. Here we would be creating a static function named GetConnection which should return IDbConnection. 
  1. public static IDbConnection GetConnection()  
  2.         {  
  3.             var conn = new OracleConnection(connString);  
  4.             if (conn.State == ConnectionState.Closed)  
  5.             {  
  6.                 conn.Open();  
  7.             }  
  8.             return conn;  
  9.         }  
An object is created with the reference to OracleConnection which is a member of Oracle.ManagedDataAccess.Client library which we have installed earlier through the nuget package manager. Now using this method we would be able to to connect to the database. As of now, we have made the functional procedure to connect to our oracle database so we should also make a function which should do the exact opposite, which is closing the existing connection with the database. Creating a CloseConnection() function which accepts a IDbConnection type object would do our job. 
  1. public static void CloseConnection(IDbConnection conn)  
  2.         {  
  3.             if (conn.State == ConnectionState.Open || conn.State == ConnectionState.Broken)  
  4.             {  
  5.                 conn.Close();  
  6.             }  
  7.         }  
So finally our ConnectionManager Class should look something like this.
  1. using Oracle.ManagedDataAccess.Client;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Data;  
  5. using System.Linq;  
  6. using System.Threading.Tasks;  
  7.   
  8. namespace CoreWithOracleDBDapperAsORM.Utility  
  9. {  
  10.     public static class ConnectionManager  
  11.     {  
  12.         private static string connString = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=host id)(PORT=specified port number)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=service name)));User Id = user Id; Password = your password; ";  
  13.   
  14.         public static IDbConnection GetConnection()  
  15.         {  
  16.             var conn = new OracleConnection(connString);  
  17.             if (conn.State == ConnectionState.Closed)  
  18.             {  
  19.                 conn.Open();  
  20.             }  
  21.             return conn;  
  22.         }  
  23.   
  24.         public static void CloseConnection(IDbConnection conn)  
  25.         {  
  26.             if (conn.State == ConnectionState.Open || conn.State == ConnectionState.Broken)  
  27.             {  
  28.                 conn.Close();  
  29.             }  
  30.         }  
  31.     }  
  32. }  
Let's say we have a table in database named Student who has a first name , last name and roll number. So we create a class name student.
  1.     public class Student  
  2.     {  
  3.         public int RollNumber { getset; }  
  4.         public string FirstName { getset; }  
  5.         public string LastName { getset; }  
  6.     }  
Now let's build our querybuilder who will execute all our query. For starters, we will create 3 functions which would be used for different purposes. 
 
Firstly let's create the GetList method which should take an empty object to return its type.
 
But first we need to create a generic method which would build our query based on the object that had been sent. Although we need to perform an additional task which is to create a method which would be returning the pascal form of the property of the object as in the database in oracle, the norm is to follow the Pascal case but in C# we usually use the camelCase to get our job done. Another thing is we need to create a method named GetColumnList which should take an object and return all of the properties as strings converted to the camel case. 
  1. private static string GetColumnList(T entity)  
  2.        {  
  3.            string selectedColumns = "Select ";  
  4.            foreach (var prop in entity.GetType().GetProperties())  
  5.            {  
  6.                if (!prop.Name.Contains("_"))  
  7.                {  
  8.                    selectedColumns = selectedColumns + ConvertToPascalCase(prop.Name) + " AS " + prop.Name + ",";  
  9.                }  
  10.            }  
  11.   
  12.            return selectedColumns + " From "+ ConvertToPascalCase(entity.GetType().Name);
  13.        }  
  14.   
  15.        private static string ConvertToPascalCase(string str)  
  16.        {  
  17.            return string.Concat(str.Select((x, i) => i > 0 && char.IsUpper(x) ? "_" + x.ToString() : x.ToString())).ToLower();  
  18.        }  
Now as we have the supporting methods done, let's get back to our GetList Method. 
  1. public static IEnumerable<T> GetList(T entity)  
  2. {  
  3.     IDbConnection connection = ConnectionManager.GetConnection();  
  4.   
  5.     var result = connection.Query<T>(GetColumnList(entity));  
  6.   
  7.     ConnectionManager.CloseConnection(connection);  
  8.   
  9.     return result;  
  10. }  
Similarly we need to create a method which would be returning only one row. 
  1. public static T SingleOrDefault(T entity)  
  2. {  
  3.     IDbConnection connection = ConnectionManager.GetConnection();  
  4.   
  5.     var result = connection.QueryFirstOrDefault<T>(GetColumnList(entity));  
  6.   
  7.     ConnectionManager.CloseConnection(connection);  
  8.   
  9.     return result;  
  10. }  
Now we have to get to a method which would be performing an action like insert update or delete. 
  1. public static int? ExecuteAction(string query)  
  2. {  
  3.     IDbConnection connection = ConnectionManager.GetConnection();  
  4.   
  5.     var result = connection.Execute(query);  
  6.   
  7.     ConnectionManager.CloseConnection(connection);  
  8.   
  9.     return result;  
  10. }  
Now let's look at the whole picture, 
  1. using Dapper;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Data;  
  5. using System.Linq;  
  6. using System.Threading.Tasks;  
  7.   
  8. namespace CoreWithOracleDBDapperAsORM.Utility  
  9. {  
  10.     public static class QueryBuilder<T>  
  11.     {  
  12.         public static IEnumerable<T> GetList(T entity)  
  13.         {  
  14.             IDbConnection connection = ConnectionManager.GetConnection();  
  15.   
  16.             var result = connection.Query<T>(GetColumnList(entity));  
  17.   
  18.             ConnectionManager.CloseConnection(connection);  
  19.   
  20.             return result;  
  21.         }  
  22.   
  23.         public static T SingleOrDefault(T entity)  
  24.         {  
  25.             IDbConnection connection = ConnectionManager.GetConnection();  
  26.   
  27.             var result = connection.QueryFirstOrDefault<T>(GetColumnList(entity));  
  28.   
  29.             ConnectionManager.CloseConnection(connection);  
  30.   
  31.             return result;  
  32.         }  
  33.   
  34.         public static int? ExecuteAction(string query)  
  35.         {  
  36.             IDbConnection connection = ConnectionManager.GetConnection();  
  37.   
  38.             var result = connection.Execute(query);  
  39.   
  40.             ConnectionManager.CloseConnection(connection);  
  41.   
  42.             return result;  
  43.         }  
  44.   
  45.         private static string GetColumnList(T entity)  
  46.         {  
  47.             string selectedColumns = "Select ";  
  48.             foreach (var prop in entity.GetType().GetProperties())  
  49.             {  
  50.                 if (!prop.Name.Contains("_"))  
  51.                 {  
  52.                     selectedColumns = selectedColumns + ConvertToPascalCase(prop.Name) + " AS " + prop.Name + ",";  
  53.                 }  
  54.             }  
  55.   
  56.             return selectedColumns + " From " + ConvertToPascalCase(entity.GetType().Name);  
  57.         }  
  58.   
  59.         private static string ConvertToPascalCase(string str)  
  60.         {  
  61.             return string.Concat(str.Select((x, i) => i > 0 && char.IsUpper(x) ? "_" + x.ToString() : x.ToString())).ToLower();  
  62.         }  
  63.     }  
  64. }  
Now let's get back to our controller. 
  1. using CoreWithOracleDBDapperAsORM.Model;  
  2. using CoreWithOracleDBDapperAsORM.Utility;  
  3. using Microsoft.AspNetCore.Mvc;  
  4.   
  5. namespace CoreWithOracleDBDapperAsORM.Controllers  
  6. {  
  7.     [Route("api/[controller]")]  
  8.     [ApiController]  
  9.     public class StudentController : ControllerBase  
  10.     {  
  11.         [HttpGet]  
  12.         [Route("GetStudentList")]  
  13.         public object GetStudentList()  
  14.         {  
  15.             return QueryBuilder<Student>.GetList(new Student());  
  16.         }  
  17.     }  
  18. }  
As this is a basic tutorial on how to connect your .net core application with oracle database with the help of Dapper, no repository or service pattern has been used to populate the data. When you do, it's entirely upon you which design pattern you follow to build up your application.
 
THANK YOU.


Similar Articles