DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Spring Boot - How To Use Native SQL Queries | Restful Web Services
  • Snowflake New Web Interface — Snowsight
  • How to Restore a Transaction Log Backup in SQL Server
  • How to Attach SQL Database Without a Transaction Log File

Trending

  • Understanding Java Signals
  • Doris: Unifying SQL Dialects for a Seamless Data Query Ecosystem
  • Failure Handling Mechanisms in Microservices and Their Importance
  • How to Configure and Customize the Go SDK for Azure Cosmos DB
  1. DZone
  2. Data Engineering
  3. Databases
  4. How to Use the SQL Helper Class to Create Web APIs

How to Use the SQL Helper Class to Create Web APIs

Learn how to easily use the SQL Helper Class, which interacts with a database with help from connection strings, to create Web APIs by using Visual Studio 2017.

By 
Thiruppathi Rengasamy user avatar
Thiruppathi Rengasamy
·
Jul. 26, 17 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
19.2K Views

Join the DZone community and get the full member experience.

Join For Free

The SQL Helper class is used in the Data Access Layer, which interacts with a database with the help of connection strings provided. It contains several methods, as shown below. And it improves the performance for the Business Layer and Data Access Layer.

  •  ExecuteNonQuery 
  •  ExecuteDataset
  •  ExecuteDataTable 
  •  ExecuteReader 
  •  ExcuteScalar  

ASP.NET Web API

The ASP.NET Web API is a framework for building Web APIs on the top on the .NET framework, which makes it easy to build HTTP services for a range of clients, including mobile devices, browsers, and desktop applications.

Web API is similar to the 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 the New menu and create a new project.

ASP.NET Web API

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

ASP.NET Web API

Once the project is created, add a new API in the Controllers folder. Right-click on Controllers > Add Controller. Now, add a scaffold and create an API Controller named MasterApiController.

ASP.NET Web API

Helper Class

Create a new folder called Helper in Solution Explorer. Then, paste the below code in your class file.

ASP.NET Web API

Follow the connection string name in the web.config file.

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

Write Web.Config File

I am accessing my local database in the 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 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 a new database, table, and producer. Just use the below 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:

ASP.NET Web API

Create an EmployeeVM model class and convert as a 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 a SQL Data Access class MasterImplementation in the 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 the 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 an HTML file and set this as the 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 running the application, the Web API REST services are ready for consuming.

ASP.NET Web API

You can easily check the custom HTTP request using an advanced REST client. After downloading, 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 click Send, it should hit the Web API Service.

ASP.NET Web API

Finally, the Web API is working perfectly. You get your result in JSON format and RESTful connection.

Conclusion

In this article, we have seen the technique of using the SQL Helper class in building Web APIs. If you have any queries, please tell me through the comments section. And happy coding! 

Web Service Web API Database sql

Opinions expressed by DZone contributors are their own.

Related

  • Spring Boot - How To Use Native SQL Queries | Restful Web Services
  • Snowflake New Web Interface — Snowsight
  • How to Restore a Transaction Log Backup in SQL Server
  • How to Attach SQL Database Without a Transaction Log File

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!