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.
11- Change the below property for EmpId column in edmx file.
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
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.
ReplyDeleteAdvanced 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
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
ReplyDeletemicrosoft azure training in bangalore
rpa training in bangalore
best rpa training in bangalore
rpa online training
Really very nice blog information for this one and more technical skills are improve,i like that kind of post.
ReplyDeleteBest Devops training in sholinganallur
Devops training in velachery
Devops training in annanagar
Devops training in tambaram
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!
ReplyDeletepython Course in Pune
python Course institute in Chennai
python Training institute in Bangalore