Scaffolding with Web API - ASP.NET Web API 2: Beginner Guide (2015)

ASP.NET Web API 2: Beginner Guide (2015)

Scaffolding with Web API

ASP.NET Scaffolding is a code generation framework for ASP.NET Web applications. Visual Studio includes pre-installed code generators for MVC and Web API projects. Visual Studio automatically generates the API code required to perform various operations on the specified model or data source.

Scaffold on the Entity Framework

To demonstrate how scaffolding works in a Web API project, we can use the Entity Framework to define our database and generate the Web API methods. First, we need to add an ADO.NET entity data model that defines the data.

Add an ADO.NET Entity Data Model to the project using the Add new Item context menu.

image

Figure 7: New ADO.NET Entity Data Model

Select the Empty EF designer model option to define the models using Model First approach.

NOTE: For more details on different entity framework approaches, refer Different Approaches of Entity Framework

image

Figure 8: Empty EF Designer model

Design the models using the Entity Data Model designer. For the sample, use the data model based on two tables, Course and Status, as shown in the next Figure.

image

Figure 9: Adding an entity data model based on the Course and Status tables

After we define the data model, we can generate the Web API controller that corresponds to the model. Rebuild the application to generate the code context corresponding to the EF data model. Right-click Controller and then click Add Controller, which lunches the Add Scaffold dialog box. Select the Web API 2 Controller with actions, using Entity Framework option and click Add.

image

Figure 10: Adding a controller based on the EF data model

This will open the Add Controller window. Select the Course model from the list of available models and select the container corresponding to the course model for Data Context.

image

Figure 11: Add Controller

If you are planning to execute the Web API methods in asynchronous manner, select the Use async controller actions checkbox. Click on Add to add the new Web API controller, courseController based on actions related to the Course model. Same way add the Web API methods for the Status model too.

Listing 6 shows the automatic code generated for the CourseController API controller. Notice that it contains methods to support get, put, post, and delete operations that correspond to the selected model.

Listing 6: Code generated for the CourseController API controller

public class CoursesController : ApiController

{

private ApplicationDbContext db = new ApplicationDbContext();

// GET: api/Courses

public IQueryable<Course> GetCourses()

{

return db.Courses;

}

// GET: api/Courses/5

[ResponseType(typeof(Course))]

public IHttpActionResult GetCourse(int id)

{

Course course = db.Courses.Find(id);

if (course == null)

{

return NotFound();

}

return Ok(course);

}

// PUT: api/Courses/5

[ResponseType(typeof(void))]

public IHttpActionResult PutCourse(int id, Course course)

{

if (!ModelState.IsValid)

{

return BadRequest(ModelState);

}

if (id != course.CourseId)

{

return BadRequest();

}

db.Entry(course).State = System.Data.Entity.EntityState.Modified;

try

{

db.SaveChanges();

}

catch (DbUpdateConcurrencyException)

{

if (!CourseExists(id))

{

return NotFound();

}

else

{

throw;

}

}

return StatusCode(HttpStatusCode.NoContent);

}

// POST: api/Courses

[ResponseType(typeof(Course))]

public IHttpActionResult PostCourse(Course course)

{

if (!ModelState.IsValid)

{

return BadRequest(ModelState);

}

db.Courses.Add(course);

db.SaveChanges();

return CreatedAtRoute("DefaultApi", new { id = course.CourseId }, course);

}

// DELETE: api/Courses/5

[ResponseType(typeof(Course))]

public IHttpActionResult DeleteCourse(int id)

{

Course course = db.Courses.Find(id);

if (course == null)

{

return NotFound();

}

db.Courses.Remove(course);

db.SaveChanges();

return Ok(course);

}

protected override void Dispose(bool disposing)

{

if (disposing)

{

db.Dispose();

}

base.Dispose(disposing);

}

private bool CourseExists(int id)

{

return db.Courses.Count(e => e.CourseId == id) > 0;

}

}

The Web API scaffolding feature reduces the development effort required to generate the API methods necessary to perform CRUD (create, read, update, delete) operations in different models.