CRUD ASP.NET Web API With Entity Framework In ASP.NET MVC

Here are the steps, 

Step 1

Create a table, for example, see below with snapshot.

Create

Step 2

->Open Visual studio and take a new project.

->Choose ASP.NET Web Application and give name Ex.CRUDWebApiExam and click ok .

project

We have to create first Web API, so we choose Web API option and click OK.

create

Step 3

Now we have to add class so for this, we right click of web api project and add ADO.NET Entity Data Model,

Model

Add EF Designer from database and click Next button.

 EF Designer

Add click new connection option and give the server name and select database and click Test Connection and click ok.

connection

Click Next and select the table which you want and click ok.

Next

Click Finish.

Step 4

Now we have to add Wep Api controller, So right click on controllers folder,

controllers

Select 'Web Api Controller with views, using Entity framework'.

Controller

Click Add.

Select the Model Class Name Exam. Customer(In my project).

Select Data context class, Exam. SystemTestEntity (In my project).
 
Give Controller Name Exam. Customer.

Click Add.

Add

Note - After that it automatically generates CustomerController.cs like this.
  1. using System.Data.Entity;  
  2. using System.Data.Entity.Infrastructure;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Web.Http;  
  6. using System.Web.Http.Description;  
  7. using CRUDWebApiExam.Models;  
  8.   
  9. namespace CRUDWebApiExam.Controllers  
  10. {  
  11.     public class CustomersController : ApiController  
  12.     {  
  13.         private SystemTestEntities db = new SystemTestEntities();  
  14.   
  15.         // GET: api/Customers  
  16.         public IQueryable<Customer> GetCustomer()  
  17.         {  
  18.             return db.Customer;  
  19.         }  
  20.   
  21.         // GET: api/Customers/5  
  22.         [ResponseType(typeof(Customer))]  
  23.         public IHttpActionResult GetCustomer(int id)  
  24.         {  
  25.             Customer customer = db.Customer.Find(id);  
  26.             if (customer == null)  
  27.             {  
  28.                 return NotFound();  
  29.             }  
  30.   
  31.             return Ok(customer);  
  32.         }  
  33.   
  34.         // PUT: api/Customers/5  
  35.         [ResponseType(typeof(void))]  
  36.         public IHttpActionResult PutCustomer(int id, Customer customer)  
  37.         {  
  38.             if (!ModelState.IsValid)  
  39.             {  
  40.                 return BadRequest(ModelState);  
  41.             }  
  42.   
  43.             if (id != customer.CustomerId)  
  44.             {  
  45.                 return BadRequest();  
  46.             }  
  47.   
  48.             db.Entry(customer).State = EntityState.Modified;  
  49.   
  50.             try  
  51.             {  
  52.                 db.SaveChanges();  
  53.             }  
  54.             catch (DbUpdateConcurrencyException)  
  55.             {  
  56.                 if (!CustomerExists(id))  
  57.                 {  
  58.                     return NotFound();  
  59.                 }  
  60.                 else  
  61.                 {  
  62.                     throw;  
  63.                 }  
  64.             }  
  65.   
  66.             return StatusCode(HttpStatusCode.NoContent);  
  67.         }  
  68.   
  69.         // POST: api/Customers  
  70.         [ResponseType(typeof(Customer))]  
  71.         public IHttpActionResult PostCustomer(Customer customer)  
  72.         {  
  73.             if (!ModelState.IsValid)  
  74.             {  
  75.                 return BadRequest(ModelState);  
  76.             }  
  77.   
  78.             db.Customer.Add(customer);  
  79.             db.SaveChanges();  
  80.   
  81.             return CreatedAtRoute("DefaultApi"new { id = customer.CustomerId }, customer);  
  82.         }  
  83.   
  84.         // DELETE: api/Customers/5  
  85.         [ResponseType(typeof(Customer))]  
  86.         public IHttpActionResult DeleteCustomer(int id)  
  87.         {  
  88.             Customer customer = db.Customer.Find(id);  
  89.             if (customer == null)  
  90.             {  
  91.                 return NotFound();  
  92.             }  
  93.   
  94.             db.Customer.Remove(customer);  
  95.             db.SaveChanges();  
  96.   
  97.             return Ok(customer);  
  98.         }  
  99.   
  100.         protected override void Dispose(bool disposing)  
  101.         {  
  102.             if (disposing)  
  103.             {  
  104.                 db.Dispose();  
  105.             }  
  106.             base.Dispose(disposing);  
  107.         }  
  108.   
  109.         private bool CustomerExists(int id)  
  110.         {  
  111.             return db.Customer.Count(e => e.CustomerId == id) > 0;  
  112.         }  
  113.     }  
  114.   
  115. }  
And run the Web Api project and see the result like this below,

result
Step 5

->Now we have to add MVC project for consuming the web api services, So first we have to add a model class, so here we took Customer class. For this we right click models folder and add class and give name, for exm. Customer.cs.
  1. using System;  
  2. using System.ComponentModel.DataAnnotations;  
  3.   
  4. namespace MVCPersatantion.Models  
  5. {  
  6.     public class Customer  
  7.     {  
  8.         [Display(Name = "CustomerId")]  
  9.         public int CustomerId { getset; }  
  10.         [Display(Name = "Name")]  
  11.         public string Name { getset; }  
  12.         [Display(Name = "Address")]  
  13.         public string Address { getset; }  
  14.         [Display(Name = "MobileNo")]  
  15.         public string MobileNo { getset; }  
  16.         [Display(Name = "Birthdate")]  
  17.         [DataType(DataType.Date)]  
  18.         public DateTime Birthdate { getset; }  
  19.         [Display(Name = "EmailId")]  
  20.         public string EmailId { getset; }  
  21.          
  22.     }  
  23.   
  24. }  
->Ok we added customer class so next thing is we have to add ViewModel folder and add a class for exm.CustomerViewModel.cs,
  1. using MVCPersatantion.Models;  
  2.   
  3. namespace MVCPersatantion.ViewModel  
  4. {  
  5.     public class CustomerViewModel  
  6.     {  
  7.         public Customer customer { getset; }  
  8.     }  
  9.   
  10. }  
Step 6

We have to add a class for consuming the web service for this thing so we add a class and give the name exam. CustomerClient.cs for this just right click on models folder and add below code.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Net.Http;  
  4. using System.Net.Http.Headers;  
  5.   
  6. namespace MVCPersatantion.Models  
  7. {  
  8.     public class CustomerClient  
  9.     {  
  10.         private string Base_URL = "http://localhost:30110/api/";  
  11.   
  12.         public IEnumerable<Customer> findAll()  
  13.         {  
  14.             try  
  15.             {  
  16.                 HttpClient client = new HttpClient();  
  17.                 client.BaseAddress = new Uri(Base_URL);  
  18.                 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
  19.                 HttpResponseMessage response = client.GetAsync("customers").Result;  
  20.   
  21.                 if (response.IsSuccessStatusCode)  
  22.                     return response.Content.ReadAsAsync<IEnumerable<Customer>>().Result;  
  23.                 return null;  
  24.             }  
  25.             catch  
  26.             {  
  27.                 return null;  
  28.             }  
  29.         }  
  30.         public Customer find(int id)  
  31.         {  
  32.             try  
  33.             {  
  34.                 HttpClient client = new HttpClient();  
  35.                 client.BaseAddress = new Uri(Base_URL);  
  36.                 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
  37.                 HttpResponseMessage response = client.GetAsync("customers/" + id).Result;  
  38.   
  39.                 if (response.IsSuccessStatusCode)  
  40.                     return response.Content.ReadAsAsync<Customer>().Result;  
  41.                 return null;  
  42.             }  
  43.             catch  
  44.             {  
  45.                 return null;  
  46.             }  
  47.         }  
  48.         public bool Create(Customer customer)  
  49.         {  
  50.             try  
  51.             {  
  52.                 HttpClient client = new HttpClient();  
  53.                 client.BaseAddress = new Uri(Base_URL);  
  54.                 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
  55.                 HttpResponseMessage response = client.PostAsJsonAsync("customers", customer).Result;  
  56.                 return response.IsSuccessStatusCode;  
  57.             }  
  58.             catch  
  59.             {  
  60.                 return false;  
  61.             }  
  62.         }  
  63.         public bool Edit(Customer customer)  
  64.         {  
  65.             try  
  66.             {  
  67.                 HttpClient client = new HttpClient();  
  68.                 client.BaseAddress = new Uri(Base_URL);  
  69.                 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
  70.                 HttpResponseMessage response = client.PutAsJsonAsync("customers/" + customer.CustomerId, customer).Result;  
  71.                 return response.IsSuccessStatusCode;  
  72.             }  
  73.             catch  
  74.             {  
  75.                 return false;  
  76.             }  
  77.         }  
  78.         public bool Delete(int id)  
  79.         {  
  80.             try  
  81.             {  
  82.                 HttpClient client = new HttpClient();  
  83.                 client.BaseAddress = new Uri(Base_URL);  
  84.                 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
  85.                 HttpResponseMessage response = client.DeleteAsync("customers/" + id).Result;  
  86.                 return response.IsSuccessStatusCode;  
  87.             }  
  88.             catch  
  89.             {  
  90.                 return false;  
  91.             }  
  92.         }  
  93.     }  
  94.   
  95. }  
Note - We see here that in every method some codes are repeating, so we can declare only one time and we can use that but I wrote a separate one for understanding purposes

->First we see in first line I gave base url. see below
private string Base_URL = "http://localhost:30110/api/";

So I want to say that this base_url value is the web api service url,
url
->After we write methods for Insert ,Update,Delete,Select one by one

Step 7

We have to add a controller, so for this right click on Controllers folder and add a controller and give the name for ex.Customer and write the code and call the service client method.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using MVCPersatantion.Models;  
  7. using MVCPersatantion.ViewModel;  
  8.   
  9. namespace MVCPersatantion.Controllers  
  10. {  
  11.     public class CustomerController : Controller  
  12.     {  
  13.         // GET: Customer  
  14.         public ActionResult Index()  
  15.         {  
  16.             CustomerClient CC = new CustomerClient();  
  17.             ViewBag.listCustomers = CC.findAll();  
  18.   
  19.             return View();  
  20.         }  
  21.         [HttpGet]  
  22.         public ActionResult Create()  
  23.         {  
  24.             return View("Create");  
  25.         }  
  26.         [HttpPost]  
  27.         public ActionResult Create(CustomerViewModel cvm)  
  28.         {  
  29.             CustomerClient CC = new CustomerClient();  
  30.             CC.Create(cvm.customer);  
  31.             return RedirectToAction("Index");  
  32.         }  
  33.          
  34.         public ActionResult Delete(int id)  
  35.         {  
  36.             CustomerClient CC = new CustomerClient();  
  37.             CC.Delete(id);  
  38.             return RedirectToAction("Index");  
  39.         }  
  40.         [HttpGet]  
  41.         public ActionResult Edit(int id)  
  42.         {  
  43.             CustomerClient CC = new CustomerClient();  
  44.             CustomerViewModel CVM = new CustomerViewModel();  
  45.             CVM.customer = CC.find(id);  
  46.             return View("Edit",CVM);  
  47.         }  
  48.         [HttpPost]  
  49.         public ActionResult Edit(CustomerViewModel CVM)  
  50.         {  
  51.             CustomerClient CC = new CustomerClient();  
  52.             CC.Edit(CVM.customer);  
  53.             return RedirectToAction("Index");  
  54.         }  
  55.     }  
  56.   
  57. }  
Step 8:

->Now we have to create view page so first create Index page.

->For this right click on index method in Customer controller and add view and write below code

Index.cshtml
  1. @ {  
  2.     ViewBag.Title = "Index";  
  3. }  
  4.   
  5. <  
  6. h2 > Index < /h2>  
  7.   
  8. <  
  9. div align = "center" >  
  10.     <  
  11.     a href = "@Url.Action("  
  12. Create ","  
  13. Customer ")" > Add New Customer < /a> <  
  14.     br / > < br / >  
  15.     <  
  16.     table cellpadding = "2"  
  17. class = "table"  
  18. cellspacing = "2"  
  19. border = "1" >  
  20.     <  
  21.     tr class = "btn-primary" >  
  22.     <  
  23.     th > CustomerId < /th> <  
  24.     th > Name < /th> <  
  25.     th > Address < /th> <  
  26.     th > MobileNo < /th> <  
  27.     th > Birthdate < /th> <  
  28.     th > EmailId < /th> <  
  29.     th > Action < /th> <  
  30.     /tr>  
  31. @foreach(var Cust in ViewBag.listCustomers) { <  
  32.     tr class = "btn-success" >  
  33.         <  
  34.         td >  
  35.         @Cust.CustomerId <  
  36.         /td> <  
  37.         td >  
  38.         @Cust.Name <  
  39.         /td> <  
  40.         td >  
  41.         @Cust.Address <  
  42.         /td> <  
  43.         td >  
  44.         @Cust.MobileNo <  
  45.         /td> <  
  46.         td >  
  47.         @Cust.Birthdate.ToString("dd/MM/yyyy") <  
  48.         /td> <  
  49.         td >  
  50.         @Cust.EmailId <  
  51.         /td> <  
  52.         td >  
  53.         <  
  54.         a onclick = "return confirm('Do you want to Delete?')"  
  55.     href = "@Url.Action("  
  56.     Delete ","  
  57.     Customer ",new {  
  58.         id  
  59.             = Cust.CustomerId  
  60.     })  
  61. ">Delete</a> ||  
  62. <  
  63. a href = "@Url.Action("  
  64. Edit ","  
  65. Customer ",new {  
  66. id  
  67.     = Cust.CustomerId  
  68. })  
  69. ">Edit</a> <  
  70. /td>  
  71.   
  72. <  
  73. /tr>  
  74. <  
  75. /table> <  
  76. /div>  
->Now we have to create Create page.

->For this right click on create method in Customer controller and add view and write below code.

Create.cshtml
  1. @ {  
  2.     ViewBag.Title = "Create";  
  3. }  
  4. @model MVCPersatantion.ViewModel.CustomerViewModel  
  5.   
  6.     <  
  7.     h2 > Create < /h2>  
  8.   
  9. <  
  10. div align = "center" >  
  11.     @using(Html.BeginForm("create", "Customer", FormMethod.Post)) { <  
  12.         table class = "table" >  
  13.             <  
  14.             tr >  
  15.             <  
  16.             td >  
  17.             @Html.LabelFor(model => model.customer.Name) <  
  18.             /td>  
  19.   
  20.         <  
  21.         td >  
  22.             @Html.TextBoxFor(model => model.customer.Name) <  
  23.             /td> <  
  24.             /tr> <  
  25.             tr >  
  26.             <  
  27.             td >  
  28.             @Html.LabelFor(model => model.customer.Address) <  
  29.             /td>  
  30.   
  31.         <  
  32.         td >  
  33.             @Html.TextBoxFor(model => model.customer.Address) <  
  34.             /td> <  
  35.             /tr> <  
  36.             tr >  
  37.             <  
  38.             td >  
  39.             @Html.LabelFor(model => model.customer.MobileNo) <  
  40.             /td>  
  41.   
  42.         <  
  43.         td >  
  44.             @Html.TextBoxFor(model => model.customer.MobileNo) <  
  45.             /td> <  
  46.             /tr> <  
  47.             tr >  
  48.             <  
  49.             td >  
  50.             @Html.LabelFor(model => model.customer.Birthdate) <  
  51.             /td>  
  52.   
  53.         <  
  54.         td >  
  55.             @Html.TextBoxFor(model => model.customer.Birthdate) <  
  56.             /td> <  
  57.             /tr> <  
  58.             tr >  
  59.             <  
  60.             td >  
  61.             @Html.LabelFor(model => model.customer.EmailId) <  
  62.             /td>  
  63.   
  64.         <  
  65.         td >  
  66.             @Html.TextBoxFor(model => model.customer.EmailId) <  
  67.             /td> <  
  68.             /tr> <  
  69.             tr >  
  70.             <  
  71.             td >  
  72.   
  73.             <  
  74.             /td>  
  75.   
  76.         <  
  77.         td >  
  78.             <  
  79.             input type = "submit"  
  80.         value = "Save" / >  
  81.             <  
  82.             /td> <  
  83.             /tr> <  
  84.             /table>  
  85.     } <  
  86.     /div>  
->Now we have to create edit view page.

->For this right click on Edit method in Customer controller and add view and write below code

Edit.cshtml
  1. @ {  
  2.     ViewBag.Title = "Edit";  
  3. }  
  4. @model MVCPersatantion.ViewModel.CustomerViewModel  
  5.   
  6.     <  
  7.     h2 > Edit < /h2> <  
  8.     div align = "center"  
  9. width = "500px" >  
  10.     @using(Html.BeginForm("Edit", "Customer", FormMethod.Post)) { <  
  11.         table class = "table"  
  12.         width = "400px"  
  13.         cellpadding = "20" >  
  14.             <  
  15.             tr class = "btn-default" >  
  16.             <  
  17.             td >  
  18.             @Html.LabelFor(model => model.customer.Name) <  
  19.             /td>  
  20.   
  21.         <  
  22.         td >  
  23.             @Html.TextBoxFor(model => model.customer.Name) <  
  24.             /td> <  
  25.             /tr> <  
  26.             tr >  
  27.             <  
  28.             td >  
  29.             @Html.LabelFor(model => model.customer.Address) <  
  30.             /td>  
  31.   
  32.         <  
  33.         td >  
  34.             @Html.TextBoxFor(model => model.customer.Address) <  
  35.             /td> <  
  36.             /tr> <  
  37.             tr >  
  38.             <  
  39.             td >  
  40.             @Html.LabelFor(model => model.customer.MobileNo) <  
  41.             /td>  
  42.   
  43.         <  
  44.         td >  
  45.             @Html.TextBoxFor(model => model.customer.MobileNo) <  
  46.             /td> <  
  47.             /tr> <  
  48.             tr >  
  49.             <  
  50.             td >  
  51.             @Html.LabelFor(model => model.customer.Birthdate) <  
  52.             /td>  
  53.   
  54.         <  
  55.         td >  
  56.             @Html.TextBoxFor(model => model.customer.Birthdate) <  
  57.             /td> <  
  58.             /tr> <  
  59.             tr >  
  60.             <  
  61.             td >  
  62.             @Html.LabelFor(model => model.customer.EmailId) <  
  63.             /td>  
  64.   
  65.         <  
  66.         td >  
  67.             @Html.TextBoxFor(model => model.customer.EmailId) <  
  68.             /td> <  
  69.             /tr> <  
  70.             tr >  
  71.             <  
  72.             td > < /td>  
  73.   
  74.         <  
  75.         td >  
  76.             <  
  77.             input type = "submit"  
  78.         value = "Save" / > & nbsp; < a class = "btn-primary"  
  79.         href = "@Url.Action("  
  80.         Index ","  
  81.         Customer ")" > Back < /a>  
  82.         @Html.HiddenFor(model => model.customer.CustomerId) <  
  83.             /td> <  
  84.             /tr> <  
  85.             /table>  
  86.     } <  
  87.     /div>  
->Finally we have completed it so now we execute the program but one thing here is we have to run the both web api and mvc projects so first we have to set this that runs both programs.

->So for set this, we right click on solution and go to properties like this.

properties

->So next, we go to Startup Project option and select the multiple startup project and go to Action and set 'Start' for both project, that's all

->So finally execute the program and see the result and see the functionality of crud operation.

First see for the select result,
result

See for the Insert,

Insert

See for Update,

Update

See for delete,

delete

Clic ok.

I hope you enjoyed this. Thank you for looking at the example.