In the below image, you can see that the connection was successfully created.
Step 7
Now, select the table(s) which are needed to be configured with our application through Entity Framework and click Finish.
Step 8
Now, you can see in the below image that the EntityModels are configured with Classes, Properties, DataContext and etc. If you have more than one table, you can easily see the tables with relationships in a .exmx diagram. Here, we have one table only, so there is no possibility to see that.
Implement WEB API scaffolding with Entity Framework
What is Scaffolding?
This option is enabled from Visual Studio 2013 for MVC and Web-API. Scaffolding generates the code automatically for CRUD operations, here we will use the WEB API scaffolding with Entity Framework to create Dynamic code for doing create, read, update, and delete. We will see one by one of the following steps for better understanding.
Step 1 Create Controller
Right click on Controllers folder under your project-> select Add-> Controller
Step 2
To implement scaffolding Select "Web API 2 Controller with actions, using Entity Framework" and click add
Step 3
Name the Controller->Select the Models->Select Data context->and click add
You will fall into the below error if you did not rebuild your project after completion database first approach,
So now rebuilding the project and repeat the steps of creating controller and scaffolding.
After completion of step 3 by clicking the Add button, it will start the Scaffolding process
Step 4
In the below image you can see that CRUDController is created with Get, Put, Post, Delete, Dispose and IsExists Action method with Logics.
Generated Codes
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Data.Entity;
- using System.Data.Entity.Infrastructure;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Web.Http;
- using System.Web.Http.Description;
- using WEB_API_CRUD_Logics.Models;
- namespace WEB_API_CRUD_Logics.Controllers {
- public class CRUDController: ApiController {
- private CSharpCornerEntities db = new CSharpCornerEntities();
-
- public IQueryable < Employee > GetEmployees() {
- return db.Employees;
- }
-
- [ResponseType(typeof(Employee))]
- public IHttpActionResult GetEmployee(long id) {
- Employee employee = db.Employees.Find(id);
- if (employee == null) {
- return NotFound();
- }
- return Ok(employee);
- }
-
- public IHttpActionResult PutEmployee(long id, Employee employee) {
- if (!ModelState.IsValid) {
- return BadRequest(ModelState);
- }
- if (id != employee.ID) {
- return BadRequest();
- }
- db.Entry(employee).State = EntityState.Modified;
- try {
- db.SaveChanges();
- } catch (DbUpdateConcurrencyException) {
- if (!EmployeeExists(id)) {
- return NotFound();
- } else {
- throw;
- }
- }
- return StatusCode(HttpStatusCode.NoContent);
- }
-
- [ResponseType(typeof(Employee))]
- public IHttpActionResult PostEmployee(Employee employee) {
- if (!ModelState.IsValid) {
- return BadRequest(ModelState);
- }
- db.Employees.Add(employee);
- db.SaveChanges();
- return CreatedAtRoute("DefaultApi", new {
- id = employee.ID
- }, employee);
- }
-
- [ResponseType(typeof(Employee))]
- public IHttpActionResult DeleteEmployee(long id) {
- Employee employee = db.Employees.Find(id);
- if (employee == null) {
- return NotFound();
- }
- db.Employees.Remove(employee);
- db.SaveChanges();
- return Ok(employee);
- }
- protected override void Dispose(bool disposing) {
- if (disposing) {
- db.Dispose();
- }
- base.Dispose(disposing);
- }
- private bool EmployeeExists(long id) {
- return db.Employees.Count(e => e.ID == id) > 0;
- }
- }
- }
Now Rebuild and Run your application, we might get the below error if we did not enable directory browse in IIS or in our application
HTTP Error 403.14 - Forbidden
We can overcome this HTTP Error 403.14- Forbidden in two ways
- Enable directoryBrowse in WebCofing system.webServer
- Enable in IIS
Enable directoryBrowse in WebCofing system.webServer
Goto your Web API project->Open the WebConfig file and add the below code
- <system.webServer>
- <directoryBrowse enabled="true" />
- </system.webServer>
Enable in IIS
Refer this
Link
Now Run your application, you will get the below error if you are using the Web API template first time or Visual Studio 2013
Could not load file or assembly 'System.Web.Http, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
To overcome this issue update or install below dll from NuGet package
Enabling Cross-Origin Requests in ASP.NET Web API 2
Cross-Origin Resource Sharing (CORS) is a W3C standard that allows a server to relax the same-origin policy. Using CORS, a server can explicitly allow some cross-origin requests while rejecting others. CORS is safer and more flexible than earlier techniques such as JSONP
- Install below dll from NuGet package
- Microsoft.AspNet.WebApi.Cors
And add below code to your WebApiConfig.cs file
- config.EnableCors(new EnableCorsAttribute("*", "*", "GET,PUT,POST,DELETE"));
Complete code of WebApiConfig.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web.Http;
- using System.Web.Http.Cors;
- namespace WEB_API_CRUD_Logics {
- public static class WebApiConfig {
- public static void Register(HttpConfiguration config) {
-
-
- config.MapHttpAttributeRoutes();
- config.Routes.MapHttpRoute(name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new {
- id = RouteParameter.Optional
- });
- config.EnableCors(new EnableCorsAttribute("*", "*", "GET,PUT,POST,DELETE"));
- }
- }
- }
Now run your application, Yes! We got the successful services. We will validate all actions(CRUD) using postman
Attribute Routing
Attribute routing can be thought of as convention based routing. It means the developer can change the route's default pattern to a custom way. Attribute routing is used on the top of an action, controller name in WebAPI and MVC. Here we will see the action based attribute routing. In the below code, you can see that I have created attribute routing on top of the action.
Example [Route("api/GetEmployees")] to get all employees.
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Data.Entity;
- using System.Data.Entity.Infrastructure;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Web.Http;
- using System.Web.Http.Description;
- using WEB_API_CRUD_Logics.Models;
- namespace WEB_API_CRUD_Logics.Controllers {
- public class CRUDController: ApiController {
- private CSharpCornerEntities db = new CSharpCornerEntities();
-
- [ResponseType(typeof(IEnumerable < Employee > ))]
- [Route("api/GetEmployees")]
- public IQueryable < Employee > GetEmployees() {
- return db.Employees;
- }
-
- [ResponseType(typeof(Employee))]
- [Route("api/GetEmployee")]
- public IHttpActionResult GetEmployee(long id) {
- Employee employee = db.Employees.Find(id);
- if (employee == null) {
- return NotFound();
- }
- return Ok(employee);
- }
-
- [Route("api/PutEmployee")]
- public IHttpActionResult PutEmployee(long id, Employee employee) {
- if (!ModelState.IsValid) {
- return BadRequest(ModelState);
- }
- if (id != employee.ID) {
- return BadRequest();
- }
- db.Entry(employee).State = EntityState.Modified;
- try {
- db.SaveChanges();
- } catch (DbUpdateConcurrencyException) {
- if (!EmployeeExists(id)) {
- return NotFound();
- } else {
- throw;
- }
- }
- return StatusCode(HttpStatusCode.NoContent);
- }
-
- [Route("api/PostEmployee")]
- [ResponseType(typeof(Employee))]
- public IHttpActionResult PostEmployee(Employee employee) {
- if (!ModelState.IsValid) {
- return BadRequest(ModelState);
- }
- db.Employees.Add(employee);
- db.SaveChanges();
- return CreatedAtRoute("DefaultApi", new {
- id = employee.ID
- }, employee);
- }
-
- [Route("api/DeleteEmployee")]
- [ResponseType(typeof(Employee))]
- public IHttpActionResult DeleteEmployee(long id) {
- Employee employee = db.Employees.Find(id);
- if (employee == null) {
- return NotFound();
- }
- db.Employees.Remove(employee);
- db.SaveChanges();
- return Ok(employee);
- }
- protected override void Dispose(bool disposing) {
- if (disposing) {
- db.Dispose();
- }
- base.Dispose(disposing);
- }
- [Route("api/EmployeeExists")]
- private bool EmployeeExists(long id) {
- return db.Employees.Count(e => e.ID == id) > 0;
- }
- }
- }
Enable Postman
Postman is a free API debugging tool. Install it for Chrome from
Here. Or visit
Here for others
After successful installation, open it and select HTTP Method and enter the URL of your Web API as shown below.
API URL: http://localhost:54259/
Get Employee List Routing: api/GetEmployees
After Clicked the send button it will make a request to server
And the Result will be
Now we will see how to pass the parameter, for that we will use the api/GetEmployee.
Yeah! we successfully made a WEB API services for CRUD operation. Now the client application can perform the CRUD operation by calling these APIs. In another article, I discussed how to make a standard form of services, the easiest way to make documentation and validate the API using Swagger can be found
Here.
Summary
In this article, you learned to implement CRUD services in ASP.NET WEB API using Entity Framework without writing code and how to use the Postman and also validate the API Services.
I hope it's helpful, your valuable feedback and comments about this article are always welcome.