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









11 comments:

  1. 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
  2. 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
  3. Attend The Python training in bangalore From ExcelR. Practical Python training in bangalore Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Python training in bangalore.
    python training in bangalore

    ReplyDelete
  4. Thank you for sharing this Information.
    Check out the best
    entertainment unit
    shoe rack

    ReplyDelete
  5. Well Said, you have furnished the right information that will be useful to anyone at all time. Thanks for sharing your Ideas.
    Apache Spark with Scala online training
    AWS online training

    ReplyDelete

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives