In this blog, we will perform Web API CRUD operations using Entity Framework and ASP.Net MVC.
What is ASP.Net Web API?
Web API is the Microsoft open source technology for developing REST services based on HTTP protocol. ASP.Net Web API is a framework for building, consuming HTTP based services. The advantage of Web API is that it can be consumed by a wide range of clients like a web browser and mobile applications.
What is Entity Framework?
Entity Framework is an object-relational mapping that allows developers to work with relational databases. Entity Framework is an open-source framework. Read More…
You may read more on MVC, Web API and Angular |
Follow the below steps to create a Web API project in Visual Studio 2017
Let’s open the Visual Studio 2017 and start the demonstration.
First, create a Web API project in Visual Studio 2017.
Add ADO.Net Entity Data Model to this project.
To do this follow the below steps.
![Web API2 CRUD operations using Entity Framework and MVC Web API2 CRUD operations using Entity Framework and MVC](https://1.bp.blogspot.com/-x770uUPQvyM/W9eqN9sNnwI/AAAAAAAAB5g/sTu2_q8-xxUPW6qC5V_KxyiKyXYYwBOEwCLcBGAs/s1600/image001.png)
Select Approach.
![Web API2 CRUD operations using Entity Framework and MVC Web API2 CRUD operations using Entity Framework and MVC](https://4.bp.blogspot.com/-_uFfaTh-pv0/W9eqOcjV0EI/AAAAAAAAB5k/_JS1fCDoMvEjcJ-dqy-saeexPZRrs1nywCLcBGAs/s1600/image003.png)
Set the connection string.
![Web API2 CRUD operations using Entity Framework and MVC Web API2 CRUD operations using Entity Framework and MVC](https://4.bp.blogspot.com/-9mToHaTPJO4/W9eqOWSE9lI/AAAAAAAAB5o/2a5HHAO7bYQ0aLvDeJyWt_KSJtYzUr5RgCLcBGAs/s1600/image004.png)
Select the Entity Framework version.
Select a database object you want to use.
I am selecting ProductMaster table as I will demonstrate CRUD operation for the Product Table.
![Web API2 CRUD operations using Entity Framework and MVC Web API2 CRUD operations using Entity Framework and MVC](https://4.bp.blogspot.com/-BQZpaXKVBYQ/W9eqPWR6NUI/AAAAAAAAB5w/JBVrHJXIX3wjjtwgJ09kig__4BCwrpzGgCLcBGAs/s1600/image006.png)
![](https://3.bp.blogspot.com/-_Igee4LZzls/W9fzgJ1Df0I/AAAAAAAAB8c/7c46z5ZqmAYnXZTB8DE0Gx_vPS5RSq9UACLcBGAs/s1600/image007.png)
Create Web API 2 Project
![Web API2 CRUD operations using Entity Framework and MVC Web API2 CRUD operations using Entity Framework and MVC](https://1.bp.blogspot.com/-Cn8gXysw1cM/W9eqQHhdigI/AAAAAAAAB54/Xe7ZU3K77Nw_bdmKgegpqeG3Rd5QlJRCQCLcBGAs/s1600/image009.png)
Select Model Class from dropdown and Data Context class as shown below.
![Web API2 CRUD operations using Entity Framework and MVC Web API2 CRUD operations using Entity Framework and MVC](https://3.bp.blogspot.com/-RjzaTDubHkw/W9eqQNN4oCI/AAAAAAAAB58/2LbUcQ346UYiAv4Gy0J-Dfd7q2RNVc_YwCLcBGAs/s1600/image011.png)
![](https://4.bp.blogspot.com/-L9_3bctLbWw/W9eqQhaaMBI/AAAAAAAAB6A/4hmWMRRB69k1wUuIJDMN0eORy4G-bnWZwCLcBGAs/s1600/image012.png)
WebAPI2 controller code will look like this.
namespace WebAPI2Demo.Controllers { public class ProductMastersController : ApiController { private ReviewAndShareEntities db = new ReviewAndShareEntities(); // GET: api/ProductMasters public IQueryable<ProductMaster> GetProductMasters() { return db.ProductMasters; } // GET: api/ProductMasters/5 [ResponseType(typeof(ProductMaster))] public IHttpActionResult GetProductMaster(int id) { ProductMaster productMaster = db.ProductMasters.Find(id); if (productMaster == null) { return NotFound(); } return Ok(productMaster); } // PUT: api/ProductMasters/5 [ResponseType(typeof(void))] public IHttpActionResult PutProductMaster(int id, ProductMaster productMaster) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (id != productMaster.id) { return BadRequest(); } db.Entry(productMaster).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!ProductMasterExists(id)) { return NotFound(); } else { throw; } } return StatusCode(HttpStatusCode.NoContent); } // POST: api/ProductMasters [ResponseType(typeof(ProductMaster))] public IHttpActionResult PostProductMaster(ProductMaster productMaster) { if (!ModelState.IsValid) { return BadRequest(ModelState); } db.ProductMasters.Add(productMaster); db.SaveChanges(); return CreatedAtRoute(“DefaultApi”, new { id = productMaster.id }, productMaster); } // DELETE: api/ProductMasters/5 [ResponseType(typeof(ProductMaster))] public IHttpActionResult DeleteProductMaster(int id) { ProductMaster productMaster = db.ProductMasters.Find(id); if (productMaster == null) { return NotFound(); } db.ProductMasters.Remove(productMaster); db.SaveChanges(); return Ok(productMaster); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } private bool ProductMasterExists(int id) { return db.ProductMasters.Count(e => e.id == id) > 0; } } } |
Host your web API in IIS and test.
Open IIS and Add Website…
![](https://3.bp.blogspot.com/-yKYiCBuIZgg/W9fzlyDpA6I/AAAAAAAAB8g/8-qyaWg4PkEQUgkj_FZ15izngfHlMcPqACLcBGAs/s1600/image013.png)
![Web API2 CRUD operations using Entity Framework and MVC Web API2 CRUD operations using Entity Framework and MVC](https://1.bp.blogspot.com/-mby03hxwEZw/W9eqRCFbGzI/AAAAAAAAB6I/SZvVjRUHWSMTrTVcX1ZNvzqJlDU553_0gCLcBGAs/s1600/image015.png)
![](https://4.bp.blogspot.com/-FQREiP9qffc/W9fzrNHvfrI/AAAAAAAAB8k/hTAOOTlk0zwX3_P90Fi3zXBuvicCTRRuQCLcBGAs/s640/image016.png)
Access the URL, you will see the result in XML format as shown below.
![](https://1.bp.blogspot.com/-MCdHm5VwL58/W9fzw9XQ9rI/AAAAAAAAB8s/qVcGSb7lMnAdnA2MHO_XPlUjzlP3hs3PwCLcBGAs/s640/image020.png)
To get a particular record, use below URL.
/api/ProductMastsers/<id>
![](https://3.bp.blogspot.com/-lJqnxGqgP14/W9fz1USujzI/AAAAAAAAB8w/MvX-xkrznrkczFI9tn3ObSVP4bNUoviegCLcBGAs/s640/image022.png)
![](https://3.bp.blogspot.com/-G-JN5CU-3XA/W9fz9fIiLzI/AAAAAAAAB84/preXQu0a4kMo4KXyPQ_gs8hoKGu9gOqBgCLcBGAs/s640/image024.png)
![Web API2 CRUD operations using Entity Framework and MVC Web API2 CRUD operations using Entity Framework and MVC](https://1.bp.blogspot.com/-AGY-xgdP4ko/W9eqTfiCa3I/AAAAAAAAB6c/KkBHTxT1FmUlGULLT-QZ7NihVS5IxSeTgCLcBGAs/s1600/image026.png)
Select MVC from Project template.
![Web API2 CRUD operations using Entity Framework and MVC Web API2 CRUD operations using Entity Framework and MVC](https://3.bp.blogspot.com/-GCeEEXkovFM/W9eqTcf8HEI/AAAAAAAAB6g/A3w2q0nkQWM-Si4gEH4JriaJHVhDqZhgQCLcBGAs/s1600/image028.png)
![Web API2 CRUD operations using Entity Framework and MVC Web API2 CRUD operations using Entity Framework and MVC](https://1.bp.blogspot.com/-wED2J_nH-2I/W9eqUKnTQjI/AAAAAAAAB6k/-AqSTy78sF4WcrRGAI8fn9oYRJyyAG6QwCLcBGAs/s1600/image030.png)
ProductModel class.
public class ProductModel { public int id { get; set; } public string product { get; set; } public decimal cost { get; set; } public int stock { get; set; } } |
![Web API2 CRUD operations using Entity Framework and MVC Web API2 CRUD operations using Entity Framework and MVC](https://3.bp.blogspot.com/-05lIJ1CWcFA/W9eqUtjIbbI/AAAAAAAAB6s/EcgfjQkRHUQrIdvwe3ap5GmGhy4m1nC_gCLcBGAs/s1600/image032.png)
Index View to show Product List.
@model IEnumerable<WebAPI2Consumer.Models.ProductModel> @{ ViewBag.Title = “Index”; } <h2>Index</h2> <p> @Html.ActionLink(“Create New”, “Create”) </p> <table class=”table”> <tr> <th> @Html.DisplayNameFor(model => model.product) </th> <th> @Html.DisplayNameFor(model => model.cost) </th> <th> @Html.DisplayNameFor(model => model.stock) </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.product) </td> <td> @Html.DisplayFor(modelItem => item.cost) </td> <td> @Html.DisplayFor(modelItem => item.stock) </td> <td> @Html.ActionLink(“Edit”, “Edit”, new { id=item.id }) | @Html.ActionLink(“Details”, “Details”, new { id=item.id }) | @Html.ActionLink(“Delete”, “Delete”, new { id=item.id }) </td> </tr> } </table> |
In order to create a Web API client.
Add Microsoft.AspNet.Webapi.Client using NuGet package manager.
![](https://1.bp.blogspot.com/-E4TgzBaHfcY/W9f0GM9j_VI/AAAAAAAAB9E/NUXtbz_gaiQITXkN6fYv2KnspRsmvNuWwCLcBGAs/s1600/image033.png)
![](https://4.bp.blogspot.com/-jWs-Ab35gNs/W9f0MVnsRRI/AAAAAAAAB9I/euEmsnsJV68wFn9TIy0Ixs2-ztPBZIQyACEwYBhgL/s1600/image034.png)
![Web API2 CRUD operations using Entity Framework and MVC Web API2 CRUD operations using Entity Framework and MVC](https://4.bp.blogspot.com/-V6-coGf2_MY/W9eqV5dpAkI/AAAAAAAAB60/fN0LdCtYrbko5ctFWy5QgE4EoteWC0ILQCLcBGAs/s1600/image036.png)
![Web API2 CRUD operations using Entity Framework and MVC Web API2 CRUD operations using Entity Framework and MVC](https://3.bp.blogspot.com/-2VhK6sq5Mr0/W9eqWA6_ZaI/AAAAAAAAB64/2IdyetAFvUA8A8cvWJW8Ff25YxST5osQACLcBGAs/s1600/image037.png)
Host your MVC project in IIS.
Open IIS and Add a new website.
![Web API2 CRUD operations using Entity Framework and MVC Web API2 CRUD operations using Entity Framework and MVC](https://4.bp.blogspot.com/-xVSyQnNbQJM/W9eqW1rOQLI/AAAAAAAAB7E/h5Ph0_QaY04xR491CPl9QJ0ZrLTh2CLwACLcBGAs/s1600/image039.png)
If you don’t want to host your application and web API in IIS.
Right-click on Solution name in visual studio 2017 solution explorer and select properties.
Set Multiple startup projects for Web API and MVC project i.e. Web API consumer.
![Web API2 CRUD operations using Entity Framework and MVC Web API2 CRUD operations using Entity Framework and MVC](https://2.bp.blogspot.com/-r_aPIEKieNQ/W9eqW0FuCgI/AAAAAAAAB7A/aVseXsDZJqILzExyrxbkqESV2ngHs1igQCLcBGAs/s1600/image040.png)
public class ProductController : Controller { public static HttpClient webClient = new HttpClient(); // GET: Product public ActionResult Index() { IEnumerable<ProductModel> products; HttpResponseMessage webResponse = webClient.GetAsync(“http://localhost:90/api/ProductMasters”).Result; products = webResponse.Content.ReadAsAsync<IEnumerable<ProductModel>>().Result; return View(products); } } |
![Web API2 CRUD operations using Entity Framework and MVC Web API2 CRUD operations using Entity Framework and MVC](https://3.bp.blogspot.com/-uqaMbCMX6sQ/W9eqXXd0zoI/AAAAAAAAB7I/POlD0ilb9i4aZ1KH8MACUs89dRoY6DkCACLcBGAs/s1600/image042.png)
![Web API2 CRUD operations using Entity Framework and MVC Web API2 CRUD operations using Entity Framework and MVC](https://3.bp.blogspot.com/-Abx01DeXXgY/W9eqX6_OWdI/AAAAAAAAB7M/_JyssbIKv0AoglqJqNyGS1SrFp9pdjv8QCLcBGAs/s1600/image043.png)
Now click on Create New link on the Product list view Page.
public ActionResult Create() { return View(); } [HttpPost] public ActionResult Create(ProductModel productModel) { HttpResponseMessage httpResponseMessage = webClient.PostAsJsonAsync(“http://localhost:90/api/ProductMasters”, productModel).Result; return View(); } |
![Web API2 CRUD operations using Entity Framework and MVC Web API2 CRUD operations using Entity Framework and MVC](https://1.bp.blogspot.com/-co3v4O2oESE/W9eqX5s5XBI/AAAAAAAAB7Q/XwZWWNkOjGUbx_UPGSiTexh2VD_Bt0EtACLcBGAs/s1600/image044.png)
![Web API2 CRUD operations Web API2 CRUD](https://2.bp.blogspot.com/-u6uY_2KvKWY/W9eqYRtYYKI/AAAAAAAAB7U/ipAYr5BHfg0MCClN7mV9b0MNSuTnp_63gCLcBGAs/s1600/image045.png)
![Web API2 CRUD operations using Entity Framework Web API2 CRUD operations using Entity Framework](https://4.bp.blogspot.com/-in1296Rp-OE/W9eqY8ejCZI/AAAAAAAAB7Y/SlgxI2yGdE0xLabEE09p_-xax5iC6MC0ACLcBGAs/s1600/image046.png)
public ActionResult Edit() { return View(); } [HttpPost] public ActionResult Edit(ProductModel productModel) { HttpResponseMessage httpResponseMessage = webClient.PutAsJsonAsync(“http://localhost:90/api/ProductMasters/” + productModel.id, productModel).Result; return View(); } |
![Web API2 CRUD operations using Entity Framework and MVC Web API2 CRUD operations using Entity Framework and MVC](https://2.bp.blogspot.com/-mNSl156ecwo/W9eqY0xNKXI/AAAAAAAAB7c/1h1fF2Pe3ecs9T03VTI9bwcVXF_a_XnDgCLcBGAs/s1600/image047.png)
![Web API2 CRUD operations using Entity Framework and MVC Web API2 CRUD operations using Entity Framework and MVC](https://4.bp.blogspot.com/-GwuQXrOkjvE/W9eqZe99mHI/AAAAAAAAB7g/HQ5juhEIUvwOxbC64L-ulAlTXZ7IB1FWACLcBGAs/s1600/image048.png)
public ActionResult Delete(int id) { HttpResponseMessage httpResponseMessage = webClient.DeleteAsync(“http://localhost:90/api/ProductMasters/” + id).Result; return View(); } |
![Web API2 CRUD operations using Entity Framework and MVC Web API2 CRUD operations using Entity Framework and MVC](https://3.bp.blogspot.com/-iAcijYZUeNQ/W9eqaIHWEcI/AAAAAAAAB7k/5j-C_B3x0NYTMFj7vTslb0_TFlgsy8a2wCLcBGAs/s1600/image049.png)
@model WebAPI2Consumer.Models.ProductModel @{ ViewBag.Title = “Delete”; } <h2>Delete</h2> <div> <h4>ProductModel</h4> <hr /> <h2>Record Deleted Successfully</h2> @using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class=”form-actions no-color”> @Html.ActionLink(“Back to List”, “Index”) </div> } </div> |
To view the details of a particular record, we need a separate action.
public ActionResult Details(int id) { HttpResponseMessage httpResponse = webClient.GetAsync(“http://localhost:90/api/ProductMasters/” + id).Result; return View(httpResponse.Content.ReadAsAsync<ProductModel>().Result); } |
![Web API2 CRUD operations Web API2 CRUD operations using Entity Framework and MVC](https://1.bp.blogspot.com/-ZZvBqQbGEJQ/W9eqaMTsWBI/AAAAAAAAB8E/i73dLHXRjbYTY__3gFFzyV5W0kMaCCG9ACEwYBhgL/s1600/image050.png)
Click on the Details link, you will see the details of that record.