Friday, 18 January 2019

WebApi CRUD Operation- Step by step

In this tutorial, I am assuming you have basic knowledge of asp.net MVC, Web Api, Entity Framework.

1- Open Visual Studio 2015. Create a new Webapi project.


2- Add a new WebApi Controller named EmployeeController.cs.


3- Add a Repository Folder in the solution. add a IEmployeeRepo.cs interface and EmployeeRepo.cs class in the folder. (See above image)

4- Create Database and table in Sql server. below is the script.

CREATE DATABASE [EmployeeDB]
USE [EmployeeDB]
CREATE TABLE [dbo].[tblEmployee](
 [EmpId] [int] IDENTITY(1,1) NOT NULL,
 [FirstName] [varchar](50) NULL,
 [LastName] [varchar](50) NULL,
 CONSTRAINT [PK_tblEmployee] PRIMARY KEY CLUSTERED 
(
 [EmpId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

SET IDENTITY_INSERT [dbo].[tblEmployee] ON 
INSERT [dbo].[tblEmployee] ([EmpId], [FirstName], [LastName]) VALUES (1, N'Suraj', N'Kumar')
INSERT [dbo].[tblEmployee] ([EmpId], [FirstName], [LastName]) VALUES (2, N'Rahul', N'Raj')
INSERT [dbo].[tblEmployee] ([EmpId], [FirstName], [LastName]) VALUES (3, N'Amit', N'Kumar')
SET IDENTITY_INSERT [dbo].[tblEmployee] OFF

5- Add  EmployeeModel.cs class in the Model Folder.



6- Here we are using Database first approach for Entity framework so you need to add Datamodel file (.edmx).


7- Now add the below code in IEmployeeRepo.cs file.

    public interface IEmployeeRepo
    {
        List<EmployeeModel> GetAllEmp();
        void AddEmployee(EmployeeModel entity);
        void DeleteEmployee(int id);
        void UpdateEmployee(int id, EmployeeModel model);
        EmployeeModel FindByEmpId(int Id);
    }

8- Implement this interface in EmployeeRepo.cs class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using EmployeeWeb.Models;

namespace EmployeeWeb.Repository
{
    public class EmployeeRepo : IEmployeeRepo
    {
        EmployeeDBEntities EmpContext;
        List<EmployeeModel> EmpObj = new List<EmployeeModel>();
        public EmployeeRepo()
        {
            EmpContext = new EmployeeDBEntities();
        }

        public List<EmployeeModel> GetAllEmp()
        {
            return MapList(EmpContext.tblEmployees.ToList());
        }

        public List<EmployeeModel> MapList(List<tblEmployee> model)
        {
            List<EmployeeModel> obj = new List<EmployeeModel>();
            foreach (var item in model)
            {
                EmployeeModel emp = new Models.EmployeeModel();
                emp.EmpId = item.EmpId;
                emp.FirstName = item.FirstName;
                emp.LastName = item.LastName;
                
                obj.Add(emp);

            }
            return obj;
        }

        public EmployeeModel FindByEmpId(int Id)
        {
            var result = (from r in EmpContext.tblEmployees where r.EmpId == Id select r).FirstOrDefault();
            return MapEntityToModelModel(result);
        }

        public EmployeeModel MapEntityToModelModel(tblEmployee emp)
        {
            EmployeeModel model = new Models.EmployeeModel();
            model.EmpId = emp.EmpId;
            model.FirstName = emp.FirstName;
            model.LastName = emp.LastName;
            return model;
        }


        public void AddEmployee(EmployeeModel model)
        {
            EmpContext.tblEmployees.Add(MapModelToEntityModel(model));
            EmpContext.SaveChanges();
        }

        public tblEmployee MapModelToEntityModel(EmployeeModel emp)
        {
            tblEmployee model = new Models.tblEmployee();
            //model.EmpId = emp.EmpId;
            model.FirstName = emp.FirstName;
            model.LastName = emp.LastName;
            return model;
        }


        public void DeleteEmployee(int id)
        {
            var emp = EmpContext.tblEmployees
                 .Where(s => s.EmpId == id)
                 .FirstOrDefault();

            EmpContext.Entry(emp).State = System.Data.Entity.EntityState.Deleted;
            EmpContext.SaveChanges();
        }

        public void UpdateEmployee(int id, EmployeeModel model)
        {          
            var existingEmp = EmpContext.tblEmployees.Where(s => s.EmpId == id)
                                                   .FirstOrDefault<tblEmployee>();
            if (existingEmp != null)
            {
                existingEmp.FirstName = model.FirstName;
                existingEmp.LastName = model.LastName;
                EmpContext.Entry(existingEmp).State = System.Data.Entity.EntityState.Modified;
                EmpContext.SaveChanges();
            }
        }
    }
}

9-  Now you need to call your repository functions from Employee api controller.

using System.Net;
using System.Net.Http;
using System.Web.Http;
using EmployeeWeb.Models;
using EmployeeWeb.Repository;
using System.Web.Http.Cors;

namespace EmployeeWeb.Controllers
{
    [EnableCors(origins: "http://localhost:4200", headers: "*", methods: "*")]
    public class EmployeeController : ApiController
    {
        public IEmployeeRepo repository = null;   
        public EmployeeController()
        {
            repository = new EmployeeRepo();
        }

        // GET: api/Employee
        public HttpResponseMessage Get()
        {
            var result = repository.GetAllEmp();
            return Request.CreateResponse(HttpStatusCode.OK, result);
        }

        // GET: api/Employee/5
        public HttpResponseMessage Get(int id)
        {
            var result = repository.FindByEmpId(id);

            return Request.CreateResponse(HttpStatusCode.OK, result);
        }

        // POST: api/Employee
        public HttpResponseMessage Post(EmployeeModel model)
        {
            repository.AddEmployee(model);
            return Request.CreateResponse(HttpStatusCode.Created);
        }

        // PUT: api/Employee/5
        public HttpResponseMessage Put(int id, EmployeeModel model)
        {
            repository.UpdateEmployee(id, model);
            return Request.CreateResponse(HttpStatusCode.OK);
        }

        // DELETE: api/Employee/5
        public HttpResponseMessage Delete(int id)
        {
            repository.DeleteEmployee(id);
            return Request.CreateResponse(HttpStatusCode.OK);
        }
    }
}

10- Add some extraa code in Register function of Webapi config to return api data in json format and to enable CORS.

   public static void Register(HttpConfiguration config)
        {
            config.EnableCors(); // Enables CORS

            // Web API configuration and services
            // Configure Web API to use only bearer token authentication.
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            config.Formatters.Remove(config.Formatters.XmlFormatter);
        }

11- Change the below property for EmpId column in edmx file.


12- Now build and run your solution. Your Api is ready for functioning. Test the Api with any RestClient.


13- See the result of above request.


14- Below is the request for Post method.


15- Below is the request of update method. Here I'm updating the employee of EmpId= 5.



Let me know if you have any concern in this tutorial. Download the complete project. Click here









6 comments:

  1. Hmm, it seems like your site ate my first comment (it was extremely long) so I guess I’ll just sum it up what I had written and say, I’m thoroughly enjoying your blog. I as well as an aspiring blog writer, but I’m still new to the whole thing. Do you have any recommendations for newbie blog writers? I’d appreciate it.
    Advanced AWS Training in Bangalore | Best Amazon Web Services Training Institute in Bangalore
    Advanced AWS Training Institute in Pune | Best Amazon Web Services Training Institute in Pune
    Advanced AWS Online Training Institute in india | Best Online AWS Certification Course in india
    AWS training in bangalore | Best aws training in bangalore

    ReplyDelete
  2. Have you been thinking about the power sources and the tiles whom use blocks I wanted to thank you for this great read!! I definitely enjoyed every little bit of it and I have you bookmarked to check out the new stuff you post
    microsoft azure training in bangalore
    rpa training in bangalore
    best rpa training in bangalore
    rpa online training

    ReplyDelete
  3. This is such a good post. One of the best posts that I\'ve read in my whole life. I am so happy that you chose this day to give me this. Please, continue to give me such valuable posts. Cheers!
    python Course in Pune
    python Course institute in Chennai
    python Training institute in Bangalore

    ReplyDelete
  4. Amazing article. Your blog helped me to improve myself in many ways thanks for sharing this kind of wonderful informative blogs in live. I have bookmarked more article from this website. Such a nice blog you are providing ! Kindly Visit Us @ Best Travels in Madurai | Tours and Travels in Madurai | Madurai Travels

    ReplyDelete

Topics

ADO .Net (2) Ajax (1) Angular (1) Angular Js (17) Angular2 (28) ASP .Net (14) Azure (1) Breeze.js (1) C# (50) CloudComputing (1) CMS (1) CSS (2) Design_Pattern (3) DI (3) Dotnet (22) Entity Framework (3) ExpressJS (4) Html (3) IIS (1) Javascript (6) Jquery (8) Lamda (3) Linq (11) Mongodb (1) MVC (50) NodeJS (7) RDLC (1) Report (1) SDLC (1) Sql Server (30) SSIS (3) SSRS (2) UI (1) WCF (13) Web Api (11) Web Service (1) XMl (1)