ASP.Net Web API Using Entity Framework 6: Day 1

Introduction

There are various types of project templates available in the Visual Studio 2013. The ASP.NET Web API project template is one of them. The following is the list of ASP.NET project templates that are available in Visual Studio 2013:

  • ASP.NET Empty Project Template
  • ASP.NET Web Forms Project Template
  • ASP.NET MVC Project Template
  • ASP.NET Web API Project Template
  • ASP.NET Single Page Application Project Template
  • ASP.NET Facebook Project Template
  • ASP.NET Windows Azure Mobile Services Project Template

If we describe the ASP.NET WEB API, then HTTP is the most powerful platform for creating a Web API. We can broadcast the service and data with the use of the Web API. The use of HTTP is very easy and formative. As we know, every platform can understand the HTTP so that it can be accessible from everywhere like applications created on desktops, mobiles as well as browsers. Therefore, we can say that the ASP.NET Web API is a framework for building Web APIs on top of the .NET Framework.

I am creating an article series in which I am using the ASP.NET Web API 2 that is the latest version of the Web API. We'll create the application using the ASP.NET Web API and use the Entity Framework 6 in the application for communicating with the database. Entity Framework 6 is the latest version of Entity Framework. I am using the latest version of both the oftechnologies, the ASP.NET Web API and the Entity Framework in here.

The ASP.NET Web API Project Template is based on web applications and uses the Single Page Application (SPA) design. SPA design based apps load a single HTML page and then dynamically updates the page. This app communicates with the server using the AJAX requests. While requesting using AJAX, it returns the JSON data that modifies the application user interface.

This article explains:

  • ASP.NET Web API Applications
  • Use of the Entity Framework
  • The ADO.NET Entity Data Model
  • Web API 2 Controllers

Prerequisites

All Project Templates that are defined above run on the Visual Studio 2013. Since we are learning the ASP.NET Web API, we require the following prerequisites:

  • Visual Studio 2013
  • ASP.NET Web API

Getting Started

So, let's proceed with the following sections:

  • Create ASP.NET Web Application
  • Installing Entity Framework
  • Adding ADO.NET Entity Data Model
  • Adding Web API 2 Controller

Create ASP.NET Web Application

In this section, we'll create the ASP.NET Web Application that is based on the Web API project template. Use the following procedure:

Step 1

Open Visual Studio 2013 and click on New Project.

Step 2

Select the ASP.NET Web Application and enter the name for the application.

Creating ASP.NET Web Application

Step 3

In the next One ASP.NET wizard, select the Web API project template.

Web API Project Template

You can see that the Web API and MVC references are added to this project automatically. Leave the Windows Azure section and click on OK.

Visual Studio automatically creates the application in which you can find the Models and Controllers folder are already added.

Installing Entity Framework

We'll work with the latest version of Entity Framework which is Entity Framework version 6. If your app has the EF6 installed already then you can skip this. Otherwise we can easily install this using the NuGet Gallery. Review the following procedure.

Step 1

Open the Package Manager Console from "Tools" -> "NuGet Package Manager" -> "Package Manager Console".

Step 2

Enter the following command to install:

Install-Package EntityFramework

Package Manager Console

As you can see that the EntityFramework 6.1.1 package is installed on the application.

Adding ADO.NET Entity Data Model

In this section, we'll add an ADO.NET Entity Data Model to add a Model. We can create a simple class in here. I have created the database and tables in the back end and now I'll add them in the Models folder using the following procedure.

Step 1

In the Solution Explorer, right-click on the Models folder and go to Add and click on the ADO.NET Entity Data Model.

Adding Enity Data Model

Step 2

Specify the name for the model and click OK.

Specifying Model Name

Step 3

Select the option to generate the database and click on "Next".

Selecting Model Objects

Step 4

Define the connection and specify the connection string name and click on "Next".

Creating Connection in Entity Data Model

Step 5

Select the database objects from the next wizard and click on Finish.

Selecting Database Objects

Now the model has been added to the application. The classes for every table are created in the models folder.

Entity Data Model

Note: I have used the ADO.Net Entity Data Model for working on a model. You can simply add classes to the Models folder.

Adding Web API 2 Controller

So far the model has been added to the application and now we need a Web API Controller to communicate with the model. In this section we'll add the Web API Controller with the Entity Framework. Just use the following procedure.

Step 1

In the Solution Explorer, right-click on the Controllers folder and go to Add and click on Controller.

Adding New Controller

Step 2

In the next Add Scaffold wizard, select the Web API 2 Controller using Entity Framework and click on Add.

Adding Web API 2 EF Controller

Step 3

Define the Model Class and for the Data Context class click on the Add button.

Adding Model Class in Add Controller Wizard

Step 4

Enter the name for new Data Context and click on Add.

Specifying DataContext Class

Step 5

Tick the checkbox for Use async controller actions and click on Add.

Adding Controller

After this, using Scaffolding generates the controller and creates the data context class in the models folder. Have a look:

Solution Explorer

The following is the class structure of Controller Class and Data Context Class.

CollegeDetailsController Class:

  1. using System.Data.Entity;  
  2. using System.Data.Entity.Infrastructure;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Threading.Tasks;  
  6. using System.Web.Http;  
  7. using System.Web.Http.Description;  
  8. using CollegeApp.Models;  
  9.   
  10. namespace CollegeApp.Controllers  
  11. {  
  12.     public class CollegeDetailsController : ApiController  
  13.     {  
  14.         private CollegeDbContext db = new CollegeDbContext();  
  15.   
  16.         // GET: api/CollegeDetails  
  17.         public IQueryable<CollegeDetail> GetCollegeDetails()  
  18.         {  
  19.             return db.CollegeDetails;  
  20.         }  
  21.   
  22.         // GET: api/CollegeDetails/5  
  23.         [ResponseType(typeof(CollegeDetail))]  
  24.         public async Task<IHttpActionResult> GetCollegeDetail(int id)  
  25.         {  
  26.             CollegeDetail collegeDetail = await db.CollegeDetails.FindAsync(id);  
  27.             if (collegeDetail == null)  
  28.             {  
  29.                 return NotFound();  
  30.             }  
  31.   
  32.             return Ok(collegeDetail);  
  33.         }  
  34.   
  35.         // PUT: api/CollegeDetails/5  
  36.         [ResponseType(typeof(void))]  
  37.         public async Task<IHttpActionResult> PutCollegeDetail(int id, CollegeDetail collegeDetail)  
  38.         {  
  39.             if (!ModelState.IsValid)  
  40.             {  
  41.                 return BadRequest(ModelState);  
  42.             }  
  43.   
  44.             if (id != collegeDetail.CollegeID)  
  45.             {  
  46.                 return BadRequest();  
  47.             }  
  48.   
  49.             db.Entry(collegeDetail).State = EntityState.Modified;  
  50.   
  51.             try  
  52.             {  
  53.                 await db.SaveChangesAsync();  
  54.             }  
  55.             catch (DbUpdateConcurrencyException)  
  56.             {  
  57.                 if (!CollegeDetailExists(id))  
  58.                 {  
  59.                     return NotFound();  
  60.                 }  
  61.                 else  
  62.                 {  
  63.                     throw;  
  64.                 }  
  65.             }  
  66.   
  67.             return StatusCode(HttpStatusCode.NoContent);  
  68.         }  
  69.   
  70.         // POST: api/CollegeDetails  
  71.         [ResponseType(typeof(CollegeDetail))]  
  72.         public async Task<IHttpActionResult> PostCollegeDetail(CollegeDetail collegeDetail)  
  73.         {  
  74.             if (!ModelState.IsValid)  
  75.             {  
  76.                 return BadRequest(ModelState);  
  77.             }  
  78.   
  79.             db.CollegeDetails.Add(collegeDetail);  
  80.             await db.SaveChangesAsync();  
  81.   
  82.             return CreatedAtRoute("DefaultApi"new { id = collegeDetail.CollegeID }, collegeDetail);  
  83.         }  
  84.   
  85.         // DELETE: api/CollegeDetails/5  
  86.         [ResponseType(typeof(CollegeDetail))]  
  87.         public async Task<IHttpActionResult> DeleteCollegeDetail(int id)  
  88.         {  
  89.             CollegeDetail collegeDetail = await db.CollegeDetails.FindAsync(id);  
  90.             if (collegeDetail == null)  
  91.             {  
  92.                 return NotFound();  
  93.             }  
  94.   
  95.             db.CollegeDetails.Remove(collegeDetail);  
  96.             await db.SaveChangesAsync();  
  97.   
  98.             return Ok(collegeDetail);  
  99.         }  
  100.   
  101.         protected override void Dispose(bool disposing)  
  102.         {  
  103.             if (disposing)  
  104.             {  
  105.                 db.Dispose();  
  106.             }  
  107.             base.Dispose(disposing);  
  108.         }  
  109.   
  110.         private bool CollegeDetailExists(int id)  
  111.         {  
  112.             return db.CollegeDetails.Count(e => e.CollegeID == id) > 0;  
  113.         }  
  114.     }  

CollegeDbContext Class:

  1. using System.Data.Entity;  
  2.   
  3. namespace CollegeApp.Models  
  4. {  
  5.     public class CollegeDbContext : DbContext  
  6.     {  
  7.         public CollegeDbContext() : base("name=CollegeDbContext")  
  8.         {             
  9.         }  
  10.   
  11.         public System.Data.Entity.DbSet<CollegeApp.Models.CollegeDetail> CollegeDetails { getset; }  
  12.         public System.Data.Entity.DbSet<CollegeApp.Models.Comment> Comments { getset; }      
  13.     }  

That's it in the Day 1 article.

Summary

This article described how to create the ASP.NET Web API application. We learned to add an ADO.NET Entity Data Model and Controller using the Entity Framework in the application. In the next part, we'll perform the operations on the database. Thanks for reading.


Similar Articles