Learn Web API : Using SQL Helper Class

Introduction

This article demonstrates how to use SQL Helper Class in Web API using Visual Studio 2017.

What is SQL Helper?

SQL Helper class is used in Data Access Layer which interacts with database with the help of connection string provided and it contains several methods like below. And, it improves the performance for Business Layer & Data Access Layer.

  • ExecuteNonQuery
  • ExecuteDataset,
  • ExecuteDataTable
  • ExecuteReader,
  • ExcuteScalar & more

ASP.NET Web API

ASP.NET Web API is a Framework for building Web API’s on the top on the .NET framework, which makes it easy to build HTTP services for a  range of clients, including mobile devices, all browsers, & desktop application.

Web API is similar to ASP.NET MVC so it contains all MVC features.

  • Model
  • Controller
  • Routing
  • Model binding
  • Filter
  • Dependency injections

Create Web API

Open Visual Studio 2017.

ASP.NET Web API

Go to New menu and create a new project.

ASP.NET Web API

In the New Project menu, select ASP.NET Web Application on Framework 4.6. Enter the name of project in “Solution name” textbox and click OK button.

ASP.NET Web API

Once the project is created, add new API in the Controllers folder. Right click on Controllers-> Add Controller. Now, add Scaffold & create an API Controller “MasterApiController”.

ASP.NET Web API

Helper Class

Create new folder as “Helper” in Solution Explorer; then paste the below code in your class file.

ASP.NET Web API

Follow the connection string name in web.config file.

  1. private static readonly string connectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;   

Write Web.Config File

I am accessing my local DB in Web.config file. 

  1. <connectionStrings>  
  2.     <add name="ConString" providerName="System.Data.SqlClient" connectionString="Data Source=MYLTOP;Initial Catalog=DBMyn;User ID=sa;Password=Thiru@123" />  
  3.   </connectionStrings>   

Create one more data convert class using Reflection, like below 

  1. public static IList<T> ToList<T>(this DataTable table) where T : new()  
  2.         {  
  3.             IList<PropertyInfo> properties = typeof(T).GetProperties().ToList();  
  4.             IList<T> result = new List<T>();  
  5.   
  6.             foreach (var row in table.Rows)  
  7.             {  
  8.                 var item = CreateItemFromRow<T>((DataRow)row, properties);  
  9.                 result.Add(item);  
  10.             }  
  11.   
  12.             return result;  
  13.         }   

If you want to know what Reflection is, see my blog here.

Create new database, Table, & Producer. Just use the below query.

SQL Query 

  1. USE [ABCDB]  
  2. GO  
  3. /****** Object:  StoredProcedure [dbo].[PC_EmpMaster]    Script Date: 7/22/2017 1:20:35 PM ******/  
  4. SET ANSI_NULLS ON  
  5. GO  
  6. SET QUOTED_IDENTIFIER ON  
  7. GO  
  8.   
  9. CREATE PROCEDURE [dbo].[PC_EmpMaster]  
  10.   
  11.     @Row_id             BIGINT=NULL,  
  12.     @MODE               VARCHAR(10)=NULL  
  13.       
  14. AS   
  15.   
  16.  BEGIN   
  17.     SET NOCOUNT ON;  
  18.         IF(@MODE ='GET')  
  19.         BEGIN  
  20.             SELECT Row_id,Emp_Code,Emp_FName,Emp_Status,CONVERT(VARCHAR(12),Emp_DOB) AS Emp_DOB,Emp_Maritalstatus,Emp_Profilestatus,Emp_Expriance,Create_By,CONVERT(VARCHAR(12),Create_Date) AS Create_Date FROM EmpMaster  
  21.         END  
  22.         ELSE IF(@MODE ='GETBYID')  
  23.         BEGIN  
  24.             SELECT Emp_Code,Emp_FName,Emp_LName,Emp_Role,Emp_Department,Emp_Address FROM EmpMaster WHERE Row_id=@Row_id  
  25.         END  
  26.     SET NOCOUNT OFF;  
  27. END  
  28. GO  
  29. /****** Object:  Table [dbo].[EmpMaster]    Script Date: 7/22/2017 1:20:35 PM ******/  
  30. SET ANSI_NULLS ON  
  31. GO  
  32. SET QUOTED_IDENTIFIER ON  
  33. GO  
  34. SET ANSI_PADDING ON  
  35. GO  
  36. CREATE TABLE [dbo].[EmpMaster](  
  37.     [Row_id] [numeric](18, 0) IDENTITY(1,1) NOT NULL,  
  38.     [Emp_Code] [varchar](10) NULL,  
  39.     [Emp_FName] [varchar](50) NULL,  
  40.     [Emp_LName] [varchar](50) NULL,  
  41.     [Emp_Status] [bitNULL,  
  42.     [Emp_DOB] [datetime] NULL,  
  43.     [Emp_Maritalstatus] [varchar](10) NULL,  
  44.     [Emp_Role] [varchar](50) NULL,  
  45.     [Emp_Department] [varchar](50) NULL,  
  46.     [Emp_Address] [varchar](500) NULL,  
  47.     [Emp_Profilestatus] [intNULL,  
  48.     [Emp_Expriance] [intNULL,  
  49.     [Create_By] [varchar](50) NULL,  
  50.     [Create_Date] [datetime] NULL  
  51. ON [PRIMARY]   

Simply insert some employee details in this table.

ASP.NET Web API

Create EmployeeVM Model Class with Convert as list.

  1. public class EmployeeVM  
  2.     {  
  3.         public List<EmployeeDetails> loadEmployeeList { get; set; }  
  4.     }  
  5.     public class EmployeeDetails  
  6.     {  
  7.         public long Row_id { get; set; }  
  8.         public string Emp_Code { get; set; }  
  9.         public string Emp_FName { get; set; }  
  10.         public string Emp_LName { get; set; }  
  11.         public string Emp_DOB { get; set; }  
  12.         public string Emp_Maritalstatus { get; set; }  
  13.         public string Emp_Role { get; set; }  
  14.   
  15.         public string Emp_Department { get; set; }  
  16.         public string Emp_Address { get; set; }  
  17.   
  18.         public int Emp_Profilestatus { get; set; }  
  19.         public int Emp_Expriance { get; set; }  
  20.         public string Create_By { get; set; }  
  21.         public string Create_Date { get; set; }  
  22.         public string Mode { get; set; }  
  23.         public bool Emp_Status { get; set; }  
  24.     }   

Create SQL Data Access Class, "MasterImplementation" in implementation folder.

  1. public EmployeeVM GetEmployeeDetails(EmployeeDetails empDetails)  
  2.         {  
  3.   
  4.             EmployeeVM vmGetGrid = new EmployeeVM();  
  5.             SqlParameter[] prms = new SqlParameter[2];  
  6.             prms[0] = new SqlParameter("@Row_id""");  
  7.             prms[1] = new SqlParameter("@MODE""GET");  
  8.   
  9.             DataSet ds = new DataSet();  
  10.             ds = (new DBHelper().GetDatasetFromSP)("dbo.PC_EmpMaster", prms);  
  11.             if (ds != null)  
  12.             {  
  13.                 if (ds.Tables[0].Rows.Count > 0)  
  14.                 {  
  15.                     vmGetGrid.loadEmployeeList = ds.Tables[0].ToList<EmployeeDetails>().ToList();  
  16.                 }  
  17.   
  18.             }  
  19.             return vmGetGrid;  
  20.         }   

Now, you can access this class from Web API Controller.

  1. [HttpGet]  
  2.         #region GetEmployeeDetails  
  3.         public HttpResponseMessage GetEmployeeDetails(EmployeeDetails empDetails)  
  4.         {  
  5.             try  
  6.             {  
  7.                 var Response = EmployeeMaster.GetEmployeeDetails(empDetails);  
  8.                 var Result = this.Request.CreateResponse(HttpStatusCode.OK, Response, new JsonMediaTypeFormatter());  
  9.   
  10.                 return Result;  
  11.             }  
  12.             catch (Exception ex)  
  13.             {  
  14.                 HttpError Error = new HttpError(ex.Message) { { "IsSuccess"false } };  
  15.                 return this.Request.CreateErrorResponse(HttpStatusCode.OK, Error);  
  16.             }  
  17.         }  
  18.         #endregion   

Create  HTML file and set as start Page. 

  1. <html xmlns="http://www.w3.org/1999/xhtml">  
  2. <head>  
  3.     <title>Web Api</title>  
  4. </head>  
  5. <body>  
  6.     <h1>Web api Service is up</h1>  
  7. </body>  
  8. </html>   

Once you run the application, Web API REST services are ready for consuming.

ASP.NET Web API

You can easily check custom HTTP Request using Advanced REST Client. After download, open it from your Chrome Apps List.

ASP.NET Web API

Enter the correct URL and select the right HTTP verbs on the header.

ASP.NET Web API

Once you've clicked on send button in this tool, it should hit the Web API Service.

ASP.NET Web API

Finally, the Web API is working perfectly. You got result in JSON format & RESTful connection.

Output

ASP.NET Web API

Conclusion

In this article, we have seen the technique of using SQL Helper class in Web API. If you have any queries, please tell me through the comments section.

Happy Coding!...


Similar Articles