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.
Go to New menu and create a new project.
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.
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”.
Helper Class
Create new folder as “Helper” in Solution Explorer; then paste the below code in your class file.
Follow the connection string name in web.config file.
- private static readonly string connectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
Write Web.Config File
I am accessing my local DB in Web.config file.
- <connectionStrings>
- <add name="ConString" providerName="System.Data.SqlClient" connectionString="Data Source=MYLTOP;Initial Catalog=DBMyn;User ID=sa;Password=Thiru@123" />
- </connectionStrings>
Create one more data convert class using Reflection, like below
- public static IList<T> ToList<T>(this DataTable table) where T : new()
- {
- IList<PropertyInfo> properties = typeof(T).GetProperties().ToList();
- IList<T> result = new List<T>();
-
- foreach (var row in table.Rows)
- {
- var item = CreateItemFromRow<T>((DataRow)row, properties);
- result.Add(item);
- }
-
- return result;
- }
If you want to know what Reflection is, see my blog here.
Create new database, Table, & Producer. Just use the below query.
SQL Query
- USE [ABCDB]
- GO
- /****** Object: StoredProcedure [dbo].[PC_EmpMaster] Script Date: 7/22/2017 1:20:35 PM ******/
- SET ANSI_NULLS ON
- GO
- SET QUOTED_IDENTIFIER ON
- GO
-
- CREATE PROCEDURE [dbo].[PC_EmpMaster]
-
- @Row_id BIGINT=NULL,
- @MODE VARCHAR(10)=NULL
-
- AS
-
- BEGIN
- SET NOCOUNT ON;
- IF(@MODE ='GET')
- BEGIN
- 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
- END
- ELSE IF(@MODE ='GETBYID')
- BEGIN
- SELECT Emp_Code,Emp_FName,Emp_LName,Emp_Role,Emp_Department,Emp_Address FROM EmpMaster WHERE Row_id=@Row_id
- END
- SET NOCOUNT OFF;
- END
- GO
- /****** Object: Table [dbo].[EmpMaster] Script Date: 7/22/2017 1:20:35 PM ******/
- SET ANSI_NULLS ON
- GO
- SET QUOTED_IDENTIFIER ON
- GO
- SET ANSI_PADDING ON
- GO
- CREATE TABLE [dbo].[EmpMaster](
- [Row_id] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
- [Emp_Code] [varchar](10) NULL,
- [Emp_FName] [varchar](50) NULL,
- [Emp_LName] [varchar](50) NULL,
- [Emp_Status] [bit] NULL,
- [Emp_DOB] [datetime] NULL,
- [Emp_Maritalstatus] [varchar](10) NULL,
- [Emp_Role] [varchar](50) NULL,
- [Emp_Department] [varchar](50) NULL,
- [Emp_Address] [varchar](500) NULL,
- [Emp_Profilestatus] [int] NULL,
- [Emp_Expriance] [int] NULL,
- [Create_By] [varchar](50) NULL,
- [Create_Date] [datetime] NULL
- ) ON [PRIMARY]
Simply insert some employee details in this table.
Create EmployeeVM Model Class with Convert as list.
- public class EmployeeVM
- {
- public List<EmployeeDetails> loadEmployeeList { get; set; }
- }
- public class EmployeeDetails
- {
- public long Row_id { get; set; }
- public string Emp_Code { get; set; }
- public string Emp_FName { get; set; }
- public string Emp_LName { get; set; }
- public string Emp_DOB { get; set; }
- public string Emp_Maritalstatus { get; set; }
- public string Emp_Role { get; set; }
-
- public string Emp_Department { get; set; }
- public string Emp_Address { get; set; }
-
- public int Emp_Profilestatus { get; set; }
- public int Emp_Expriance { get; set; }
- public string Create_By { get; set; }
- public string Create_Date { get; set; }
- public string Mode { get; set; }
- public bool Emp_Status { get; set; }
- }
Create SQL Data Access Class, "MasterImplementation" in implementation folder.
- public EmployeeVM GetEmployeeDetails(EmployeeDetails empDetails)
- {
-
- EmployeeVM vmGetGrid = new EmployeeVM();
- SqlParameter[] prms = new SqlParameter[2];
- prms[0] = new SqlParameter("@Row_id", "");
- prms[1] = new SqlParameter("@MODE", "GET");
-
- DataSet ds = new DataSet();
- ds = (new DBHelper().GetDatasetFromSP)("dbo.PC_EmpMaster", prms);
- if (ds != null)
- {
- if (ds.Tables[0].Rows.Count > 0)
- {
- vmGetGrid.loadEmployeeList = ds.Tables[0].ToList<EmployeeDetails>().ToList();
- }
-
- }
- return vmGetGrid;
- }
Now, you can access this class from Web API Controller.
- [HttpGet]
- #region GetEmployeeDetails
- public HttpResponseMessage GetEmployeeDetails(EmployeeDetails empDetails)
- {
- try
- {
- var Response = EmployeeMaster.GetEmployeeDetails(empDetails);
- var Result = this.Request.CreateResponse(HttpStatusCode.OK, Response, new JsonMediaTypeFormatter());
-
- return Result;
- }
- catch (Exception ex)
- {
- HttpError Error = new HttpError(ex.Message) { { "IsSuccess", false } };
- return this.Request.CreateErrorResponse(HttpStatusCode.OK, Error);
- }
- }
- #endregion
Create HTML file and set as start Page.
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <title>Web Api</title>
- </head>
- <body>
- <h1>Web api Service is up</h1>
- </body>
- </html>
Once you run the application, Web API REST services are ready for consuming.
You can easily check custom HTTP Request using Advanced REST Client. After download, open it from your Chrome Apps List.
Enter the correct URL and select the right HTTP verbs on the header.
Once you've clicked on send button in this tool, it should hit the Web API Service.
Finally, the Web API is working perfectly. You got result in JSON format & RESTful connection.
Output
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!...