Saturday, 1 August 2015

Web Api CRUD Operations without Repository Using Entity Framework

CRUD stands for Create ,Read, Update and Delete, these are four basic standard database operations . How we implement these CRUD operations in  asp.net web api.
create webapi application
In the New ASP.NET MVC 4 Project dialog, select Web API and click OK.


I will take one sample  Employee table with valid data
create one Employee table in database
Create Table Employee
(
EmployeeID int PRIMARY KEY identity(1,1),
Name varchar(50),
Age int,
Salary int
)
insert into Employee values('sasishekaraya',25,40000)

like this insert 2 more records

create one model name it as Employee

model is an object that represents the data in your application. In ASP.NET Web API, you can use strongly typed CLR objects as models, and they will automatically be serialized to XML or JSON for the client.
           
public class Employee
    {
        public int EmployeeID { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public int Salary { get; set; }
    }


The Database context class is Enity framework object.This class contains all collections of entities that map to tables in the database. The controller has to be access this Database context class so that it can perform CRUD operations.

Add database context class

public class DatabaseContext:DbContext
    {
        public DatabaseContext()
            : base("Name=DatabaseContext")
        {
            Database.SetInitializer<DatabaseContext>(null);
        }
        public DbSet<Employee> employee { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<Employee>().ToTable("employee");
        }

    }



Install Entiry Framework From Manage NugetPackage

DbSet class is one of most important object in Entity framework.DbSet represents collection of entities.DbSet<TEntity> is generic version.


In web.config

<connectionStrings>
  
  <add name="DataBaseContext" connectionString="Data Source=SQLEXPRESS;Initial Catalog=Sample;Persist Security Info=True;User ID=sa;Password=007" providerName="System.Data.SqlClient" />
  </connectionStrings>

Add a web api controller,it handles the incoming  http requests

Create a controller name it as Employee

In Solution Explorer, right-click the the Controllers folder. Select Add and then select Controller.

The Employee API will expose several "read" actions as HTTP GET methods. Each action will correspond to a method in the ProductsController class.

public class EmployeeController : ApiController
    {
        DatabaseContext db = new DatabaseContext();

//This method is used to get Employee Details based on EmployeedID
        public Employee GetEmp(int id)
        {
            var emp = db.employee.FirstOrDefault(p => p.EmployeeID == id);
            return emp;
        }


//This method is used to add Employee to Database
        [HttpPost]                             
        public string AddEmployee(Employee emp)
        {
            db.employee.Add(emp);
            db.SaveChanges();
            return "Success";
        }
Or to post employee details to database
[HttpPost]
        public HttpResponseMessage AddEmployee(Employee emp)
        {
            db.employee.Add(emp);
            db.SaveChanges();
            var response = Request.CreateResponse<Employee>(HttpStatusCode.Created, emp);

            string uri = Url.Link("DefaultApi", new { id = emp.EmployeeID });
            response.Headers.Location = new Uri(uri);
            return response;

        }

Notice that the method return type is now HttpResponseMessage. By returning an HttpResponseMessage instead of a Employee, we can control the details of the HTTP response message, including the status code and the Location header.




//This method is used to get list of employees
        public List<Employee> GetAllEmployees()
        {
            var lstemps = db.employee.ToList();
            return lstemps;
        }
    }


This method is used to Update Employee Details
 //To update Employee Details
        [HttpPut]
        public string UpdateEmployee(Employee emp)
        {
            Employee empdetails = db.employee.Find(emp.EmployeeID);
            empdetails.Age = emp.Age;
            empdetails.Name = emp.Name;
            empdetails.Salary = emp.Salary;           
            db.SaveChanges();
            return "Success";
        }

This method is used to remove Employee Details


// To remove employee Details
        public string DeleteEmployee(int id)
        {
            Employee empdetails = db.employee.Find(id);
            db.employee.Remove(empdetails);
            db.SaveChanges();
            return   "Success";
        }

db.SaveChanges() method is used to save the changes to the database.

Employee Controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApiCRUD.Models;

namespace WebApiCRUD.Controllers
{
    public class EmployeeController : ApiController
    {
        DatabaseContext db = new DatabaseContext();
        public Employee GetEmp(int id)
        {
            var emp = db.employee.FirstOrDefault(p => p.EmployeeID == id);
            return emp;
        }
        [HttpPost]
        public HttpResponseMessage AddEmployee(Employee emp)
        {
            db.employee.Add(emp);
            db.SaveChanges();
            var response = Request.CreateResponse<Employee>(HttpStatusCode.Created, emp);

            string uri = Url.Link("DefaultApi", new { id = emp.EmployeeID });
            response.Headers.Location = new Uri(uri);
            return response;

        }
        public List<Employee> GetAllEmployees()
        {
            var lstemps = db.employee.ToList();
            return lstemps;
        }

        //To update Employee Details
        [HttpPut]
        public string UpdateEmployee(Employee emp)
        {
            Employee empdetails = db.employee.Find(emp.EmployeeID);
            empdetails.Age = emp.Age;
            empdetails.Name = emp.Name;
            empdetails.Salary = emp.Salary;           
            db.SaveChanges();
            return "Success";
        }
        // To remove employee Details
        public string DeleteEmployee(int id)
        {
            Employee empdetails = db.employee.Find(id);
            db.employee.Remove(empdetails);
            db.SaveChanges();
            return   "Success";
        }

    }
}




Test api

Rightclick on project =>manage nugget package=>search as testclient


we will get A ‘simple Test Client For Asp.Net Web Api’  click on install




Now run the Application




Click on the GetEmployee



click on TestApi





give the id and click on send you will get  the following result



tags:Web api curd operations,create ,update and delete in web api,curd operations web api 2.2 , curd operations in asp.net web api,sample web api application,realtime web api application and curd operations,web api headers and post data, web api employee curd operations,employee web api,employee asp.net web api.