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.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Http;
- using System.Web.Mvc;
- using System.Threading.Tasks;
- using System.Web.Http.Description;
- using System.Data.Entity.Infrastructure;
- using System.Net;
- namespace WebAPI.Controllers
- {
- public class AsyncPersonController : ApiController
- {
- private efDBEntities db = new efDBEntities();
- public async Task<IHttpActionResult> Putcompany([FromUri] int id, [FromBody] company company)
- {
- if (!ModelState.IsValid)
- {
- return BadRequest(ModelState);
- }
- try
- {
- var tmpCompany = db.company.Where(cn => cn.cid == id).FirstOrDefault();
- tmpCompany.company_name = company.company_name;
- await db.SaveChangesAsync();
- }
- catch (DbUpdateConcurrencyException)
- {
- if (!companyExists(id))
- {
- return NotFound();
- }
- else
- {
- throw;
- }
- }
- return StatusCode(HttpStatusCode.NoContent);
- }
-
- private bool companyExists(int id)
- {
- return db.company.Count(e => e.cid == id) > 0;
- }
- }
- }
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.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using ClassLibrary;
- using System.Threading;
- using System.Net.Http;
- using System.Net.Http.Headers;
- using System.Net.Http.Formatting;
- using Newtonsoft.Json;
-
- namespace ConsoleAPP
- {
- public class companyEntity
- {
- public int c_id { get; set; }
- public string company_name { get; set; }
-
- }
- class Program
- {
- static void Main(string[] args)
- {
- using (var client = new HttpClient())
- {
- companyEntity c = new companyEntity {c_id =3, company_name = "IBM" };
-
- client.BaseAddress = new Uri("http://localhost:1565/");
- var response = client.PutAsJsonAsync("api/AsyncPerson/3",c).Result;
- var data = response.Content;
-
- if (response.IsSuccessStatusCode)
- {
- Task<string> d = data.ReadAsStringAsync();
- Console.Write(d.Result.ToString());
- }
-
- Console.ReadLine();
- }
- }
- }
- }
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.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Http;
- using System.Web.Mvc;
- using System.Threading.Tasks;
- using System.Web.Http.Description;
- using System.Data.Entity.Infrastructure;
- using System.Net;
- namespace WebAPI.Controllers
- {
- public class AsyncPersonController : ApiController
- {
- private efDBEntities db = new efDBEntities();
-
- [ResponseType(typeof(company))]
- public async Task<IHttpActionResult> Deletecompany([FromUri] int id)
- {
- company company = await db.company.FindAsync(id);
- if (company == null)
- {
- return NotFound();
- }
-
- db.company.Remove(company);
- await db.SaveChangesAsync();
- return Ok(company);
- }
-
- }
- }
Fine, here is the client code that will invoke the Web API by passing a key value through the URL.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using ClassLibrary;
- using System.Threading;
- using System.Net.Http;
- using System.Net.Http.Headers;
- using System.Net.Http.Formatting;
- using Newtonsoft.Json;
-
- namespace ConsoleAPP
- {
- public class companyEntity
- {
- public int c_id { get; set; }
- public string company_name { get; set; }
-
- }
- class Program
- {
- static void Main(string[] args)
- {
- using (var client = new HttpClient())
- {
- companyEntity c = new companyEntity {c_id =3, company_name = "IBM" };
-
- client.BaseAddress = new Uri("http://localhost:1565/");
- var response = client.DeleteAsync("api/AsyncPerson/3").Result;
- var data = response.Content;
-
- if (response.IsSuccessStatusCode)
- {
- Task<string> d = data.ReadAsStringAsync();
- Console.WriteLine("The deleted record is");
- Console.Write(d.Result.ToString());
- }
-
- Console.ReadLine();
- }
- }
- }
- }
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.