Asynchronous Controller of Web API 2 With Entity Framework 6: Put and Delete Method

In our previous two articles we saw to how do Get and Post operations within a Web API controller asynchronously using Entity Framework 6. You can read them here.

Asynchronous Controller of Web API 2 With Entity Framework 6: Get() Method
Asynchronous Controller of Web API 2 With Entity Framework 6: Post Method


As promised, in this article we will see how to update the DB using the Entity Framework using a Put method. Here is the implementation of the Put method in the Web API. It takes two parameters, the first one is the key that will point to the table's primary key, it will come from a URL and the second parameter is the actual object that carries a new property.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Http;  
  6. using System.Web.Mvc;  
  7. using System.Threading.Tasks;  
  8. using System.Web.Http.Description;  
  9. using System.Data.Entity.Infrastructure;  
  10. using System.Net;  
  11. namespace WebAPI.Controllers  
  12. {  
  13.     public class AsyncPersonController : ApiController  
  14.     {  
  15.         private efDBEntities db = new efDBEntities();  
  16.         public async Task<IHttpActionResult> Putcompany([FromUri] int id, [FromBody] company company)  
  17.         {  
  18.             if (!ModelState.IsValid)  
  19.             {  
  20.                 return BadRequest(ModelState);  
  21.             }  
  22.             try  
  23.             {  
  24.                 var tmpCompany = db.company.Where(cn => cn.cid == id).FirstOrDefault();  
  25.                 tmpCompany.company_name = company.company_name;  
  26.                 await db.SaveChangesAsync();  
  27.             }  
  28.             catch (DbUpdateConcurrencyException)  
  29.             {  
  30.                 if (!companyExists(id))  
  31.                 {  
  32.                     return NotFound();  
  33.                 }  
  34.                 else  
  35.                 {  
  36.                     throw;  
  37.                 }  
  38.             }  
  39.             return StatusCode(HttpStatusCode.NoContent);  
  40.         }  
  41.         //Function to check whether company is exhis or not  
  42.         private bool companyExists(int id)  
  43.         {  
  44.             return db.company.Count(e => e.cid == id) > 0;  
  45.         }  
  46.     }  

Theew is another method in this controller called companyExhists(). It will check the id value to ensure that the data is present in the database.

Fine, now we will implement the client application, have a look at the following example. At first we replicate the same class that is created by Entity Framework in the Web API end.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using ClassLibrary;  
  7. using System.Threading;  
  8. using System.Net.Http;  
  9. using System.Net.Http.Headers;  
  10. using System.Net.Http.Formatting;  
  11. using Newtonsoft.Json;  
  12.   
  13. namespace ConsoleAPP  
  14. {  
  15.     public class companyEntity  
  16.     {  
  17.         public int c_id { getset; }  
  18.         public string company_name { getset; }  
  19.   
  20.     }  
  21.     class Program  
  22.     {  
  23.         static void Main(string[] args)  
  24.         {  
  25.             using (var client = new HttpClient())  
  26.             {  
  27.                 companyEntity c = new companyEntity {c_id =3, company_name = "IBM" };  
  28.   
  29.                 client.BaseAddress = new Uri("http://localhost:1565/");  
  30.                 var response = client.PutAsJsonAsync("api/AsyncPerson/3",c).Result;  
  31.                 var data = response.Content;  
  32.   
  33.                 if (response.IsSuccessStatusCode)  
  34.                 {  
  35.                     Task<string> d = data.ReadAsStringAsync();  
  36.                     Console.Write(d.Result.ToString());  
  37.                 }  
  38.                   
  39.                 Console.ReadLine();  
  40.             }  
  41.         }  
  42.     }  

Then we are using the PutAsJsonAsync() function to invoke the Put() method of the controller and if everything is fine then we will see the changed value in the DB.



We will now do the Delete operation in the DB using the Entity Framework asynchronously in the Web API. So, let's implement the Web API at first. Here is a simple Delete method that will take an Id as a parameter from the client end and dp a delete in the database asynchronously. After successful deletion of a record we would like to display the deleted row in the client end.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Http;  
  6. using System.Web.Mvc;  
  7. using System.Threading.Tasks;  
  8. using System.Web.Http.Description;  
  9. using System.Data.Entity.Infrastructure;  
  10. using System.Net;  
  11. namespace WebAPI.Controllers  
  12. {  
  13.     public class AsyncPersonController : ApiController  
  14.     {  
  15.         private efDBEntities db = new efDBEntities();  
  16.   
  17.         [ResponseType(typeof(company))]  
  18.         public async Task<IHttpActionResult> Deletecompany([FromUri] int id)  
  19.         {  
  20.             company company = await db.company.FindAsync(id);  
  21.             if (company == null)  
  22.             {  
  23.                 return NotFound();  
  24.             }  
  25.   
  26.             db.company.Remove(company);  
  27.             await db.SaveChangesAsync();  
  28.             return Ok(company);  
  29.         }  
  30.   
  31.     }  

Fine, here is the client code that will invoke the Web API by passing a key value through the URL.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using ClassLibrary;  
  7. using System.Threading;  
  8. using System.Net.Http;  
  9. using System.Net.Http.Headers;  
  10. using System.Net.Http.Formatting;  
  11. using Newtonsoft.Json;  
  12.   
  13. namespace ConsoleAPP  
  14. {  
  15.     public class companyEntity  
  16.     {  
  17.         public int c_id { getset; }  
  18.         public string company_name { getset; }  
  19.   
  20.     }  
  21.     class Program  
  22.     {  
  23.         static void Main(string[] args)  
  24.         {  
  25.             using (var client = new HttpClient())  
  26.             {  
  27.                 companyEntity c = new companyEntity {c_id =3, company_name = "IBM" };  
  28.   
  29.                 client.BaseAddress = new Uri("http://localhost:1565/");  
  30.                 var response = client.DeleteAsync("api/AsyncPerson/3").Result;  
  31.                 var data = response.Content;  
  32.   
  33.                 if (response.IsSuccessStatusCode)  
  34.                 {  
  35.                     Task<string> d = data.ReadAsStringAsync();  
  36.                     Console.WriteLine("The deleted record is");  
  37.                     Console.Write(d.Result.ToString());  
  38.                 }  
  39.                   
  40.                 Console.ReadLine();  
  41.             }  
  42.         }  
  43.     }  

This is the status of the current database and since we will pass a key value of 3, the company_name “IBM” will be deleted.



If we run the application then we will see that the record is showing in the client end that has benn deleted from the Database.



If we now check the Database then we will see the record has been deleted from the Database.



Thanks to be with the series. This is the last article of the series and I hope you have enjoyed it. Stay with us for more articles on .NET technology. Happy learning and have a nice day.


Similar Articles