How to do CRUD operations in Asp.net Web API ? (Part 2)


Hi

We can do CRUD(Create Read Update and Delete) operations in Web API as given below

Step 1: Create the new project from visual studio like this

Step 2: Create the tblEmp with Id, EmpName and EmpAddress in database as given below

Step 3: Go to the model folder and add the data model as given below

Step 4: Right click on controller folder and Add the Web API controller like this

Add the suitable Model class and data context class as per as your application

Step 5: Now your Web API controller is ready to use in any application

using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Web.Http;
using System.Web.Http.Description;
using WebApi_Sample.Models;

namespace WebApi_Sample.Controllers.Web_Api
{
    public class Emps_API_Controller : ApiController
    {
        private Database1Entities db = new Database1Entities();

        // GET: api/Emps_API_
        public IQueryable<tblEmp> GettblEmps()
        {
            return db.tblEmps;
        }

        // GET: api/Emps_API_/5
        [ResponseType(typeof(tblEmp))]
        public IHttpActionResult GettblEmp(int id)
        {
            tblEmp tblEmp = db.tblEmps.Find(id);
            if (tblEmp == null)
            {
                return NotFound();
            }

            return Ok(tblEmp);
        }

        // PUT: api/Emps_API_/5
        [ResponseType(typeof(void))]
        public IHttpActionResult PuttblEmp(int id, tblEmp tblEmp)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != tblEmp.Id)
            {
                return BadRequest();
            }

            db.Entry(tblEmp).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!tblEmpExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }

        // POST: api/Emps_API_
        [ResponseType(typeof(tblEmp))]
        public IHttpActionResult PosttblEmp(tblEmp tblEmp)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.tblEmps.Add(tblEmp);
            db.SaveChanges();

            return CreatedAtRoute("DefaultApi", new { id = tblEmp.Id }, tblEmp);
        }

        // DELETE: api/Emps_API_/5
        [ResponseType(typeof(tblEmp))]
        public IHttpActionResult DeletetblEmp(int id)
        {
            tblEmp tblEmp = db.tblEmps.Find(id);
            if (tblEmp == null)
            {
                return NotFound();
            }

            db.tblEmps.Remove(tblEmp);
            db.SaveChanges();

            return Ok(tblEmp);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

        private bool tblEmpExists(int id)
        {
            return db.tblEmps.Count(e => e.Id == id) > 0;
        }
    }
}

Step 6: Now test on browser for get method. you will get the output as given below

Summary:

In this post we learnt that how to create the CRUD operation using Entity Framework with asp.net web api. We also observed that in Asp.net Web API, we cannot give any method name similar to Asp.net MVC controller.
Method Name should always start with HTTP Verbs i.e (GET,PUT, POST and DELETE)

  • Create -> POST
  • Read -> GET
  • Update -> PUT
  • Delete -> DELETE
    Advertisement
  • Leave a Reply

    Fill in your details below or click an icon to log in:

    WordPress.com Logo

    You are commenting using your WordPress.com account. Log Out /  Change )

    Twitter picture

    You are commenting using your Twitter account. Log Out /  Change )

    Facebook photo

    You are commenting using your Facebook account. Log Out /  Change )

    Connecting to %s

    This site uses Akismet to reduce spam. Learn how your comment data is processed.