Core Web API With Oracle Database and Dapper

Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

21/1/2020 ASP.

NET Core Web API With Oracle Database And Dapper

Top 10 Cloud Service Providers


ASP.NET Core Web API With Oracle Database
Become a member And
C# Corner Login
Dapper Post Ask Question
Mukesh Kumar Updated date May 30 2018 67.7k 4 6

Download Free .NET & JAVA Files API


Try Free File Format APIs for Word/Excel/PDF

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 rst, 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, rst, 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 di erent kinds of the template, you have to
choose Web API.

Now, click OK. It will take a few minutes to con gure 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 exible which helps us to work with databases smoothly.  

As per Oracle

https://www.c-sharpcorner.com/article/asp-net-core-web-api-with-oracle-database-and-dapper/ 1/12
21/1/2020 ASP.NET Core Web API With Oracle Database And Dapper

Oracle SQL Developer is a


Top 10 free,Service
Cloud integrated development environment that simpli es the
Providers
development and management of Oracle Database in both traditional and a
Become Cloud deployments.
member Login
C# Corner
SQL Developer o ers complete end-to-end development of your PL/SQL applications, a
Post theAsk
worksheet for running queries and scripts, a DBA console for managing Question
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.

01. CREATE TABLE "TEST_DB"."EMPLOYEE"


02. (
03. "ID" NUMBER(10,0) GENERATED BY DEFAULT ON NULL AS IDENTITY MINVALUE 1 MAX
04. "NAME" VARCHAR2(255 BYTE),
05. "SALARY" NUMBER(10,0),
06. "ADDRESS" VARCHAR2(500 BYTE)
07. ) SEGMENT CREATION IMMEDIATE
08. PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255
09. 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.

01. Insert into TEST_DB.EMPLOYEE (ID,NAME,SALARY,ADDRESS) values (100,'Mukesh',2


02. Insert into TEST_DB.EMPLOYEE (ID,NAME,SALARY,ADDRESS) values (101,'Rion',280
03. Insert into TEST_DB.EMPLOYEE (ID,NAME,SALARY,ADDRESS) values (102,'Mahesh',1
04. Insert into TEST_DB.EMPLOYEE (ID,NAME,SALARY,ADDRESS) values (103,'Banky',20

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.

01. CREATE OR REPLACE PROCEDURE "TEST_DB"."USP_GETEMPLOYEES" (


02. EMPCURSOR OUT SYS_REFCURSOR
03. )
04. AS
05. Begin
06. Open EMPCURSOR For
07. SELECT ID, NAME, SALARY,ADDRESS FROM Employee;
08. End;

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

01. CREATE OR REPLACE PROCEDURE "TEST_DB"."USP_GETEMPLOYEEDETAILS"


https://www.c-sharpcorner.com/article/asp-net-core-web-api-with-oracle-database-and-dapper/ 2/12
21/1/2020 ASP.NET Core Web API With Oracle Database And Dapper

02. ( Top 10 Cloud Service Providers


03. EMP_ID IN INT,
04. EMP_DETAIL_CURSOR OUT SYS_REFCURSOR Become a member
C# Corner Login
05. ) AS
06. BEGIN Post Ask Question
07. OPEN EMP_DETAIL_CURSOR FOR
08. SELECT ID, NAME, SALARY,ADDRESS FROM Employee WHERE ID = EMP_ID;
09. 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" le. 

01. {
02. "Logging": {
03. "IncludeScopes": false,
04. "Debug": {
05. "LogLevel": {
06. "Default": "Warning"
07. }
08. },
09. "Console": {
10. "LogLevel": {
11. "Default": "Warning"
12. }
13. }
14. },
15. "ConnectionStrings": {
16. "EmployeeConnection": "data source=mukesh:1531;password=**********;user
17. }
https://www.c-sharpcorner.com/article/asp-net-core-web-api-with-oracle-database-and-dapper/ 3/12
21/1/2020 ASP.NET Core Web API With Oracle Database And Dapper

18. } Top 10 Cloud Service Providers

Become a member
C# Corner Login
Create Repositories Post Ask Question

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. 

01. namespace Core2API.Repositories


02. {
03. public interface IEmployeeRepository
04. {
05. object GetEmployeeList();
06.
07. object GetEmployeeDetails(int empId);
08.
09. }
10. }

Following is the EmployeeRepository class which is implementing IEmployeeRepository. To access


con guration, we are injecting ICon guration in the constructor. So, we have con guration 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
nally return connection. We have implemented "IEmployeeRepository" which have two methods
as GetEmployeeDetails and GetEmployeeList.

01. using Core2API.Oracle;


02. using Dapper;
03. using Microsoft.Extensions.Configuration;
04. using Oracle.ManagedDataAccess.Client;
05. using System;
06. using System.Data;
07.
08.
09. 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

https://www.c-sharpcorner.com/article/asp-net-core-web-api-with-oracle-database-and-dapper/ 4/12
21/1/2020 ASP.NET Core Web API With Oracle Database And Dapper

25. dyParam.Add("EMP_DETAIL_CURSOR",
Top 10 Cloud Service Providers OracleDbType.RefCursor, Par
26.
27. var conn = this.GetConnection(); Become a member
C# Corner Login
28. if (conn.State == ConnectionState.Closed)
29. { Post Ask Question
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, co
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, ParameterDi
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, co
68. }
69. }
70. catch (Exception ex)
71. {
72. throw ex;
73. }
74.
75. return result;
76. }
77.
78. public IDbConnection GetConnection()
79. {

https://www.c-sharpcorner.com/article/asp-net-core-web-api-with-oracle-database-and-dapper/ 5/12
21/1/2020 ASP.NET Core Web API With Oracle Database And Dapper

80. varCloud
Top 10 connectionString
Service Providers = configuration.GetSection("ConnectionStrin
81. var conn = new OracleConnection(connectionString);
82. return conn; Become a member
C# Corner Login
83. }
84. } Post Ask Question
85. }
86.
87. public IDbConnection GetConnection()
88. {
89. var connectionString = configuration.GetSection("ConnectionStrings").Ge
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. 

01. using Dapper;


02. using Oracle.ManagedDataAccess.Client;
03. using System.Collections.Generic;
04. using System.Data;
05.
06. namespace Core2API.Oracle
07. {
08. public class OracleDynamicParameters : SqlMapper.IDynamicParameters
09. {
10. private readonly DynamicParameters dynamicParameters = new DynamicPa
11. private readonly List<OracleParameter> oracleParameters = new List<O
();
12.
13. public void Add(string name, OracleDbType oracleDbType, ParameterDir
14. {
15. OracleParameter oracleParameter;
16. if (size.HasValue)
17. {
18. oracleParameter = new OracleParameter(name, oracleDbType, si
19. }
20. else
21. {
22. oracleParameter = new OracleParameter(name, oracleDbType, va
23. }
24.
25. oracleParameters.Add(oracleParameter);
26. }
27.
28. public void Add(string name, OracleDbType oracleDbType, ParameterDir
29. {
30. var oracleParameter = new OracleParameter(name, oracleDbType, di
31. oracleParameters.Add(oracleParameter);
32. }
33.
34. public void AddParameters(IDbCommand command, SqlMapper.Identity ide
35. {
https://www.c-sharpcorner.com/article/asp-net-core-web-api-with-oracle-database-and-dapper/ 6/12
21/1/2020 ASP.NET Core Web API With Oracle Database And Dapper

36. ((SqlMapper.IDynamicParameters)dynamicParameters).AddParameters(
Top 10 Cloud Service Providers
37.
38. Become a member
C# Corner
var oracleCommand = command as OracleCommand; Login
39.
40. if (oracleCommand != null) Post Ask Question
41. {
42. oracleCommand.Parameters.AddRange(oracleParameters.ToArray()
43. }
44. }
45. }
46. }

Con gure Dependencies in Startup.cs

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

01. using Core2API.Repositories;


02. using Microsoft.AspNetCore.Builder;
03. using Microsoft.AspNetCore.Hosting;
04. using Microsoft.Extensions.Configuration;
05. using Microsoft.Extensions.DependencyInjection;
06.
07. namespace Core2API
08. {
09. 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 se
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 config
27. public void Configure(IApplicationBuilder app, IHostingEnvironment e
28. {
29. if (env.IsDevelopment())
30. {
31. app.UseDeveloperExceptionPage();
32. }
33.
34. app.UseMvc();
https://www.c-sharpcorner.com/article/asp-net-core-web-api-with-oracle-database-and-dapper/ 7/12
21/1/2020 ASP.NET Core Web API With Oracle Database And Dapper

35. }Top 10 Cloud Service Providers


36. }
37. } Become a member
C# Corner Login

Post Ask Question


Add EmployeeController

Now it's time to nally 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.

01. using Core2API.Repositories;


02. using Microsoft.AspNetCore.Mvc;
03.
04. namespace CoreAPI.Controllers
05. {
06. [Produces("application/json")]
07. public class EmployeeController : Controller
08. {
09. 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 nally, API call is also ready inside the controller. So, it's time to run the API and see the result

https://www.c-sharpcorner.com/article/asp-net-core-web-api-with-oracle-database-and-dapper/ 8/12
21/1/2020 ASP.NET Core Web API With Oracle Database And Dapper

in PostMan. Just press F5Cloud


Top 10 to run the Web
Service API and open PostMan to test the result. 
Providers

Become a member
C#toCorner Login
To test in PostMan, rst, choose "Get" as a method and provide the URL get the list of
employee records and click to SEND button which will make a request
Post to our API
Ask and get the list
Question
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.

Next Recommended Article


ASP.NET Core Web API With Dapper And VS 2017

In this article, you will learn how to create an ASP.NET Core based Web API using
DapperMicro ORM with Visual Studio 2017 along with dependency injection

ASP.NET Core ASP.NET Core Web API Dapper Oracle Database

Mukesh Kumar

I am a software developer, Microsoft MVP, C# Corner MVP, blogger and you can also nd me
on Asp.Net Forums . I have extensive experience with designing and developing enterprise
scale applications on Microsoft technolo... Read more
http://www.mukeshkumar.net https://in.linkedin.com/in/mukeshkumartech

https://www.c-sharpcorner.com/article/asp-net-core-web-api-with-oracle-database-and-dapper/ 9/12
21/1/2020 ASP.NET Core Web API With Oracle Database And Dapper

79 8.8m Top 10 Cloud


4 Service
1 Providers

Become a member
C# Corner Login
6 4
Post Ask Question

Type your comment here and press Enter Key (Minimum 10 characters)

Hi Mukesh, Thanks for giving nice article, I works good with out cursor but when I try to return
Varchar2 Employee Name alone it gives 0 "Zero" output.
suresh kumar Oct 18, 2019
1816 66 0 0 0 Reply

How one use oracle change noti cation to automatically get newest records when database changes?
Mihai Dumitru Mar 02, 2019
1865 17 0 0 0 Reply

Hi, I have implemented it on vs 2017 and it works ne Now I want t implement it on vs 2015, I have
done everything but these two functions are not available in vs 2015 Do you know any alternative of
these two: UseHsts() & UseHttpsRedirection As they are not available in core 1.0 Thanks.
Omer Obaid Dec 29, 2018
1858 24 0 0 0 Reply

Good job, Mukesh! Could you please provide the source code? Thank you.
Daniel Ha Nov 12, 2018
1877 5 0 0 0 Reply

https://www.c-sharpcorner.com/article/asp-net-core-web-api-with-oracle-database-and-dapper/ 10/12
21/1/2020 ASP.NET Core Web API With Oracle Database And Dapper

Top 10 Cloud Service Providers

Become a member
C# Corner Login

Post Ask Question

FEATURED ARTICLES
Introduction To MongoDB Atlas

Why Is My SQL Server Query Slow

Null Value And Null Reference Handling - C#6 To C# 9 New Features - Day One

Learn To Draw Simple ASP.NET Core Blazor Bar Chart Using Canvas Extensions

Host ASP.NET Core Web API On Linux Azure VM


View All

TRENDING UP

01 Learn Angular 8 Step By Step In 10 Days - HttpClient Or Ajax Call - Day Nine

02 How to Prevent Memory Leak and Pro ling in Xamarin Applications

03 Top 10 Social Media In uencers

04 How To Manage Our Blob Storage Account Using Logic Apps

05 How To Upload A File To Amazon S3 Using AWS SDK In MVC

06 Comparison Between ECMAScript 5 And ECMAScript 6 Versions Of JavaScript

07 ASP.NET Core MVC Request Life Cycle

08 What Can Be Done To Make Code Quality Better

https://www.c-sharpcorner.com/article/asp-net-core-web-api-with-oracle-database-and-dapper/ 11/12
21/1/2020 ASP.NET Core Web API With Oracle Database And Dapper

09 A File System Top


Manager From
10 Cloud Scratch
Service In .NET Core And VueJS
Providers

Become a member
C# Corner Login
10 Xamarin UI Test
Post View All
Ask Question

About Us Contact Us Privacy Policy Terms Media Kit Sitemap Report a Bug FAQ Partners

C# Tutorials Common Interview Questions Stories Consultants Ideas Certi cations


©2020 C# Corner. All contents are copyright of their authors.

https://www.c-sharpcorner.com/article/asp-net-core-web-api-with-oracle-database-and-dapper/ 12/12

You might also like