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 a 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 the first Web API, so we choose the Web API option and click OK.

create

Step 3

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

Model

Add EF Designer from the database and click the 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 Web 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 the 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.     public class CustomersController: ApiController {  
  11.         private SystemTestEntities db = new SystemTestEntities();  
  12.   
  13.         // GET: api/Customers    
  14.         public IQueryable < Customer > GetCustomer() {  
  15.             return db.Customer;  
  16.         }  
  17.   
  18.         // GET: api/Customers/5    
  19.         [ResponseType(typeof(Customer))]  
  20.         public IHttpActionResult GetCustomer(int id) {  
  21.             Customer customer = db.Customer.Find(id);  
  22.             if (customer == null) {  
  23.                 return NotFound();  
  24.             }  
  25.   
  26.             return Ok(customer);  
  27.         }  
  28.   
  29.         // PUT: api/Customers/5    
  30.         [ResponseType(typeof(void))]  
  31.         public IHttpActionResult PutCustomer(int id, Customer customer) {  
  32.             if (!ModelState.IsValid) {  
  33.                 return BadRequest(ModelState);  
  34.             }  
  35.   
  36.             if (id != customer.CustomerId) {  
  37.                 return BadRequest();  
  38.             }  
  39.   
  40.             db.Entry(customer).State = EntityState.Modified;  
  41.   
  42.             try {  
  43.                 db.SaveChanges();  
  44.             } catch (DbUpdateConcurrencyException) {  
  45.                 if (!CustomerExists(id)) {  
  46.                     return NotFound();  
  47.                 } else {  
  48.                     throw;  
  49.                 }  
  50.             }  
  51.   
  52.             return StatusCode(HttpStatusCode.NoContent);  
  53.         }  
  54.   
  55.         // POST: api/Customers    
  56.         [ResponseType(typeof(Customer))]  
  57.         public IHttpActionResult PostCustomer(Customer customer) {  
  58.             if (!ModelState.IsValid) {  
  59.                 return BadRequest(ModelState);  
  60.             }  
  61.   
  62.             db.Customer.Add(customer);  
  63.             db.SaveChanges();  
  64.   
  65.             return CreatedAtRoute("DefaultApi"new { id = customer.CustomerId }, customer);  
  66.         }  
  67.   
  68.         // DELETE: api/Customers/5    
  69.         [ResponseType(typeof(Customer))]  
  70.         public IHttpActionResult DeleteCustomer(int id) {  
  71.             Customer customer = db.Customer.Find(id);  
  72.             if (customer == null) {  
  73.                 return NotFound();  
  74.             }  
  75.   
  76.             db.Customer.Remove(customer);  
  77.             db.SaveChanges();  
  78.   
  79.             return Ok(customer);  
  80.         }  
  81.   
  82.         protected override void Dispose(bool disposing) {  
  83.             if (disposing) {  
  84.                 db.Dispose();  
  85.             }  
  86.             base.Dispose(disposing);  
  87.         }  
  88.   
  89.         private bool CustomerExists(int id) {  
  90.             return db.Customer.Count(e => e.CustomerId == id) > 0;  
  91.         }  
  92.     }  

    And run the Web Api project and see the result like this below,

    result

    Step 5

    ->Now we have to add an 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 the name, for ex. Customer.cs.
    1. using System;  
    2. using System.ComponentModel.DataAnnotations;  
    3.   
    4. namespace MVCPersatantion.Models {  
    5.     public class Customer {  
    6.         [Display(Name = "CustomerId")]  
    7.         public int CustomerId { get;  
    8.             set; }  
    9.         [Display(Name = "Name")]  
    10.         public string Name { get;  
    11.             set; }  
    12.         [Display(Name = "Address")]  
    13.         public string Address { get;  
    14.             set; }  
    15.         [Display(Name = "MobileNo")]  
    16.         public string MobileNo { get;  
    17.             set; }  
    18.         [Display(Name = "Birthdate")]  
    19.         [DataType(DataType.Date)]  
    20.         public DateTime Birthdate { get;  
    21.             set; }  
    22.         [Display(Name = "EmailId")]  
    23.         public string EmailId { get;  
    24.             set; }  
    25.     }  

      ->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. namespace MVCPersatantion.ViewModel {  
      3.     public class CustomerViewModel {  
      4.         public Customer customer { get;  
      5.             set; }  
      6.     }  

        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.     public class CustomerClient {  
        8.         private string Base_URL = "http://localhost:30110/api/";  
        9.   
        10.         public IEnumerable < Customer > findAll() {  
        11.             try {  
        12.                 HttpClient client = new HttpClient();  
        13.                 client.BaseAddress = new Uri(Base_URL);  
        14.                 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
        15.                 HttpResponseMessage response = client.GetAsync("customers").Result;  
        16.   
        17.                 if (response.IsSuccessStatusCode)  
        18.                     return response.Content.ReadAsAsync < IEnumerable < Customer >> ().Result;  
        19.                 return null;  
        20.             } catch {  
        21.                 return null;  
        22.             }  
        23.         }  
        24.         public Customer find(int id) {  
        25.             try {  
        26.                 HttpClient client = new HttpClient();  
        27.                 client.BaseAddress = new Uri(Base_URL);  
        28.                 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
        29.                 HttpResponseMessage response = client.GetAsync("customers/" + id).Result;  
        30.   
        31.                 if (response.IsSuccessStatusCode)  
        32.                     return response.Content.ReadAsAsync < Customer > ().Result;  
        33.                 return null;  
        34.             } catch {  
        35.                 return null;  
        36.             }  
        37.         }  
        38.         public bool Create(Customer customer) {  
        39.             try {  
        40.                 HttpClient client = new HttpClient();  
        41.                 client.BaseAddress = new Uri(Base_URL);  
        42.                 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
        43.                 HttpResponseMessage response = client.PostAsJsonAsync("customers", customer).Result;  
        44.                 return response.IsSuccessStatusCode;  
        45.             } catch {  
        46.                 return false;  
        47.             }  
        48.         }  
        49.         public bool Edit(Customer customer) {  
        50.             try {  
        51.                 HttpClient client = new HttpClient();  
        52.                 client.BaseAddress = new Uri(Base_URL);  
        53.                 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
        54.                 HttpResponseMessage response = client.PutAsJsonAsync("customers/" + customer.CustomerId, customer).Result;  
        55.                 return response.IsSuccessStatusCode;  
        56.             } catch {  
        57.                 return false;  
        58.             }  
        59.         }  
        60.         public bool Delete(int id) {  
        61.             try {  
        62.                 HttpClient client = new HttpClient();  
        63.                 client.BaseAddress = new Uri(Base_URL);  
        64.                 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
        65.                 HttpResponseMessage response = client.DeleteAsync("customers/" + id).Result;  
        66.                 return response.IsSuccessStatusCode;  
        67.             } catch {  
        68.                 return false;  
        69.             }  
        70.         }  
        71.     }  

          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 the 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 the Controllers folder and add a controller and give the name for ex.Customers 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.     public class CustomerController: Controller {  
          11.         // GET: Customer    
          12.         public ActionResult Index() {  
          13.                 CustomerClient CC = new CustomerClient();  
          14.                 ViewBag.listCustomers = CC.findAll();  
          15.   
          16.                 return View();  
          17.             }  
          18.             [HttpGet]  
          19.         public ActionResult Create() {  
          20.                 return View("Create");  
          21.             }  
          22.             [HttpPost]  
          23.         public ActionResult Create(CustomerViewModel cvm) {  
          24.             CustomerClient CC = new CustomerClient();  
          25.             CC.Create(cvm.customer);  
          26.             return RedirectToAction("Index");  
          27.         }  
          28.   
          29.         public ActionResult Delete(int id) {  
          30.                 CustomerClient CC = new CustomerClient();  
          31.                 CC.Delete(id);  
          32.                 return RedirectToAction("Index");  
          33.             }  
          34.             [HttpGet]  
          35.         public ActionResult Edit(int id) {  
          36.                 CustomerClient CC = new CustomerClient();  
          37.                 CustomerViewModel CVM = new CustomerViewModel();  
          38.                 CVM.customer = CC.find(id);  
          39.                 return View("Edit", CVM);  
          40.             }  
          41.             [HttpPost]  
          42.         public ActionResult Edit(CustomerViewModel CVM) {  
          43.             CustomerClient CC = new CustomerClient();  
          44.             CC.Edit(CVM.customer);  
          45.             return RedirectToAction("Index");  
          46.         }  
          47.     }  

            Step 8:

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

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

            Index.cshtml
            1. @{ViewBag.Title = "Index";}  
            2. <h2>Index</h2>  
            3. <div align="center">  
            4.     <a href="@Url.Action(" Create"," Customer ")"> Add New Customer </a> <br /> <br />  
            5.     <table cellpadding="2" class="table" cellspacing="2" border="1">  
            6.         <tr class="btn-primary">  
            7.             <th> CustomerId </th>  
            8.             <th> Name </th>  
            9.             <th> Address </th>  
            10.             <th> MobileNo </th>  
            11.             <th> Birthdate </th>  
            12.             <th> EmailId </th>  
            13.             <th> Action </th>  
            14.         </tr>  
            15.         @foreach(var Cust in ViewBag.listCustomers) { <tr class="btn-success">  
            16.             <td>@Cust.CustomerId </td>  
            17.             <td>@Cust.Name </td>  
            18.             <td>@Cust.Address </td>  
            19.             <td>@Cust.MobileNo </td>  
            20.             <td>@Cust.Birthdate.ToString("dd/MM/yyyy") </td>  
            21.             <td>@Cust.EmailId </td>  
            22.             <td>  
            23.                 <a onclick="return confirm('Do you want to Delete?')" href="@Url.Action(" Delete "," Customer ",new {idCust.CustomerId})">Delete</a> || <a href="@Url.Action(" Edit "," Customer ",new { id = Cust.CustomerId    
            24. })    
            25. ">Edit</a> </td>  
            26.         </tr>  
            27.         }  
            28.     </table>  
            29. </div> 
            ->Now we have to create a Create page.

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

            Create.cshtml
            1. @{ViewBag.Title = "Create";  
            2. }  
            3. @model MVCPersatantion.ViewModel.CustomerViewModel  
            4. <h2> Create </h2>  
            5. <div align="center">  
            6.     @using(Html.BeginForm("create", "Customer", FormMethod.Post))  
            7.     {  
            8.     <table class="table">  
            9.         <tr>  
            10.             <td>@Html.LabelFor(model => model.customer.Name) </td>  
            11.             <td>@Html.TextBoxFor(model => model.customer.Name) </td>  
            12.         </tr>  
            13.         <tr>  
            14.             <td>@Html.LabelFor(model => model.customer.Address) </td>  
            15.             <td>@Html.TextBoxFor(model => model.customer.Address) </td>  
            16.         </tr>  
            17.         <tr>  
            18.             <td>@Html.LabelFor(model => model.customer.MobileNo) </td>  
            19.             <td>@Html.TextBoxFor(model => model.customer.MobileNo) </td>  
            20.         </tr>  
            21.         <tr>  
            22.             <td>@Html.LabelFor(model => model.customer.Birthdate) </td>  
            23.             <td>@Html.TextBoxFor(model => model.customer.Birthdate) </td>  
            24.         </tr>  
            25.         <tr>  
            26.             <td>@Html.LabelFor(model => model.customer.EmailId) </td>  
            27.             <td>@Html.TextBoxFor(model => model.customer.EmailId) </td>  
            28.         </tr>  
            29.         <tr>  
            30.             <td></td>  
            31.             <td><input type="submit" value="Save" /></td>  
            32.         </tr>  
            33.     </table>  
            34.     } </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. @ { ViewBag.Title = "Edit";}  
              2. @model MVCPersatantion.ViewModel.CustomerViewModel  
              3. <h2> Edit </h2>  
              4. <div align="center" width="500px"> @using(Html.BeginForm("Edit", "Customer", FormMethod.Post))  
              5.     {  
              6.     <table class="table" width="400px" cellpadding="20">  
              7.         <tr class="btn-default">  
              8.             <td> @Html.LabelFor(model => model.customer.Name) </td>  
              9.             <td> @Html.TextBoxFor(model => model.customer.Name) </td>  
              10.         </tr>  
              11.         <tr>  
              12.             <td> @Html.LabelFor(model => model.customer.Address) </td>  
              13.             <td> @Html.TextBoxFor(model => model.customer.Address) </td>  
              14.         </tr>  
              15.         <tr>  
              16.             <td> @Html.LabelFor(model => model.customer.MobileNo) </td>  
              17.             <td> @Html.TextBoxFor(model => model.customer.MobileNo) </td>  
              18.         </tr>  
              19.         <tr>  
              20.             <td> @Html.LabelFor(model => model.customer.Birthdate) </td>  
              21.             <td> @Html.TextBoxFor(model => model.customer.Birthdate) </td>  
              22.         </tr>  
              23.         <tr>  
              24.             <td> @Html.LabelFor(model => model.customer.EmailId) </td>  
              25.             <td> @Html.TextBoxFor(model => model.customer.EmailId) </td>  
              26.         </tr>  
              27.         <tr>  
              28.             <td> </td>  
              29.             <td> <input type="submit" value="Save" /> & nbsp; <a class="btn-primary" href="@Url.Action(" Index "," Customer ")"> Back </a> @Html.HiddenFor(model => model.customer.CustomerId) </td>  
              30.         </tr>  
              31.     </table>  
              32.     } </div> 
                ->Finally we have completed it so now we execute the program but one thing here is we have to run both web API and MVC projects so first, we have to set this that runs both programs.

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

                properties


                ->So next, we go to Startup Project option and select the multiple startup projects 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


                Click ok.

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


                Similar Articles