Creating Web API Using Code-First Approach In Entity Framework

In this article, we will create a database with a foreign key constraint (one to many relationship), using Code First technique in an Entity Framework, seed some sample data and return the data, using the Web API.

Before starting, I assume that you have some knowledge of an Entity Framework code first technique, if not you can learn it here.

Entity Framework

Entity Framework is a relational mapper framework. It is an enhancement of ADO.NET, which gives developers an automated mechanism to access and store the data in the database.

Web API

ASP.NET Web API is a framework to build HTTP Service, which reaches a broad range of clients including Browsers and mobile devices.

It is an ideal platform to build RESTtful Services.

Let's start.

WEB API

Take an empty Web API project and name it.

WEB API

Click OK and select the empty template with Web API.

WEB API

This will create an empty project with Web API.

Now, start Package Manager Console.

WEB API

In Package Manger Console, type Install-Package EntityFramework.

WEB API

Once an Entity Framework is installed, type Install-Package Newtonsoft.Json and install it as well.

Note

Newtonsoft.JSON is a framework, which is used to serialize or deserialize the objects in JSON format. For more information, click here.

Now, add a connection string in web.config file, as shown below. 

  1. <connectionStrings>  
  2.     <add connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=TestDatabase;Integrated Security=True" name="DefaultConnection" providerName="System.Data.SqlClient" />  
  3.   </connectionStrings>   

Note

When an Application will run for first time, you can see the database in SQL Server Object Explorer under MSSQLLocalDB>Database>TestDatabase.

Now, add a class file in Models folder.

WEB API

Name it as entites.cs.

WEB API

Now, replace the code of Entites.cs class with the code given below. 

  1. using System.Collections.Generic;  
  2. using System.ComponentModel.DataAnnotations;  
  3.    
  4. namespace Test.Models  
  5. {  
  6.     public class Country  
  7.     {  
  8.         [Key]  
  9.         public int CountryId { get; set; }  
  10.         public string Name { get; set; }  
  11.         public List<State> State { get; set; }  
  12.     }  
  13.    
  14.     public class State  
  15.     {  
  16.         [Key]  
  17.         public int StateId { get; set; }  
  18.         public string Name { get; set; }  
  19.         public List<City> City { get; set; }  
  20.         //Adding Foreign Key constraints for country  
  21.         public int CountryId { get; set; }  
  22.         public Country Country { get; set; }  
  23.     }  
  24.    
  25.     public class City  
  26.     {  
  27.         [Key]  
  28.         public int CityId { get; set; }  
  29.         public string Name { get; set; }  
  30.         //Adding Foreign Key Constraints for State  
  31.         public int StateId { get; set; }  
  32.         public State State { get; set; }  
  33.     }  
  34. }   

Note

[Key] defines the Primary key and Table

public int StateId { get; set; } Defines the Foreign Key

public State State { get; set; } Show the relation.

Now, add a folder in root directory and name it as Context.

WEB API

Now, add DatabaseContext.cs class. In context folder, replace the code with the code given below. 

  1. using System.Data.Entity;  
  2. using Test.Models;  
  3.    
  4. namespace Test.Context  
  5. {  
  6.     public class DatabaseContext : DbContext  
  7.     {  
  8.         public DatabaseContext() : base("DefaultConnection") { }  
  9.    
  10.         public DbSet<Country> Countries { get; set; }  
  11.         public DbSet<State> States { get; set; }  
  12.         public DbSet<City> Cities { get; set; }  
  13.     }  
  14. }   

DatabaseContext extends DbContext class. This is the main class, which implements all Entity Framework functionality. For more information about DbContext, read this.

Each DbSet<T> represents a table in the database.

Now, add a class in Context folder and name it as DatabaseInitializer.cs.

WEB API

Now, replace the code of DatabaseInitializer.cs clsass with the code given below. 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data.Entity;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using Test.Models;  
  7.    
  8. namespace Test.Context  
  9. {  
  10.     public class DatabaseInitializer : DropCreateDatabaseIfModelChanges<DatabaseContext>  
  11.     {  
  12.         protected override void Seed(DatabaseContext context)  
  13.         {  
  14.             base.Seed(context);  
  15.    
  16.             var cityInMaharashtra = new List<City> {  
  17.                 new City {Name="Mumbai" },  
  18.                                 new City {Name= "Pune" }  
  19.             };  
  20.             var cityInUttarPradesh = new List<City> {  
  21.                 new City {Name="Lucknow" },  
  22.                                 new City {Name="Banaras" }  
  23.             };  
  24.             var cityInTamilnadu = new List<City> {  
  25.                 new City {Name="Bangaluru" },  
  26.                                 new City {Name="Chennai" }  
  27.             };  
  28.             var cityInUttaranchal = new List<City> {  
  29.                 new City {Name="Dehradun" },  
  30.                                 new City {Name="Rishikesh" }  
  31.             };  
  32.             var cityInPanjab = new List<City> {  
  33.                 new City {Name="Chandigarh" },  
  34.                                 new City {Name="Ludhiana" }  
  35.             };  
  36.             var stateInIndia = new List<State> {  
  37.                 new State {  
  38.                     Name="Maharashtra",City=cityInMaharashtra  
  39.                 },  
  40.                 new State {  
  41.                     Name="Uttar Pradesh",City=cityInUttarPradesh  
  42.                 },  
  43.                 new  State {  
  44.                     Name="Tamil nadu",City=cityInTamilnadu  
  45.                 },  
  46.                 new  State {  
  47.                     Name="Uttaranchal",City=cityInUttaranchal  
  48.                 },  
  49.                 new  State {  
  50.                     Name="Panjab",City=cityInPanjab  
  51.                 }  
  52.             };  
  53.             Country country = new Country  
  54.             {  
  55.                 Name = "India",  
  56.                 State = stateInIndia  
  57.             };  
  58.             context.Countries.Add(country);  
  59.             context.SaveChanges();  
  60.         }  
  61.     }  
  62. }   

This file has some sample data inside the seed Method. When the application runs for the first time, Code First Migration will create tables specified in DatabaseContext class and the data from seed method will be inserted.

DatabaseInitializer.cs will be called in Application_Start() function in global.asax file, as shown below. 

  1. using System.Web.Http;  
  2. using Test.Context;  
  3.    
  4. namespace Test  
  5. {  
  6.     public class WebApiApplication : System.Web.HttpApplication  
  7.     {  
  8.         protected void Application_Start()  
  9.         {  
  10.             GlobalConfiguration.Configure(WebApiConfig.Register);  
  11.             System.Data.Entity.Database.SetInitializer(new DatabaseInitializer());  
  12.         }  
  13.     }  
  14. }   

Now, our database design has been done.

Let' create our API to return data in JSON format.

Add a Web API Controller inside controller folder.

WEB API

Name it as DefaultController.

WEB API

Now, replace the DefaultController.cs class code with the code given below. 

  1. using System;  
  2. using System.Linq;  
  3. using System.Web.Http;  
  4. using Test.Context;  
  5.    
  6. namespace Test.Controllers  
  7. {  
  8.     public class DefaultController : ApiController  
  9.     {  
  10.         //Creating Instance of DatabaseContext class  
  11.         private DatabaseContext db = new DatabaseContext();  
  12.    
  13.         //Creating a method to return Json data   
  14.         [HttpGet]  
  15.         public IHttpActionResult Get()  
  16.         {  
  17.             try  
  18.             {  
  19.                 //Prepare data to be returned using Linq as follows  
  20.                 var result = from country in db.Countries  
  21.                              select new {  
  22.                                  country.CountryId,  
  23.                                  country.Name,  
  24.                                  State = from state in db.States  
  25.                                          where state.CountryId==country.CountryId  
  26.                                          select new {  
  27.                                              state.StateId,  
  28.                                              state.Name,  
  29.                                              City=from city in db.Cities  
  30.                                                   where city.StateId==state.StateId  
  31.                                                   select new {  
  32.                                                       city.CityId,  
  33.                                                       city.Name  
  34.                                                   }  
  35.                                          }  
  36.                              };  
  37.                 return Ok(result);  
  38.             }  
  39.             catch (Exception)  
  40.             {  
  41.                 //If any exception occurs Internal Server Error i.e. Status Code 500 will be returned  
  42.                 return InternalServerError();  
  43.             }  
  44.         }  
  45.     }  
  46. }   

The code given above has a Get method, which will be invoked when the user will request the URL given below.

Localhost:3000/api/Default

Note:

  • Port number 3000 is randomly assigned by Visual Studio, so it will be different on your machine.
  • It uses LINQ to an Entity to select the data.

Now, our API is ready but before running, let's change the default behavior of our Application for returning XML data to JSON data in WebApiConfig.cs located under App_Start folder 

  1. using Newtonsoft.Json.Serialization;  
  2. using System.Web.Http;  
  3.    
  4. namespace Test  
  5. {  
  6.     public static class WebApiConfig  
  7.     {  
  8.         public static void Register(HttpConfiguration config)  
  9.         {  
  10.             // Web API configuration and services  
  11.    
  12.             // Web API routes  
  13.             config.MapHttpAttributeRoutes();  
  14.    
  15.             config.Routes.MapHttpRoute(  
  16.                 name: "DefaultApi",  
  17.                 routeTemplate: "api/{controller}/{id}",  
  18.                 defaults: new { id = RouteParameter.Optional }  
  19.             );  
  20.    
  21.             //By default Web API return XML data  
  22.             //We can remove this by clearing the SupportedMediaTypes option as follows  
  23.             config.Formatters.XmlFormatter.SupportedMediaTypes.Clear();  
  24.    
  25.             //Now set the serializer setting for JsonFormatter to Indented to get Json Formatted data  
  26.             config.Formatters.JsonFormatter.SerializerSettings.Formatting =  
  27.                 Newtonsoft.Json.Formatting.Indented;  
  28.    
  29.             //For converting data in Camel Case  
  30.             config.Formatters.JsonFormatter.SerializerSettings.ContractResolver =  
  31.                 new CamelCasePropertyNamesContractResolver();  
  32.         }  
  33.     }  
  34. }   

Now, our API is ready. Let's run.

WEB API

The above error happens because we haven't specified the URL, so add the /api/Default in your browser URL as highlighted

WEB API

Now, our API will return the JSON formatted data with one to many relation.

WEB API

Every country has some sample states, which have their respective cities.

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now