Database Operations in ASP.NET Core Web API Using ADO.NET

Introduction

 
In this post, we will perform database operations in ASP.NET Core Web API using ADO.NET. If you are asking about performance, then ADO.NET will always be faster than Entity framework. This post will help you understand the implementation of ADO.NET with ASP.NET Core Web API. We have to perform the following steps to achieve the desired goal.
  1. Create SQL Table
  2. Create ASP.NET Core Web API Project
  3. Create Folder and Add Class
  4. Perform Database Operations
  5. Test the API using Postman

Create SQL Table

 
First of all, we will create a database named TestDB in SQL Server Management Studio and then we will create a table named Employee in it which will have four columns ID, FirstName, LastName, and Age. Here is a table query:
  1. Use TestDB    
  2.     
  3. CREATE TABLE Employee (    
  4.     ID int NOT NULL IDENTITY(1,1),    
  5.      FirstName varchar(255),    
  6.     LastName varchar(255) NOT NULL,    
  7.     Age int,    
  8.     PRIMARY KEY (ID)    
  9. );     

Create ASP.NET Core Web API Project

 
Now, we will create anASP.NET Core Web API project. 
  • Select ASP.NET Core Web Application.
  • Name your project ADODotnetwithASPDotnetCore.
 
Select API as the template.
 

Create Folder and Add Class

 
Now we will create a folder named DB. The DB folder will have one class named Database, which will have one variable sqlDataSource. This will have a connection string for connecting the database and one function named GetData, which will be used for fetching data from the database as DataTable. There will also be another function named ExecuteData, used for inserting data into the database. The database class will have the following code:
  1. public static string sqlDataSource = "Data Source=DESKTOP-GV4424J;Initial Catalog=TestDB ;  
  2.                                       Integrated Security=True;";  
  3.   
  4. public DataTable GetData(string str)  
  5. {  
  6.     DataTable objresutl = new DataTable();  
  7.     try  
  8.     {  
  9.         SqlDataReader myReader;  
  10.   
  11.         using (SqlConnection myCon = new SqlConnection(sqlDataSource))  
  12.         {  
  13.             myCon.Open();  
  14.             using (SqlCommand myCommand = new SqlCommand(str, myCon))  
  15.             {  
  16.                 myReader = myCommand.ExecuteReader();  
  17.                 objresutl.Load(myReader);  
  18.   
  19.                 myReader.Close();  
  20.                 myCon.Close();  
  21.             }  
  22.         }  
  23.     }  
  24.     catch (Exception ex)  
  25.     {  
  26.     }  
  27.   
  28.     return objresutl;  
  29.   
  30. }  
  31. public int ExecuteData(string str, params IDataParameter[] sqlParams)  
  32. {  
  33.     int rows = -1;  
  34.     try  
  35.     {  
  36.   
  37.         using (SqlConnection conn = new SqlConnection(sqlDataSource))  
  38.         {  
  39.             conn.Open();  
  40.             using (SqlCommand cmd = new SqlCommand(str, conn))  
  41.             {  
  42.                 if (sqlParams != null)  
  43.                 {  
  44.                     foreach (IDataParameter para in sqlParams)  
  45.                     {  
  46.                         cmd.Parameters.Add(para);  
  47.                     }  
  48.                     rows = cmd.ExecuteNonQuery();  
  49.              }  
  50.                    
  51.   
  52.                
  53.   
  54.   
  55.             }  
  56.         }  
  57.     }  
  58.     catch (Exception ex)  
  59.     {  
  60.   
  61.     }  
  62.   
  63.   
  64.     return rows;  
  65.   
  66.   
  67. }  

Perform Database Operations

 
Once the class is added, we will use these class functions to perform some database operations. First, we will use Post service to insert data into the Employee table and then we will use the Get service to fetch data from the Employee table. We will go to Values controller and will remove the current code and add the following code:
  1. Database db = new Database();  
  2.   
  3. [HttpPost]  
  4. public ActionResult Post(object value)  
  5. {  
  6.     var serialize = JsonConvert.SerializeObject(value);  
  7.     JObject jobject = JObject.Parse(serialize);           
  8.     string query = "insert into Employee (FirstName,LastName,Age) values (@FirstName,@LastName,@Age);";  
  9.     var parameters = new IDataParameter[]  
  10.     {  
  11.         new SqlParameter("@FirstName", jobject["FirstName"].ToString()),  
  12.         new SqlParameter("@LastName", jobject["LastName"].ToString()),  
  13.         new SqlParameter("@Age",jobject["Age"].ToString())  
  14.    };  
  15.     if (db.ExecuteData(query,parameters) > 0)  
  16.     {  
  17.   
  18.         return Ok(new { Result = "Saved" });  
  19.     }  
  20.     else  
  21.     {  
  22.         return NotFound(new { Result = "something went wrong" });  
  23.   
  24.     }  
  25. }  
  26.   
  27. [HttpGet]  
  28. public ActionResult<ienumerable<string>> Get()  
  29. {  
  30.     string query = "select * from Employee";  
  31.     DataTable dt = db.GetData(query);  
  32.     var result = new ObjectResult(dt);  
  33.     return result;  
  34. }  
In the Post service, we will receive data as an Object from client and will Serialize that object to write insert query from received data and will pass that query to the ExecuteData function.
 
In the Get service, we will just write a Select query and pass it to the GetData function, then send returned data in response by converting it into an ObjectResult.
 

Test the API using Postman

 

 

Conclusion

 
In this post, we have seen how to perform database operations in ASP.NET Core Web API using ADO.NET. Hope you all liked it!
 
Thanks for reading!


Similar Articles