In this article, I’m explaining the asp.net web api – how to create and consume with

CRUD operation (Create, Read, Update, Delete) using Entity Framework in Asp.Net

Mvc 4.

Step 1

First create a table named “Customer” in the database like this:

CRUD Operation using Asp.Net Web API and Entity Framework in Asp.Net Mvc 4

Step 2

Now create a basic asp.net mvc 4 application and add a class named “Customer”

like this:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
 
namespace MvcWebApi.Models
{
    [Table("Customer")]
    public class Customer
    {
        [Key]
        public int CustID { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        public string ContactNo { get; set; }
    }
}

Step 2

Now add another class named “CustomerContext” like this:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
 
namespace MvcWebApi.Models
{
    public class CustomerContext : DbContext
    {
        public DbSet<Customer> Customers { get; set; }
    }
}

Step 3

Now add a controller named “ValuesController” to the project like this:

using MvcWebApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
 
namespace MvcWebApi.Controllers
{
    public class ValuesController : ApiController
    {
        CustomerContext db = new CustomerContext();
 
        public IEnumerable<Customer> Get()
        {
            return db.Customers.ToList();
        }
 
        // GET api/values/5
        public Customer Get(int id)
        {
            return db.Customers.Find(id);
            //return "value";
        }
        // POST api/values
        public void Post(List<string> val        {
            try
            {
                Customer obj = new Customer();
                obj.Name = val[0];
                obj.Address = val[1];
                obj.ContactNo = val[2];
                db.Customers.Add(obj);
                db.SaveChanges();
            }
            catch (Exception) { }
        }
        // PUT api/values/5
        public void Put(int id, Customer obj)
        {
            try
            {
                db.Entry(obj).State = System.Data.EntityState.Modified;
                db.SaveChanges();
            }
            catch (Exception) { }
        }
        //This method for update through Json
        public void Put(List<string> val)
        {
            try
            {
                int id = Convert.ToInt32(val[3]);
                Customer obj = db.Customers.Find(id);
                obj.Name = val[0];
                obj.Address = val[1];
                obj.ContactNo = val[2];
                db.Customers.Add(obj);
                db.Entry(obj).State = System.Data.EntityState.Modified;
                db.SaveChanges();
            }
            catch (Exception) { }
        }
        // DELETE api/values/5
        public void Delete(int id)
        {
            Customer obj = db.Customers.Find(id);
            db.Customers.Remove(obj);
            db.SaveChanges();
        }
 
    }
}
 

Changed its base class from controller to ApiController using the namespace System.Web.Http,

Get() Method – this method will give the list of records.

Get(int id) Method – this method will give the specific record using the id.

Post() Method – this method will add a new record.

Put() Method – this method will edit a specific record using the id.

Delete() Method – this method will delete a record using the id.

Step 4

Now add another controller named “HomeController” like this:

CRUD Operation using Asp.Net Web API and Entity Framework in Asp.Net Mvc 4

This will create the controller with 5 views (Create, Delete, Details, Edit, Index)

Change the code of the controller like below:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcWebApi.Models;
 
namespace MvcWebApi.Controllers
{
    public class HomeController : Controller
    {
        ValuesController db = new ValuesController();
 
        public ActionResult Index()
        {
            return View(db.Get());
        }
 
        //
        // GET: /Home/Details/5
 
        public ActionResult Details(int id = 0)
        {
            Customer customer = db.Get(id);
            if (customer == null)
            {
                return HttpNotFound();
            }
            return View(customer);
        }
 
        //
        // GET: /Home/Create
 
        public ActionResult Create()
        {
            return View();
        }
 
        //
        // POST: /Home/Create
 
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Customer customer)
        {
            if (ModelState.IsValid)
            {
                List<string> customerList = new List<string>();
                customerList.Add(customer.Name);
                customerList.Add(customer.Address);
                customerList.Add(customer.ContactNo);
                db.Post(customerList);
                return RedirectToAction("Index");
            }
 
            return View(customer);
        }
 
        //
        // GET: /Home/Edit/5
 
        public ActionResult Edit(int id = 0)
        {
            Customer customer = db.Get(id);
            if (customer == null)
            {
                return HttpNotFound();
            }
            return View(customer);
        }
 
        //
        // POST: /Home/Edit/5
 
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(int id, Customer customer)
        {
            if (ModelState.IsValid)
            {
                db.Put(id, customer);
                return RedirectToAction("Index");
            }
            return View(customer);
        }
 
        //
        // GET: /Home/Delete/5
 
        public ActionResult Delete(int id = 0)
        {
            Customer customer = db.Get(id);
            if (customer == null)
            {
                return HttpNotFound();
            }
            return View(customer);
        }
 
        //
        // POST: /Home/Delete/5
 
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            db.Delete(id);
            return RedirectToAction("Index");
        }
 
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}

Step 5

Now add the connection string in the web.config file:

<connectionStrings>
      <add name="CustomerContext" connectionString="Data Source=Uttam-PC4;Initial Catalog=SumitTesting;user id = userid;password=password;" providerName="System.Data.SqlClient"/>
  </connectionStrings>

 

Now your solution explorer will look like this:

CRUD Operation using Asp.Net Web API and Entity Framework in Asp.Net Mvc 4

Output

Now run the application:

CRUD Operation using Asp.Net Web API and Entity Framework in Asp.Net Mvc 4

 

Click on Create New – to add a new record:

CRUD Operation using Asp.Net Web API and Entity Framework in Asp.Net Mvc 4

CRUD Operation using Asp.Net Web API and Entity Framework in Asp.Net Mvc 4

Now click on edit – to edit a record:

CRUD Operation using Asp.Net Web API and Entity Framework in Asp.Net Mvc 4

CRUD Operation using Asp.Net Web API and Entity Framework in Asp.Net Mvc 4

 

Now click on details – to show the record details:

CRUD Operation using Asp.Net Web API and Entity Framework in Asp.Net Mvc 4

Now click on delete – to delete a record:

CRUD Operation using Asp.Net Web API and Entity Framework in Asp.Net Mvc 4

CRUD Operation using Asp.Net Web API and Entity Framework in Asp.Net Mvc 4

 

  Modified On Nov-30-2017 06:52:37 AM

Leave Comment