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
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
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
Hi I read your post very carefully and I think you are right that a well written post. Keep on blogging..
ReplyDeleteDot Net Course | Dot Net Course in Chennai | Dot net Training in Chennai | Dot net Training Institute in Chennai | Dot net Training Institute in Velachery | Dot net Course Fees
Full Stack Developer Training Online | Full Stack web Developer Training | Full Stack Developer Certification | Full Stack Developer Course | Full Stack Developer Training
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.
ReplyDeletepython training in bangalore
Thank you for sharing this Information.
ReplyDeleteCheck out the best
entertainment unit
shoe rack
Well Said, you have furnished the right information that will be useful to anyone at all time. Thanks for sharing your Ideas.
ReplyDeleteApache Spark with Scala online training
AWS online training
.If somebody take this blog article seriously in their life, he/she can earn his living by doing blogging.thank you for this article.
ReplyDeletehadoop training in chennai
hadoop training in annanagar
salesforce training in chennai
salesforce training in annanagar
c and c plus plus course in chennai
c and c plus plus course in annanagar
machine learning training in chennai
machine learning training in annanagar
Really very nice blog information for this one and more technical skills are improve,i like that kind of post.
ReplyDeletehadoop training in chennai
hadoop training in omr
salesforce training in chennai
salesforce training in omr
c and c plus plus course in chennai
c and c plus plus course in omr
machine learning training in chennai
machine learning training in omr
This post is really good. And helps people like me ,the whole blog was really valuable
ReplyDeleteto read. It was a good article at once.
java training in chennai
java training in tambaram
aws training in chennai
aws training in tambaram
python training in chennai
python training in tambaram
selenium training in chennai
selenium training in tambaram
Great post. keep sharing such a worthy information.
ReplyDeletecontent writing course in chennai
online content writing course